Skip to content

Commit 79cc7db

Browse files
Fixing the tests
1 parent bdfc104 commit 79cc7db

15 files changed

+313
-15
lines changed

.env_sample

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
SENDGRID_API_KEY=your_sendgrid_api_key
2+
SENDGRID_USERNAME=your_sendgrid_username
3+
SENDGRID_PASSWORD=your_sendgrid_password

.gitignore

+2-1
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,6 @@ sdist
88
*.egg
99
*.egg-info
1010
*.pyc
11-
.idea/
1211
venv/
12+
.idea
13+
.env

CHANGELOG.md

-4
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
# Change Log
22
All notable changes to this project will be documented in this file.
33

4-
## [1.4.2] - 2015-09-15
5-
### Added
6-
- Upgrade Mail to new-style class, on Python 2.x.
7-
84
## [1.4.1] - 2015-09-09
95
### Added
106
- Classifiers for compatible python versions

README.rst

+3-3
Original file line numberDiff line numberDiff line change
@@ -380,11 +380,11 @@ Tests
380380
~~~~~
381381

382382
.. code:: python
383-
383+
384384
virtualenv venv
385-
source venv/bin/activate
385+
source venv/bin/activate #or . ./activate.sh
386386
python setup.py install
387-
python test/__init__.py
387+
unit2 discover
388388
389389
Deploying
390390
~~~~~~~~~

activate.sh

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#!/bin/bash
2+
# Use this to activate the virtual environment, use the following to execute in current shell
3+
# . ./activate
4+
source venv/bin/activate

example_v2_test.py

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import sendgrid
2+
import os
3+
if os.path.exists('.env'):
4+
for line in open('.env'):
5+
var = line.strip().split('=')
6+
if len(var) == 2:
7+
os.environ[var[0]] = var[1]
8+
9+
sg = sendgrid.SendGridClient(os.environ.get('SENDGRID_USERNAME'), os.environ.get('SENDGRID_PASSWORD'))
10+
11+
message = sendgrid.Mail()
12+
message.add_to('Elmer Thomas <[email protected]>')
13+
message.set_subject('Testing from the Python library')
14+
message.set_html('<b>This was a successful test!</b>')
15+
message.set_text('This was a successful test!')
16+
message.set_from('Elmer Thomas <[email protected]>')
17+
status, msg = sg.send(message)
18+
print status
19+
print msg

example_v3_test.py

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import sendgrid
2+
import json
3+
4+
import os
5+
if os.path.exists('.env'):
6+
for line in open('.env'):
7+
var = line.strip().split('=')
8+
if len(var) == 2:
9+
os.environ[var[0]] = var[1]
10+
11+
client = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
12+
13+
name = "My Amazing API Key"
14+
status, msg = client.apikeys.post(name)
15+
msg = json.loads(msg)
16+
api_key_id = msg['api_key_id']
17+
print status
18+
print msg
19+
20+
name = "My NEW API Key 3000"
21+
status, msg = client.apikeys.patch(api_key_id, name)
22+
print status
23+
print msg
24+
25+
status, msg = client.apikeys.delete(api_key_id)
26+
print status
27+
28+
status, msg = client.apikeys.get()
29+
print status
30+
print msg
31+
32+
"""
33+
# Get a list of all valid API Keys from your account
34+
status, msg = client.apikeys.get()
35+
print status
36+
print msg
37+
38+
# Create a new API Key
39+
name = "My API Key 10"
40+
status, msg = client.apikeys.post(name)
41+
print status
42+
print msg
43+
44+
# Delete an API Key with a given api_key_id
45+
api_key_id = "zc0r5sW5TTuBQGsMPMUx0A"
46+
status, msg = client.apikeys.delete(api_key_id)
47+
print status
48+
print msg
49+
50+
# Update the name of an API Key, given an api_key_id
51+
api_key_id = "API_KEY"
52+
name = "My API Key 3"
53+
status, msg = client.apikeys.patch(api_key_id, name)
54+
print status
55+
print msg
56+
"""

sendgrid/__init__.py

+3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
from .version import __version__
22
from .sendgrid import SendGridClient
33
from .exceptions import SendGridError, SendGridClientError, SendGridServerError
4+
#v2 API
45
from .message import Mail
6+
#v3 API
7+
from .client import SendGridAPIClient

sendgrid/client.py

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import json
2+
from .version import __version__
3+
from socket import timeout
4+
try:
5+
import urllib.request as urllib_request
6+
from urllib.parse import urlencode
7+
from urllib.error import HTTPError
8+
except ImportError: # Python 2
9+
import urllib2 as urllib_request
10+
from urllib2 import HTTPError
11+
from urllib import urlencode
12+
13+
from .exceptions import SendGridClientError, SendGridServerError
14+
from resources.apikeys import APIKeys
15+
16+
class SendGridAPIClient(object):
17+
18+
"""SendGrid API."""
19+
20+
def __init__(self, apikey, **opts):
21+
"""
22+
Construct SendGrid API object.
23+
24+
Args:
25+
apikey: SendGrid API key
26+
opts: You can pass in host or proxies
27+
"""
28+
self._apikey = apikey
29+
self.useragent = 'sendgrid/' + __version__ + ';python_v3'
30+
self.host = opts.get('host', 'https://api.sendgrid.com')
31+
# urllib cannot connect to SSL servers using proxies
32+
self.proxies = opts.get('proxies', None)
33+
34+
self.apikeys = APIKeys(self)
35+
36+
@property
37+
def apikey(self):
38+
return self._apikey
39+
40+
@apikey.setter
41+
def apikey(self, value):
42+
self._apikey = value
43+
44+
def _build_request(self, url, json_header=False, method='GET', data=None):
45+
if self.proxies:
46+
proxy_support = urllib_request.ProxyHandler(self.proxies)
47+
opener = urllib_request.build_opener(proxy_support)
48+
urllib_request.install_opener(opener)
49+
req = urllib_request.Request(url)
50+
req.get_method = lambda: method
51+
req.add_header('User-Agent', self.useragent)
52+
req.add_header('Authorization', 'Bearer ' + self.apikey)
53+
if json_header:
54+
req.add_header('Content-Type', 'application/json')
55+
try:
56+
if data:
57+
response = urllib_request.urlopen(req, json.dumps(data))
58+
else:
59+
response = urllib_request.urlopen(req, timeout=10)
60+
except HTTPError as e:
61+
if 400 <= e.code < 500:
62+
raise SendGridClientError(e.code, e.read())
63+
elif 500 <= e.code < 600:
64+
raise SendGridServerError(e.code, e.read())
65+
else:
66+
assert False
67+
except timeout as e:
68+
raise SendGridClientError(408, 'Request timeout')
69+
body = response.read()
70+
return response, body
71+
72+
def get(self, api):
73+
url = self.host + api.base_endpoint
74+
response, body = self._build_request(url, False, 'GET')
75+
return response.getcode(), body
76+
77+
def post(self, api, data):
78+
url = self.host + api.endpoint
79+
response, body = self._build_request(url, True, 'POST', data)
80+
return response.getcode(), body
81+
82+
def delete(self, api):
83+
url = self.host + api.endpoint
84+
response, body = self._build_request(url, False, 'DELETE')
85+
return response.getcode(), body
86+
87+
def patch(self, api, data):
88+
url = self.host + api.endpoint
89+
response, body = self._build_request(url, True, 'PATCH', data)
90+
return response.getcode(), body

sendgrid/message.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from smtpapi import SMTPAPIHeader
99

1010

11-
class Mail(object):
11+
class Mail():
1212

1313
"""SendGrid Message."""
1414

sendgrid/resources/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

sendgrid/resources/apikeys.py

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
class APIKeys(object):
2+
"""The API Keys feature allows customers to be able to generate an API Key credential
3+
which can be used for authentication with the SendGrid v3 Web API or the Mail API Endpoint"""
4+
5+
def __init__(self, client , **opts):
6+
"""
7+
Constructs SendGrid APIKeys object.
8+
9+
See https://sendgrid.com/docs/API_Reference/Web_API_v3/API_Keys/index.html
10+
"""
11+
self._name = None
12+
self._base_endpoint = "/v3/api_keys"
13+
self._endpoint = "/v3/api_keys"
14+
self._client = client
15+
16+
@property
17+
def name(self):
18+
return self._name
19+
20+
@name.setter
21+
def name(self, value):
22+
self._name = value
23+
24+
@property
25+
def base_endpoint(self):
26+
return self._base_endpoint
27+
28+
@property
29+
def endpoint(self):
30+
endpoint = self._endpoint
31+
return endpoint
32+
33+
@endpoint.setter
34+
def endpoint(self, value):
35+
self._endpoint = value
36+
37+
@property
38+
def client(self):
39+
return self._client
40+
41+
# Get a list of active API keys
42+
def get(self):
43+
return self.client.get(self)
44+
45+
# Create a new API key with name (string)
46+
def post(self, name):
47+
data = {}
48+
self.name = name
49+
data['name'] = self.name
50+
return self.client.post(self, data)
51+
52+
# Delete a API key
53+
def delete(self, api_key_id):
54+
self.endpoint = self._base_endpoint + "/" + api_key_id
55+
return self.client.delete(self)
56+
57+
# Update a API key's name
58+
def patch(self, api_key_id, name):
59+
data = {}
60+
self.name = name
61+
data['name'] = self.name
62+
self.endpoint = self._base_endpoint + "/" + api_key_id
63+
return self.client.patch(self, data)

sendgrid/version.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
version_info = (1, 4, 2)
1+
version_info = (1, 4, 1)
22
__version__ = '.'.join(str(v) for v in version_info)

setup.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ def getRequires():
1717
setup(
1818
name='sendgrid',
1919
version=str(__version__),
20-
author='SendGrid',
21-
author_email='libraries@sendgrid.com',
20+
author='Yamil Asusta',
21+
author_email='yamil@sendgrid.com',
2222
url='https://github.com/sendgrid/sendgrid-python/',
2323
packages=find_packages(),
2424
license='MIT',

test/__init__.py

+65-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import unittest
66
import json
77
import sys
8-
import collections
98
try:
109
from StringIO import StringIO
1110
except ImportError: # Python 3
@@ -15,8 +14,71 @@
1514
from sendgrid.exceptions import SendGridClientError, SendGridServerError
1615
from sendgrid.sendgrid import HTTPError
1716

18-
SG_USER = os.getenv('SG_USER') or 'SENDGRID_USERNAME'
19-
SG_PWD = os.getenv('SG_PWD') or 'SENDGRID_PASSWORD'
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+
class TestAPIKeys(unittest.TestCase):
48+
def setUp(self):
49+
self.client = SendGridAPIClient(SG_APIKEY)
50+
51+
def test_apikey_post_patch_delete_test(self):
52+
name = "My Amazing API Key of Wonder [PATCH Test]"
53+
status, msg = self.client.apikeys.post(name)
54+
self.assertEqual(status, 201)
55+
msg = json.loads(msg)
56+
api_key_id = msg['api_key_id']
57+
self.assertEqual(msg['name'], name)
58+
print status
59+
print msg
60+
61+
name = "My NEW Amazing API Key of Wonder [PATCH TEST]"
62+
status, msg = self.client.apikeys.patch(api_key_id, name)
63+
self.assertEqual(status, 200)
64+
print status
65+
print msg
66+
67+
status, msg = self.client.apikeys.get()
68+
print status
69+
print msg
70+
71+
status, msg = self.client.apikeys.delete(api_key_id)
72+
self.assertEqual(status, 204)
73+
print status
74+
75+
status, msg = self.client.apikeys.get()
76+
print status
77+
print msg
78+
79+
def test_apikey_get(self):
80+
status, msg = self.client.apikeys.get()
81+
self.assertEqual(status, 200)
2082

2183
class TestSendGrid(unittest.TestCase):
2284

0 commit comments

Comments
 (0)