Skip to content

Commit

Permalink
Moving test code around, and adding to the test suite a bit
Browse files Browse the repository at this point in the history
  • Loading branch information
Murray Christopherson committed Apr 10, 2018
1 parent c96462f commit 520eaef
Show file tree
Hide file tree
Showing 5 changed files with 197 additions and 101 deletions.
23 changes: 23 additions & 0 deletions tests/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import os
import sys
import logging

LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO')

_logger = None
def logger():
global _logger

if _logger is None:
_logger = logging.getLogger(__name__)
_logger.setLevel(logging.getLevelName(LOG_LEVEL))

stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setLevel(logging.DEBUG)
stream_handler.setFormatter(
logging.Formatter(
fmt='%(asctime)s (%(levelname)s): %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'))
_logger.addHandler(stream_handler)

return _logger
126 changes: 126 additions & 0 deletions tests/postshift.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import os
import pprint
import time
import six

import requests

from tests.logger import logger

MASHAPE_KEY = os.environ['MASHAPE_KEY']

class PostShift:
ENDPOINT_URL = 'https://reuleaux-post-shift-v1.p.mashape.com/api.php'
REQUEST_INTERVAL = 10.0

@staticmethod
def _headers():
return {
'X-Mashape-Key': MASHAPE_KEY,
'Accept': 'application/json',
}

def __init__(self):
self.email_jsons = []
self.last_request_time = None

def sleep_if_needed(self):
if self.last_request_time is not None:
diff = (time.time() - self.last_request_time)

if diff < PostShift.REQUEST_INTERVAL:
logger().debug('sleeping for %s seconds...', diff)
time.sleep(diff)

def create(self):
self.sleep_if_needed()
self.last_request_time = time.time()
r = requests.get(PostShift.ENDPOINT_URL, params={
'action': 'new',
'type': 'json',
}, headers=PostShift._headers())

_json = r.json()

logger().debug('`create`: %s', pprint.pformat(_json))

if not isinstance(_json, dict):
raise RuntimeError('bad response')

if 'email' not in _json or 'key' not in _json:
raise RuntimeError('bad response')

if not isinstance(_json['email'], six.string_types):
raise RuntimeError('bad response')

if not isinstance(_json['key'], six.string_types):
raise RuntimeError('bad response')

return _json

def get_list(self, email_key):
self.sleep_if_needed()
self.last_request_time = time.time()
r = requests.get(PostShift.ENDPOINT_URL, params={
'action': 'getlist',
'key': email_key,
'type': 'json',
}, headers=PostShift._headers())

_json = r.json()

logger().debug('`get_list`: %s', pprint.pformat(_json))

if not isinstance(_json, list):
raise RuntimeError('bad response')

for e_json in _json:
if not isinstance(e_json, dict):
raise RuntimeError('bad response')

if 'id' not in e_json or 'date' not in e_json or 'subject' not in e_json or 'from' not in e_json:
raise RuntimeError('bad response')

if not isinstance(e_json['id'], int):
raise RuntimeError('bad response')

if not isinstance(e_json['date'], six.string_types):
raise RuntimeError('bad response')

if not isinstance(e_json['subject'], six.string_types):
raise RuntimeError('bad response')

if not isinstance(e_json['from'], six.string_types):
raise RuntimeError('bad response')

return _json

def clear(self, email_key):
self.sleep_if_needed()
self.last_request_time = time.time()
r = requests.get(PostShift.ENDPOINT_URL, params={
'action': 'clear',
'key': email_key,
'type': 'json',
}, headers=PostShift._headers())

_json = r.json()

logger().debug('`clear`: %s', pprint.pformat(_json))

if not isinstance(_json, dict):
raise RuntimeError('bad response')

if 'clear' not in _json or 'key' not in _json:
raise RuntimeError('bad response')

if not isinstance(_json['clear'], six.string_types):
raise RuntimeError('bad response')

if not isinstance(_json['key'], six.string_types):
raise RuntimeError('bad response')

if _json['clear'] != 'ok':
raise RuntimeError('bad response')

return _json
1 change: 0 additions & 1 deletion tests/test_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@


class TestBuilder(unittest.TestCase):
# TODO write test suite
def test_build_msg(self):
msg = builder.build_msg('Test <test@test.com>', 'Example <example@example.com>', None, None, 'The Subject', 'Some Text', '<b>Some Bold Text</b>', attachment_list=None, inline_attachment_dict=None)
self.assertIsNotNone(msg)
Expand Down
39 changes: 39 additions & 0 deletions tests/test_quick_email.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import unittest
import os
import time

from quick_email import send_email

from tests.postshift import PostShift

SMTP_HOST = os.environ['SMTP_HOST']
SMTP_PORT = int(os.environ['SMTP_PORT'])
SMTP_USER = os.environ['SMTP_USER']
SMTP_PASSWORD = os.environ['SMTP_PASSWORD']
SMTP_IS_TLS = os.environ.get('SMTP_IS_TLS') == 'true'
SMTP_SENDER = os.environ['SMTP_SENDER']


class TestQuickEmail(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.postshift = PostShift()

for i in range(6):
cls.postshift.create()

def test_send_email(self):
test_email_json = TestQuickEmail.postshift.email_jsons[0]
send_email(SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, SMTP_IS_TLS, SMTP_SENDER, test_email_json['email'], None, None, 'The Subject', 'Some Text', '<b>Some Bold Text</b>', attachment_list=None, inline_attachment_dict=None)

# wait for email to arrive
time.sleep(30.0)

_json = TestQuickEmail.postshift.get_list(test_email_json['key'])

self.assertIsInstance(_json, list)
self.assertEqual(len(_json), 1)


if __name__ == '__main__':
unittest.main()
109 changes: 9 additions & 100 deletions tests/test_sender.py
Original file line number Diff line number Diff line change
@@ -1,128 +1,37 @@
import unittest
import os
import sys
import logging
import pprint
import time

import requests

from quick_email import builder, sender

from tests.postshift import PostShift

SMTP_HOST = os.environ['SMTP_HOST']
SMTP_PORT = int(os.environ['SMTP_PORT'])
SMTP_USER = os.environ['SMTP_USER']
SMTP_PASSWORD = os.environ['SMTP_PASSWORD']
SMTP_IS_TLS = os.environ.get('SMTP_IS_TLS') == 'true'
SMTP_SENDER = os.environ['SMTP_SENDER']

MASHAPE_KEY = os.environ['MASHAPE_KEY']

LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO')

_logger = None
def logger():
global _logger

if _logger is None:
_logger = logging.getLogger(__name__)
_logger.setLevel(logging.getLevelName(LOG_LEVEL))

stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setLevel(logging.DEBUG)
stream_handler.setFormatter(
logging.Formatter(
fmt='%(asctime)s (%(levelname)s): %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'))
_logger.addHandler(stream_handler)

return _logger


class PostShift:
ENDPOINT_URL = 'https://reuleaux-post-shift-v1.p.mashape.com/api.php'
SLEEP_SECONDS = 10.0

@classmethod
def sleep(cls):
time.sleep(cls.SLEEP_SECONDS)

@classmethod
def create(cls):
r = requests.get(PostShift.ENDPOINT_URL, params={
'action': 'new',
'type': 'json',
}, headers={
'X-Mashape-Key': MASHAPE_KEY,
'Accept': 'application/json',
})

cls.sleep()

_json = r.json()

logger().debug(pprint.pformat(_json))

return _json

@classmethod
def get_list(cls, email_key):
r = requests.get(PostShift.ENDPOINT_URL, params={
'action': 'getlist',
'key': email_key,
'type': 'json',
}, headers={
'X-Mashape-Key': MASHAPE_KEY,
'Accept': 'application/json',
})

cls.sleep()

_json = r.json()

logger().debug(pprint.pformat(_json))

return _json

@classmethod
def clear(cls, email_key):
r = requests.get(PostShift.ENDPOINT_URL, params={
'action': 'clear',
'key': email_key,
'type': 'json',
}, headers={
'X-Mashape-Key': MASHAPE_KEY,
'Accept': 'application/json',
})

cls.sleep()

_json = r.json()

logger().debug(pprint.pformat(_json))

class TestSender(unittest.TestCase):
@classmethod
def setUpClass(cls):
PostShift.sleep()
cls.postshift = PostShift()

_json = PostShift.create()
for i in range(6):
cls.postshift.create()

cls.test_email = _json['email']
cls.postshift_key = _json['key']

def tearDown(self):
PostShift.clear(TestSender.postshift_key)

# TODO write test suite
def test_send_msg(self):
msg = builder.build_msg(SMTP_SENDER, TestSender.test_email, None, None, 'The Subject', 'Some Text', '<b>Some Bold Text</b>', attachment_list=None, inline_attachment_dict=None)
test_email_json = TestSender.postshift.email_jsons[0]

msg = builder.build_msg(SMTP_SENDER, test_email_json['email'], None, None, 'The Subject', 'Some Text', '<b>Some Bold Text</b>', attachment_list=None, inline_attachment_dict=None)
sender.send_msg(SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, SMTP_IS_TLS, SMTP_SENDER, msg)

# wait for email to arrive
time.sleep(30.0)

_json = PostShift.get_list(TestSender.postshift_key)
_json = TestSender.postshift.get_list(test_email_json['key'])

self.assertIsInstance(_json, list)
self.assertEqual(len(_json), 1)
Expand Down

0 comments on commit 520eaef

Please sign in to comment.