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+ try :
13+ import urllib .request as urllib_request
14+ from urllib .parse import urlencode
15+ from urllib .error import HTTPError
16+ except ImportError : # Python 2
17+ import urllib2 as urllib_request
18+ from urllib2 import HTTPError
19+ from urllib import urlencode
20+
21+ import sendgrid
22+ from sendgrid import SendGridClient , Mail
23+ from sendgrid .exceptions import SendGridClientError , SendGridServerError
24+ from sendgrid .sendgrid import HTTPError
25+ from sendgrid .client import SendGridAPIClient
26+ from sendgrid .version import __version__
27+
28+ SG_KEY = os .getenv ('SG_KEY' ) or 'SENDGRID_APIKEY'
29+
30+ class MockSendGridAPIClientRequest (SendGridAPIClient ):
31+ def __init__ (self , apikey , ** opts ):
32+ super (MockSendGridAPIClientRequest , self ).__init__ (apikey , ** opts )
33+ self ._req = None
34+
35+ def _build_request (self , url = None , json_header = False , method = 'GET' , data = None ):
36+ req = urllib_request .Request (url )
37+ req .get_method = lambda : method
38+ req .add_header ('User-Agent' , self .useragent )
39+ req .add_header ('Authorization' , 'Bearer ' + self .apikey )
40+ if json_header :
41+ req .add_header ('Content-Type' , 'application/json' )
42+ body = data
43+ if method == 'POST' :
44+ response = 201
45+ if method == 'PATCH' :
46+ response = 200
47+ if method == 'DELETE' :
48+ response = 204
49+ if method == 'GET' :
50+ response = 200
51+ return response , body
52+
53+ class TestSendGridAPIClient (unittest .TestCase ):
54+ def setUp (self ):
55+ self .client = MockSendGridAPIClientRequest
56+ self .client = SendGridAPIClient (SG_KEY )
57+
58+ def test_apikey_init (self ):
59+ self .assertEqual (self .client .apikey , SG_KEY )
60+
61+ def test_useragent (self ):
62+ useragent = 'sendgrid/' + __version__ + ';python_v3'
63+ self .assertEqual (self .client .useragent , useragent )
64+
65+ def test_host (self ):
66+ host = 'https://api.sendgrid.com'
67+ self .assertEqual (self .client .host , host )
68+
69+ class TestASMGroups (unittest .TestCase ):
70+ def setUp (self ):
71+ SendGridAPIClient = MockSendGridAPIClientRequest
72+ self .client = SendGridAPIClient (SG_KEY )
73+
74+ def test_apikeys_init (self ):
75+ self .asm_groups = self .client .asm_groups
76+ self .assertEqual (self .asm_groups .base_endpoint , "/v3/asm/groups" )
77+ self .assertEqual (self .asm_groups .endpoint , "/v3/asm/groups" )
78+ self .assertEqual (self .asm_groups .client , self .client )
79+
80+ def test_asm_groups_get (self ):
81+ status , msg = self .client .apikeys .get ()
82+ self .assertEqual (status , 200 )
83+
84+ if __name__ == '__main__' :
85+ unittest .main ()
0 commit comments