Skip to content

Commit 4da3ea9

Browse files
Cleaning up the tests and adding a Mock object for the urllib_request.urlopen call
1 parent f5c464c commit 4da3ea9

6 files changed

Lines changed: 275 additions & 242 deletions

File tree

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ python:
55
- '3.2'
66
install:
77
- python setup.py install
8-
script: unit2 discover
8+
script: python -m unittest discover
99
notifications:
1010
hipchat:
1111
rooms:

README.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -384,7 +384,7 @@ Tests
384384
virtualenv venv
385385
source venv/bin/activate #or . ./activate.sh
386386
python setup.py install
387-
unit2 discover
387+
python -m unittest discover -v
388388
389389
Deploying
390390
~~~~~~~~~

sendgrid/client.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,24 +67,24 @@ def _build_request(self, url, json_header=False, method='GET', data=None):
6767
except timeout as e:
6868
raise SendGridClientError(408, 'Request timeout')
6969
body = response.read()
70-
return response, body
70+
return response.getcode(), body
7171

7272
def get(self, api):
7373
url = self.host + api.base_endpoint
7474
response, body = self._build_request(url, False, 'GET')
75-
return response.getcode(), body
75+
return response, body
7676

7777
def post(self, api, data):
7878
url = self.host + api.endpoint
7979
response, body = self._build_request(url, True, 'POST', data)
80-
return response.getcode(), body
80+
return response, body
8181

8282
def delete(self, api):
8383
url = self.host + api.endpoint
8484
response, body = self._build_request(url, False, 'DELETE')
85-
return response.getcode(), body
85+
return response, body
8686

8787
def patch(self, api, data):
8888
url = self.host + api.endpoint
8989
response, body = self._build_request(url, True, 'PATCH', data)
90-
return response.getcode(), body
90+
return response, body

test/__init__.py

Lines changed: 0 additions & 235 deletions
Original file line numberDiff line numberDiff line change
@@ -1,236 +1 @@
1-
import os
2-
try:
3-
import unittest2 as unittest
4-
except ImportError:
5-
import unittest
6-
import json
7-
import sys
8-
try:
9-
from StringIO import StringIO
10-
except ImportError: # Python 3
11-
from io import StringIO
121

13-
from sendgrid import SendGridClient, Mail
14-
from sendgrid.exceptions import SendGridClientError, SendGridServerError
15-
from sendgrid.sendgrid import HTTPError
16-
17-
if os.path.exists('.env'):
18-
for line in open('.env'):
19-
var = line.strip().split('=')
20-
if len(var) == 2:
21-
os.environ[var[0]] = var[1]
22-
23-
SG_USER = os.environ.get('SENDGRID_USERNAME') or 'SENDGRID_USERNAME'
24-
SG_PWD = os.environ.get('SENDGRID_PASSWORD') or 'SENDGRID_PASSWORD'
25-
26-
# v3 tests
27-
from sendgrid.client import SendGridAPIClient
28-
from sendgrid.version import __version__
29-
30-
SG_APIKEY = os.environ.get('SENDGRID_API_KEY') or 'SENDGRID_API_KEY'
31-
32-
class TestSendGridAPIClient(unittest.TestCase):
33-
def setUp(self):
34-
self.client = SendGridAPIClient(SG_APIKEY)
35-
36-
def test_apikey_init(self):
37-
self.assertEqual(self.client.apikey, SG_APIKEY)
38-
39-
def test_useragent(self):
40-
useragent = 'sendgrid/' + __version__ + ';python_v3'
41-
self.assertEqual(self.client.useragent, useragent)
42-
43-
def test_host(self):
44-
host = 'https://api.sendgrid.com'
45-
self.assertEqual(self.client.host, host)
46-
47-
"""
48-
class TestAPIKeys(unittest.TestCase):
49-
def setUp(self):
50-
self.client = SendGridAPIClient(SG_APIKEY)
51-
52-
def test_apikey_post_patch_delete_test(self):
53-
name = "My Amazing API Key of Wonder [PATCH Test]"
54-
status, msg = self.client.apikeys.post(name)
55-
self.assertEqual(status, 201)
56-
msg = json.loads(msg)
57-
api_key_id = msg['api_key_id']
58-
self.assertEqual(msg['name'], name)
59-
print status
60-
print msg
61-
62-
name = "My NEW Amazing API Key of Wonder [PATCH TEST]"
63-
status, msg = self.client.apikeys.patch(api_key_id, name)
64-
self.assertEqual(status, 200)
65-
print status
66-
print msg
67-
68-
status, msg = self.client.apikeys.get()
69-
print status
70-
print msg
71-
72-
status, msg = self.client.apikeys.delete(api_key_id)
73-
self.assertEqual(status, 204)
74-
print status
75-
76-
status, msg = self.client.apikeys.get()
77-
print status
78-
print msg
79-
80-
def test_apikey_get(self):
81-
status, msg = self.client.apikeys.get()
82-
self.assertEqual(status, 200)
83-
"""
84-
85-
class TestSendGrid(unittest.TestCase):
86-
87-
def setUp(self):
88-
self.sg = SendGridClient(SG_USER, SG_PWD)
89-
90-
def test_apikey_init(self):
91-
sg = SendGridClient(SG_PWD)
92-
self.assertEqual(sg.password, SG_PWD)
93-
self.assertIsNone(sg.username)
94-
95-
@unittest.skipUnless(sys.version_info < (3, 0), 'only for python2')
96-
def test_unicode_recipients(self):
97-
recipients = [unicode('test@test.com'), unicode('guy@man.com')]
98-
m = Mail(to=recipients,
99-
subject='testing',
100-
html='awesome',
101-
from_email='from@test.com')
102-
103-
mock = {'to[]': ['test@test.com', 'guy@man.com']}
104-
result = self.sg._build_body(m)
105-
106-
self.assertEqual(result['to[]'], mock['to[]'])
107-
108-
def test_send(self):
109-
m = Mail()
110-
m.add_to('John, Doe <john@email.com>')
111-
m.set_subject('test')
112-
m.set_html('WIN')
113-
m.set_text('WIN')
114-
m.set_from('doe@email.com')
115-
m.set_asm_group_id(42)
116-
m.add_cc('cc@email.com')
117-
m.add_bcc('bcc@email.com')
118-
m.add_substitution('subKey', 'subValue')
119-
m.add_section('testSection', 'sectionValue')
120-
m.add_category('testCategory')
121-
m.add_unique_arg('testUnique', 'uniqueValue')
122-
m.add_filter('testFilter', 'filter', 'filterValue')
123-
m.add_attachment_stream('testFile', 'fileValue')
124-
url = self.sg._build_body(m)
125-
url.pop('api_key', None)
126-
url.pop('api_user', None)
127-
url.pop('date', None)
128-
test_url = json.loads('''
129-
{
130-
"to[]": ["john@email.com"],
131-
"toname[]": ["John Doe"],
132-
"html": "WIN",
133-
"text": "WIN",
134-
"subject": "test",
135-
"files[testFile]": "fileValue",
136-
"from": "doe@email.com",
137-
"cc[]": ["cc@email.com"],
138-
"bcc[]": ["bcc@email.com"]
139-
}
140-
''')
141-
test_url['x-smtpapi'] = json.dumps(json.loads('''
142-
{
143-
"sub": {
144-
"subKey": ["subValue"]
145-
},
146-
"section": {
147-
"testSection":"sectionValue"
148-
},
149-
"category": ["testCategory"],
150-
"unique_args": {
151-
"testUnique":"uniqueValue"
152-
},
153-
"filters": {
154-
"testFilter": {
155-
"settings": {
156-
"filter": "filterValue"
157-
}
158-
}
159-
},
160-
"asm_group_id": 42
161-
}
162-
'''))
163-
164-
self.assertEqual(url, test_url)
165-
166-
@unittest.skipUnless(sys.version_info < (3, 0), 'only for python2')
167-
def test__build_body_unicode(self):
168-
"""test _build_body() handles encoded unicode outside ascii range"""
169-
from_email = '\xd0\x9d\xd0\xb8\xd0\xba\xd0\xb0@email.com'
170-
from_name = '\xd0\x9a\xd0\xbb\xd0\xb0\xd0\xb2\xd0\xb4\xd0\xb8\xd1\x8f'
171-
subject = '\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0'
172-
text = '\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0'
173-
html = '\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0'
174-
m = Mail()
175-
m.add_to('John, Doe <john@email.com>')
176-
m.set_subject(subject)
177-
m.set_html(html)
178-
m.set_text(text)
179-
m.set_from("%s <%s>" % (from_name, from_email))
180-
url = self.sg._build_body(m)
181-
self.assertEqual(from_email, url['from'])
182-
self.assertEqual(from_name, url['fromname'])
183-
self.assertEqual(subject, url['subject'])
184-
self.assertEqual(text, url['text'])
185-
self.assertEqual(html, url['html'])
186-
187-
188-
def test_smtpapi_add_to(self):
189-
'''Test that message.to gets a dummy address for the header to work'''
190-
m = Mail()
191-
m.smtpapi.add_to('test@email.com')
192-
m.set_from('jon@doe.com')
193-
m.set_subject('test')
194-
url = self.sg._build_body(m)
195-
url.pop('api_key', None)
196-
url.pop('api_user', None)
197-
url.pop('date', None)
198-
test_url = json.loads('''
199-
{
200-
"to[]": ["jon@doe.com"],
201-
"subject": "test",
202-
"from": "jon@doe.com"
203-
}
204-
''')
205-
test_url['x-smtpapi'] = json.dumps(json.loads('''
206-
{
207-
"to": ["test@email.com"]
208-
}
209-
'''))
210-
self.assertEqual(url, test_url)
211-
212-
213-
214-
class SendGridClientUnderTest(SendGridClient):
215-
216-
def _make_request(self, message):
217-
raise self.error
218-
219-
220-
class TestSendGridErrorHandling(unittest.TestCase):
221-
def setUp(self):
222-
self.sg = SendGridClientUnderTest(SG_USER, SG_PWD, raise_errors=True)
223-
224-
def test_client_raises_clinet_error_in_case_of_4xx(self):
225-
self.sg.error = HTTPError('url', 403, 'msg', {}, StringIO('body'))
226-
with self.assertRaises(SendGridClientError):
227-
self.sg.send(Mail())
228-
229-
def test_client_raises_clinet_error_in_case_of_5xx(self):
230-
self.sg.error = HTTPError('url', 503, 'msg', {}, StringIO('body'))
231-
with self.assertRaises(SendGridServerError):
232-
self.sg.send(Mail())
233-
234-
235-
if __name__ == '__main__':
236-
unittest.main()

test/test_apikeys.py

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import os
2+
try:
3+
import unittest2 as unittest
4+
except ImportError:
5+
import unittest
6+
import json
7+
import sys
8+
try:
9+
from StringIO import StringIO
10+
except ImportError: # Python 3
11+
from io import StringIO
12+
import logging
13+
14+
import sendgrid
15+
from sendgrid import SendGridClient, Mail
16+
from sendgrid.exceptions import SendGridClientError, SendGridServerError
17+
from sendgrid.sendgrid import HTTPError
18+
from sendgrid.client import SendGridAPIClient
19+
from sendgrid.version import __version__
20+
21+
SG_KEY = os.getenv('SG_KEY') or 'SENDGRID_APIKEY'
22+
23+
class MockSendGridAPIClientRequest(SendGridAPIClient):
24+
def _build_request(self, url=None, json_header=False, method='GET', data=None):
25+
response = 200
26+
body = {"message": "success"}
27+
return response, body
28+
29+
class TestSendGridAPIClient(unittest.TestCase):
30+
def setUp(self):
31+
self.client = MockSendGridAPIClientRequest
32+
self.client = SendGridAPIClient(SG_KEY)
33+
34+
def test_apikey_init(self):
35+
self.assertEqual(self.client.apikey, SG_KEY)
36+
37+
def test_useragent(self):
38+
useragent = 'sendgrid/' + __version__ + ';python_v3'
39+
self.assertEqual(self.client.useragent, useragent)
40+
41+
def test_host(self):
42+
host = 'https://api.sendgrid.com'
43+
self.assertEqual(self.client.host, host)
44+
45+
class TestAPIKeys(unittest.TestCase):
46+
def setUp(self):
47+
SendGridAPIClient = MockSendGridAPIClientRequest
48+
self.client = SendGridAPIClient(SG_KEY)
49+
print self.client._build_request(self.client)
50+
51+
def test_apikeys_init(self):
52+
self.apikeys = self.client.apikeys
53+
self.assertEqual(self.apikeys.name, None)
54+
self.assertEqual(self.apikeys.base_endpoint, "/v3/api_keys")
55+
self.assertEqual(self.apikeys.endpoint, "/v3/api_keys")
56+
self.assertEqual(self.apikeys.client, self.client)
57+
58+
def test_apikeys_post(self):
59+
name = "My Amazing API Key of Wonder [PATCH Test]"
60+
status, msg = self.client.apikeys.post(name)
61+
# self.assertEqual(status, 201)
62+
# msg = json.loads(msg)
63+
# api_key_id = msg['api_key_id']
64+
# self.assertEqual(msg['name'], name)
65+
# print status
66+
# print msg
67+
68+
"""
69+
def test_apikey_post_patch_delete_test(self):
70+
name = "My Amazing API Key of Wonder [PATCH Test]"
71+
status, msg = self.client.apikeys.post(name)
72+
self.assertEqual(status, 201)
73+
msg = json.loads(msg)
74+
api_key_id = msg['api_key_id']
75+
self.assertEqual(msg['name'], name)
76+
print status
77+
print msg
78+
79+
name = "My NEW Amazing API Key of Wonder [PATCH TEST]"
80+
status, msg = self.client.apikeys.patch(api_key_id, name)
81+
self.assertEqual(status, 200)
82+
print status
83+
print msg
84+
85+
status, msg = self.client.apikeys.get()
86+
print status
87+
print msg
88+
89+
status, msg = self.client.apikeys.delete(api_key_id)
90+
self.assertEqual(status, 204)
91+
print status
92+
93+
status, msg = self.client.apikeys.get()
94+
print status
95+
print msg
96+
97+
def test_apikey_get(self):
98+
status, msg = self.client.apikeys.get()
99+
self.assertEqual(status, 200)
100+
"""
101+
102+
if __name__ == '__main__':
103+
unittest.main()

0 commit comments

Comments
 (0)