Skip to content

Unit tests no longer requires mocked server #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 27, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,6 @@ pyenv local 3.5.0 3.4.3 3.3.6 3.2.6 2.7.8 2.6.9
pyenv rehash
````

Please [email](mailto:dx@sendgrid.com) us for details on how we mocked up the SendGrid API server, otherwise when you commit to your branch the Travis tests will execute remotely against our Mock Server.

### Execute: ###

```
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,6 @@ We were inspired by the work done on [birdy](https://github.com/inueni/birdy) an

python-http-client is guided and supported by the SendGrid [Developer Experience Team](mailto:dx@sendgrid.com).

python-http-client is maintained and funded by SendGrid, inc. The names and logos for python-http-client are trademarks of SendGrid, inc.
python-http-client is maintained and funded by SendGrid, Inc. The names and logos for python-http-client are trademarks of SendGrid, Inc.


34 changes: 22 additions & 12 deletions python_http_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ class Client(object):
:param version: The version number of the API.
Subclass _build_versioned_url for custom behavior.
Or just pass the version as part of the URL
(e.g. client._("/v3"))
(e.g. client._('/v3'))
:type integer:
"""
def __init__(self,
host=None,
host,
request_headers=None,
version=None):
self.host = host
Expand Down Expand Up @@ -60,25 +60,25 @@ def _add_to_url_path(self, name):

"""Subclass this function for your own needs.
Or just pass the version as part of the URL
(e.g. client._("/v3"))
(e.g. client._('/v3'))
"""
def _build_versioned_url(self, url):
return self.host + "/v" + str(self._version) + url
return '{0}/v{1}{2}'.format(self.host, str(self._version), url)

"""Build the final URL to be passed to urllib

:param query_params: A dictionary of all the query parameters
:type query_params: dictionary
"""
def _build_url(self, query_params):
url = ""
url = ''
count = 0
while count < len(self._url_path):
url += "/" + str(self._url_path[count])
url += '/{0}'.format(self._url_path[count])
count += 1
if query_params:
url_values = urlencode(sorted(query_params.items()))
url = url + '?' + url_values
url = '{0}?{1}'.format(url, url_values)
if self._version:
url = self._build_versioned_url(url)
else:
Expand All @@ -101,7 +101,16 @@ def _set_response(self, response):
:type request_headers: dictionary
"""
def _set_headers(self, request_headers):
self.request_headers.update(request_headers)
if self.request_headers:
self.request_headers.update(request_headers)
else:
self.request_headers = request_headers

"""Make the API call and return the response. This is separated into it's
own functin, so we can mock it easily for testing.
"""
def _make_request(self, opener, request):
return opener.open(request)

"""Add variable values to the url. (e.g. /your/api/{variable_value}/call)
Another example: if you have a Python reserved word, such as global,
Expand All @@ -122,7 +131,7 @@ def _(self, name):
:type name: string or integer if name == version
"""
def __getattr__(self, name):
if name == "version":
if name == 'version':
def get_version(*args, **kwargs):
self._version = args[0]
return self
Expand All @@ -141,10 +150,11 @@ def http_request(*args, **kwargs):
if 'query_params' in kwargs else None
opener = urllib.build_opener()
request = urllib.Request(self._build_url(params), data=data)
for key, value in self.request_headers.items():
request.add_header(key, value)
if self.request_headers:
for key, value in self.request_headers.items():
request.add_header(key, value)
request.get_method = lambda: method
self._response = opener.open(request)
self._response = self._make_request(opener, request)
self._set_response(self._response)
self._reset()
return self
Expand Down
15 changes: 12 additions & 3 deletions python_http_client/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,27 @@ class Config(object):
"""Allow variables assigned in .env available using
os.environ.get('VAR_NAME')

:param base_path: The path to your .env config file
:param base_path: The path to your .env config file without a
a trailing slash
:type base_path: string
"""
def __init__(self, base_path=None):
if base_path:
base_path = base_path
else:
# By default, choose the parent directory
base_path = os.path.join(os.path.dirname(__file__), os.pardir)
if os.path.exists(base_path + '/.env'):
file = open(base_path + '/.env')
# Setup the environment variables found in .env
if os.path.exists('{0}/.env'.format(base_path)):
file = open('{0}/.env'.format(base_path))
for line in file:
var = line.strip().split('=')
if len(var) == 2:
os.environ[var[0]] = var[1]
file.close()

self._local_path_to_env = '{0}/.env'.format(base_path)

@property
def local_path_to_env(self):
return self._local_path_to_env
15 changes: 7 additions & 8 deletions tests/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,27 +120,27 @@ def run_tested_code(client, num_loops):

data = {'sample': 'data'}
headers = {'X-Mock': 200}
api_key_id = "test_url_param"
api_key_id = 'test_url_param'
client.api_keys._(api_key_id).put(request_body=data,
request_headers=headers)

data = {'sample': 'data'}
headers = {'X-Mock': 200}
api_key_id = "test_url_param"
api_key_id = 'test_url_param'
client.api_keys._(api_key_id).patch(request_body=data,
request_headers=headers)

headers = {'X-Mock': 204}
api_key_id = "test_url_param"
api_key_id = 'test_url_param'
client.api_keys._(api_key_id).delete(request_headers=headers)

num_loops -= 1


@timefunc
def dynamic_version():
path = os.path.abspath(os.path.dirname(__file__)) + "/.."
Config(path)
local_path = '{}/..'.format(os.path.abspath(os.path.dirname(__file__)))
Config(local_path)
api_key = os.environ.get('SENDGRID_API_KEY')
request_headers = {
'X-Mock': 200,
Expand All @@ -155,8 +155,8 @@ def dynamic_version():

@timefunc
def static_version():
path = os.path.abspath(os.path.dirname(__file__)) + "/.."
Config(path)
local_path = '{}/..'.format(os.path.abspath(os.path.dirname(__file__)))
Config(local_path)
api_key = os.environ.get('SENDGRID_API_KEY')
request_headers = {
'X-Mock': 200,
Expand All @@ -169,5 +169,4 @@ def static_version():
run_tested_code(client, 10)

dynamic_result = dynamic_version()

static_result = static_version()
Loading