diff --git a/.gitignore b/.gitignore index 19a9887..5e1bebb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ +/build /dist *.egg-info *.pyc .ropeproject *.swp +tags diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..8243793 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,12 @@ +sudo: false +language: python +python: + - 2.7 + - 3.3 + - 3.4 + - 3.5 +install: pip install -r test-requirements.txt +script: + - python -m unittest discover || python -m unittest + - python -m doctest abe/utils.py + - flake8 abe tests diff --git a/README.md b/README.md index a0974fb..0159f66 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,106 @@ -Api By Example for Python -========================= +[![Build Status](https://travis-ci.org/apibyexample/abe-python.svg)](https://travis-ci.org/apibyexample/abe-python) + +# Api By Example for Python This repository includes tools to be able to use the ABE format from within Python code. In particular we aim to support python tests. + + +## Support for unittest.TestCase + +You can use ABE in your unittests by mixing in `AbeTestMixin`, adding a +class-level attribute `samples_root` that points to a root folder containing +your sample files. + +You can then compare how your code behaves re: an ABE sample with a simple +call: + +```python +self.assert_matches_sample( + path_to_sample, label, actual_url, actual_response +) +``` + + +Here is a full example: + + +```python +import os + +from abe.unittest import AbeTestMixin +from django.conf import settings +from django.core.urlresolvers import reverse +from rest_framework_jwt.test import APIJWTTestCase as TestCase + +from ..factories.accounts import UserFactory, TEST_PASSWORD + + +class TestMyAccountView(AbeTestMixin, TestCase): + url = reverse('myaccount') + samples_root = os.path.join(settings.BASE_DIR, 'docs', 'api') + + def setUp(self): + super(TestMyAccountView, self).setUp() + self.user = UserFactory() + + def test_get_my_account_not_logged_in(self): + """ + If I'm not logged in, I can't access any account data + """ + response = self.client.get(self.url) + self.assert_matches_sample( + 'accounts/profile.json', 'unauthenticated', self.url, response + ) + + def test_get_my_account_logged_in(self): + """ + If I'm logged in, I can access any account data + """ + self.client.login(username=self.user.username, password=TEST_PASSWORD) + + response = self.client.get(self.url) + + self.assert_matches_sample( + 'accounts/profile.json', 'OK', self.url, response + ) +``` + +This is the file under `docs/api/accounts/profile.json`: + +```json +{ + "description": "Retrieve profile of logged in user", + "url": "/accounts/me", + "method": "GET", + "examples": { + "OK": { + "request": { + "url": "/accounts/me" + }, + "response": { + "status": 200, + "body": { + "id": 1, + "username": "user-0", + "first_name": "", + "last_name": "", + "email": "user-0@example.com" + } + } + }, + "unauthenticated": { + "description": "I am not logged in", + "request": { + "url": "/accounts/me" + }, + "response": { + "status": 403, + "body": { + "detail": "Authentication credentials were not provided." + } + } + } + } +} +``` diff --git a/abe/__init__.py b/abe/__init__.py index b794fd4..abeeedb 100644 --- a/abe/__init__.py +++ b/abe/__init__.py @@ -1 +1 @@ -__version__ = '0.1.0' +__version__ = '0.4.0' diff --git a/abe/mocks.py b/abe/mocks.py index 87e85bb..e335057 100644 --- a/abe/mocks.py +++ b/abe/mocks.py @@ -1,19 +1,23 @@ import json +import warnings from supermutes.dot import dotify class AbeMock(object): - def __init__(self, filename): + def __init__(self, data): """ Initialise an ABE mock from data. - filename is expected to be the path to an ABE file. - """ - with open(filename, 'r') as f: - data = json.load(f) + if not isinstance(data, dict): + msg = ('Instanciating an AbeMock by filename is deprecated and ' + 'will be removed in an upcoming release. ' + 'Use AbeMock.from_filename instead'.format(data)) + warnings.warn(msg, DeprecationWarning) + with open(data, 'r') as f: + data = json.load(f) # map JSON fields to attributes self.__dict__ = data @@ -25,6 +29,18 @@ def __init__(self, filename): self._feed_inherited_fields(value, 'request', ['url', 'method']) self.examples[key] = dotify(value) + @classmethod + def from_filename(cls, filename): + """ + Initialise an ABE mock from a spec file. + + filename is expected to be the path to an ABE file. + + """ + with open(filename, 'r') as f: + data = json.load(f) + return AbeMock(data) + def _feed_inherited_fields(self, value, where, inheritable): """ If missing in request or response, some fields are inherited. diff --git a/abe/unittest.py b/abe/unittest.py new file mode 100644 index 0000000..46d1a28 --- /dev/null +++ b/abe/unittest.py @@ -0,0 +1,214 @@ +import os +try: + from urlparse import parse_qs +except ImportError: + from urllib.parse import parse_qs + +from .mocks import AbeMock +from .utils import normalize, subkeys + + +class AbeTestMixin(object): + """ + Mixin for unittest.TestCase to check against API samples. + + Example usage: + + class TestCase(AbeTestMixin, unittest.TestCase) + ... + + """ + # Root directory to load samples from. + samples_root = '.' + + def load_sample(self, sample_path): + """ + Load a sample file into an AbeMock object. + """ + sample_filename = os.path.join(self.samples_root, sample_path) + return AbeMock.from_filename(sample_filename) + + def get_sample_request(self, path, label): + """ + Get the request body to send for a specific sample label. + + """ + sample = self.load_sample(path) + sample_request = sample.examples[label].request + return sample_request.body + + def assert_item_matches(self, real, sample): + """ + A primitive value matches the sample. + + If the sample represents a parameter, then do simple pattern matching. + + """ + real = normalize(real) + sample = normalize(sample) + self.assertEqual(real, sample) + + def assert_data_equal(self, real, sample, non_strict=None): + """ + Two elements are recursively equal + + :param non_strict: + Names of fields to match non-strictly. In current implementation, + only check for field presence. + """ + non_strict = non_strict or [] + try: + if isinstance(real, list): + self.assertIsInstance(sample, list) + self.assert_data_list_equal(real, sample, non_strict) + elif isinstance(real, dict): + self.assertIsInstance(sample, dict) + self.assert_data_dict_equal(real, sample, non_strict) + else: + self.assert_item_matches(real, sample) + except AssertionError as exc: + message = str(exc) + '\n{}\n{}\n\n'.format(real, sample) + raise type(exc)(message) + + def assert_data_dict_equal(self, real, sample, non_strict=None): + """ + Two dicts are recursively equal without taking order into account + """ + non_strict = non_strict or [] + self.assertEqual( + len(real), len(sample), + msg='Number of elements mismatch: {} != {}\n'.format( + real.keys(), sample.keys()) + ) + for key in sample: + self.assertIn(key, real) + if key not in non_strict: + inner_non_strict = subkeys(non_strict, key) + self.assert_data_equal( + real[key], sample[key], inner_non_strict) + + def assert_data_list_equal(self, real, sample, non_strict=None): + """ + Two lists are recursively equal, including ordering. + """ + non_strict = non_strict or [] + self.assertEqual( + len(real), len(sample), + msg='Number of elements mismatch: {} {}'.format( + real, sample) + ) + + exceptions = [] + for real_item, sample_item in zip(real, sample): + try: + self.assert_data_equal(real_item, sample_item, non_strict) + except AssertionError as exc: + exceptions.append(exc) + + if exceptions: + message = '\n*\n'.join( + map(str, exceptions) + ) + raise type(exceptions[0])(message) + + def assert_headers_contain(self, response_data, spec_data): + """ + response_data headers contain all headers defined in spec_data + """ + for expected_header, expected_value in spec_data.items(): + django_expected_header = ( + 'HTTP_' + expected_header.upper().replace('-', '_') + ) + actual_val = response_data.get( + expected_header, + response_data.get(django_expected_header) + ) + self.assertEqual( + expected_value, actual_val, + "Incorrect or missing value specified for " + "header {0}".format(expected_header) + ) + + def assert_query_params_equal(self, request_data, spec_data): + qs = parse_qs(request_data) + for k, expected_value in spec_data.items(): + try: + actual_value = qs[k] + except KeyError: + raise AssertionError('Missing {0} from request'.format(k)) + + if len(actual_value) == 1: + actual_value = actual_value[0] + self.assertEqual(expected_value, actual_value) + + def assert_matches_request(self, sample_request, wsgi_request, + non_strict=None): + """ + Check that the sample request and wsgi request match. + """ + non_strict = non_strict or [] + + if 'url' not in non_strict: + self.assertEqual(wsgi_request.META['PATH_INFO'], + sample_request['url']) + if 'method' not in non_strict: + self.assertEqual(wsgi_request.META['REQUEST_METHOD'], + sample_request['method']) + + if 'headers' in sample_request and 'headers' not in non_strict: + self.assert_headers_contain( + wsgi_request.META, sample_request['headers'] + ) + + if 'queryParams' in sample_request and 'queryParams' not in non_strict: + self.assert_query_params_equal( + wsgi_request.META['QUERY_STRING'], + sample_request['queryParams'] + ) + + if 'body' in sample_request: + self.assert_data_equal( + wsgi_request.POST, sample_request['body'], non_strict) + + def assert_matches_response(self, sample_response, wsgi_response, + non_strict=None): + """ + Check that the sample response and wsgi response match. + """ + non_strict = non_strict or [] + self.assertEqual(wsgi_response.status_code, sample_response.status) + if 'body' in sample_response: + response_parsed = wsgi_response.data + self.assert_data_equal( + response_parsed, sample_response.body, non_strict) + + def assert_matches_sample( + self, path, label, response, non_strict_response=None, + non_strict_request=None + ): + """ + Check a URL and response against a sample. + + :param sample_name: + The name of the sample file, e.g. 'query.json' + :param label: + The label for a specific sample request/response, e.g. 'OK' + :param response: + The actual API response we want to match with the sample. + It is assumed to be a Django Rest Framework response object + :param non_strict: + List of fields that will not be checked for strict matching. + You can use this to include server-generated fields whose exact + value you don't care about in your test, like ids, dates, etc. + """ + non_strict_response = non_strict_response or [] + non_strict_request = non_strict_request or [] + sample = self.load_sample(path) + sample_request = sample.examples[label].request + sample_response = sample.examples[label].response + + self.assert_matches_response( + sample_response, response, non_strict=non_strict_response) + self.assert_matches_request( + sample_request, response.wsgi_request, + non_strict=non_strict_request) diff --git a/abe/utils.py b/abe/utils.py new file mode 100644 index 0000000..733df80 --- /dev/null +++ b/abe/utils.py @@ -0,0 +1,46 @@ +from datetime import datetime +import sys + +_PY3 = sys.version_info >= (3, 0) + +if _PY3: + unicode = str + + +def datetime_to_string(value): + representation = value.isoformat() + if value.microsecond: + representation = representation[:23] + representation[26:] + if representation.endswith('+00:00'): + representation = representation[:-6] + 'Z' + return representation + + +def normalize(data): + """ + Ensure that dates, Decimals and strings become unicode + + Integers, on the other hand, are not converted. + """ + if isinstance(data, datetime): + data = datetime_to_string(data) + elif not isinstance(data, int): + data = str(data) + + if not _PY3 and isinstance(data, str): + data = unicode(data) + return data + + +def subkeys(original, key): + """ + Takes a list of dot-hierarchical values and keeps only matching subkeys. + + Example: + + >>> subkeys(['one.two', 'one.three', 'four'], 'one') + ['two', 'three'] + """ + new_keys = filter(lambda s: s.startswith(key + '.'), original) + new_keys = list(map(lambda s: s[len(key) + 1:], new_keys)) + return new_keys diff --git a/ep.yml b/ep.yml new file mode 100644 index 0000000..89f3ee2 --- /dev/null +++ b/ep.yml @@ -0,0 +1,17 @@ +ep: 0.1.2 +dependencies: + - python: + version: ">=2.6.0" + file: test-requirements.txt +run: + - flake8 abe tests + - coverage erase + - coverage run --omit="*/tests/*","*$VIRTUAL_ENV*" -m unittest discover + - coverage html + - python -m doctest abe/utils.py +publish: + - git diff --exit-code + - ep run + - git tag $(python setup.py --version) + - git push --tags + - python setup.py sdist bdist_wheel upload diff --git a/setup.py b/setup.py index 8345c30..97e41f0 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ from abe import __version__ setup( - name='ABE-mocks for python', + name='abe-python', description='Parse ABE files for usage within python tests', version=__version__, author='Carles Barrobés', diff --git a/test-requirements.txt b/test-requirements.txt new file mode 100644 index 0000000..021d3f6 --- /dev/null +++ b/test-requirements.txt @@ -0,0 +1,5 @@ +-r requirements.txt + +flake8 +coverage +mock diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/data/sample.json b/tests/data/sample.json new file mode 100644 index 0000000..7c09dce --- /dev/null +++ b/tests/data/sample.json @@ -0,0 +1,34 @@ +{ + "description": "Retrieve profile of logged in user", + "url": "/accounts/me", + "method": "GET", + "examples": { + "OK": { + "request": { + "url": "/accounts/me" + }, + "response": { + "status": 200, + "body": { + "id": 1, + "username": "user-0", + "first_name": "", + "last_name": "", + "email": "user-0@example.com" + } + } + }, + "unauthenticated": { + "description": "I am not logged in", + "request": { + "url": "/accounts/me" + }, + "response": { + "status": 403, + "body": { + "detail": "Authentication credentials were not provided." + } + } + } + } +} diff --git a/tests/test_assertions.py b/tests/test_assertions.py new file mode 100644 index 0000000..5d76c8e --- /dev/null +++ b/tests/test_assertions.py @@ -0,0 +1,408 @@ +from os.path import abspath, dirname, join +from unittest import TestCase +import warnings + +from mock import Mock + +from abe.mocks import AbeMock +from abe.unittest import AbeTestMixin + +DATA_DIR = join(dirname(abspath(__file__)), 'data') + + +class TestAssertDataEqual(TestCase, AbeTestMixin): + + def test_int_value_matches(self): + self.assert_data_equal(3, 3) + + def test_int_value_mismatch(self): + self.assertRaises( + AssertionError, + self.assert_data_equal, 3, 33 + ) + + def test_int_vs_string_value_mismatch(self): + self.assertRaises( + AssertionError, + self.assert_data_equal, 3, "3" + ) + + def test_string_value_matches(self): + self.assert_data_equal("hello", "hello") + + def test_string_value_mismatch(self): + self.assertRaises( + AssertionError, + self.assert_data_equal, "hell", "hello" + ) + + +class TestDataListEqual(TestCase, AbeTestMixin): + + def test_simple_list_equality(self): + self.assert_data_list_equal([1, 2], [1, 2]) + + def test_simple_list_equality_for_ordering(self): + self.assertRaises( + AssertionError, + self.assert_data_list_equal, [3, 1, 2], [2, 3, 1] + ) + + def test_list_equality_nested_items(self): + self.assert_data_list_equal([[3, 1], 1, 2], [[3, 1], 1, 2]) + self.assert_data_list_equal( + [[3, 1], {'foo': 'bar'}, 2], + [[3, 1], {'foo': 'bar'}, 2] + ) + self.assert_data_list_equal( + [[3, 1], {'foo': [1, 2, 3]}, 2], + [[3, 1], {'foo': [1, 2, 3]}, 2] + ) + + def test_list_equality_ordering_nested_items(self): + nested_examples = [ + ([[3, 1], 1, 2], [[1, 3], 1, 2]), + ([[3, 1], {'foo': 'bar'}, 2], [[3, 1], {'foo': 'dee'}, 2]), + ([[3, 1], {'foo': [1, 2, 3]}, 2], [[3, 1], {'foo': [1, 3, 2]}, 2]) + ] + for data1, data2 in nested_examples: + self.assertRaises( + AssertionError, + self.assert_data_list_equal, data1, data2 + ) + + +class TestAssertHeadersEqual(TestCase, AbeTestMixin): + + def test_matches_django_test_format(self): + self.assert_headers_contain( + {'HTTP_THIS_CUSTOM_HEADER': 'Foo'}, + {'This-Custom-Header': 'Foo'} + ) + + def test_matches_normal_header_format(self): + self.assert_headers_contain( + {'This-Custom-Header': 'Foo'}, + {'This-Custom-Header': 'Foo'}, + ) + + def test_matches_only_sample_defined_headers(self): + self.assert_headers_contain( + {'HTTP_THIS_CUSTOM_HEADER': 'Foo', + 'HTTP_SOME_UNDEFINED_IN_SPEC_HEADER': 'Bar'}, + {'This-Custom-Header': 'Foo'}, + ) + + def test_requires_key_and_value_match(self): + with self.assertRaises(AssertionError): + self.assert_headers_contain( + {'HTTP_THIS_CUSTOM_HEADER': 'Bar'}, + {'This-Custom-Header': 'Foo'}, + ) + with self.assertRaises(AssertionError): + self.assert_headers_contain( + {'HTTP_THIS_CUSTOM': 'Foo'}, + {'This-Custom-Header': 'Foo'}, + ) + + +class TestAssertMatchesRequest(TestCase, AbeTestMixin): + + def setUp(self): + abe_mock = AbeMock({ + "method": "POST", + "url": "/resource/", + "examples": { + "OK": { + "request": { + "queryParams": { + "foo": "1", + "bar": "2" + }, + "body": { + "name": "My Resource" + }, + "headers": { + "This-Custom-Header": 'Foo' + } + } + } + } + }) + self.sample_request = abe_mock.examples['OK'].request + + self.mock_wsgi_request = Mock( + POST={'name': 'My Resource'}, + META={ + 'HTTP_THIS_CUSTOM_HEADER': 'Foo', + 'REQUEST_METHOD': 'POST', + 'PATH_INFO': '/resource/', + 'QUERY_STRING': 'foo=1&bar=2' + }, + ) + + def test_success_case(self): + self.assert_matches_request( + self.sample_request, self.mock_wsgi_request + ) + + def test_assertion_error_if_url_mismatch(self): + self.mock_wsgi_request.META['PATH_INFO'] = '/resourceoops/' + + with self.assertRaises(AssertionError): + self.assert_matches_request( + self.sample_request, self.mock_wsgi_request + ) + + def test_assertion_error_if_method_mismatch(self): + self.mock_wsgi_request.META['REQUEST_METHOD'] = 'PATCH' + + with self.assertRaises(AssertionError): + self.assert_matches_request( + self.sample_request, self.mock_wsgi_request + ) + + def test_assertion_error_if_post_data_mismatch(self): + self.mock_wsgi_request.POST = {'a': 1} + + with self.assertRaises(AssertionError): + self.assert_matches_request( + self.sample_request, self.mock_wsgi_request + ) + + def test_matches_non_strict(self): + self.mock_wsgi_request.POST = {'name': 'Something else'} + self.assert_matches_request( + self.sample_request, self.mock_wsgi_request, non_strict=['name'] + ) + + def test_assertion_error_if_query_params_mismatch(self): + self.mock_wsgi_request.META['QUERY_STRING'] = "foo=1" + with self.assertRaises(AssertionError): + self.assert_matches_request( + self.sample_request, self.mock_wsgi_request + ) + + +def _abe_wrap_response(response): + abe_mock = AbeMock({ + "method": "POST", + "url": "/resource/", + "examples": { + "0": {"response": response} + } + }) + return abe_mock.examples['0'].response + + +class TestAssertMatchesResponse(TestCase, AbeTestMixin): + + def test_response_matches_strictly(self): + sample = _abe_wrap_response({ + "status": 201, + "body": { + "id": 12, + "name": "My Resource", + "url": "http://example.com/resource/12", + "author": { + "name": "Slough", + "url": "http://example.com/user/25" + } + } + }) + response = Mock() + response.status_code = 201 + response.data = { + "id": 12, + "name": "My Resource", + "url": "http://example.com/resource/12", + "author": { + "name": "Slough", + "url": "http://example.com/user/25" + } + } + + self.assert_matches_response( + sample, response + ) + + def test_strict_response_mismatch(self): + sample = _abe_wrap_response({ + "status": 201, + "body": { + "url": "http://example.com/resource/12" + } + }) + response = Mock() + response.status_code = 201 + response.data = { + "url": "http://example.com/resource/13" + } + + self.assertRaises( + AssertionError, + self.assert_matches_response, + sample, response + ) + + def test_non_strict_response_matches(self): + sample = _abe_wrap_response({ + "status": 201, + "body": { + "id": 12, + "name": "My Resource", + "url": "http://example.com/resource/12", + "author": { + "name": "Slough", + "url": "http://example.com/user/25" + } + } + }) + response = Mock() + response.status_code = 201 + response.data = { + "id": 25, + "name": "My Resource", + "url": "http://example.com/resource/12312", + "author": { + "name": "Slough", + "url": "http://testserver/25/" + } + } + + self.assert_matches_response( + sample, response, + non_strict=['id', 'url', 'author.url'] + ) + + def test_non_strict_response_mismatch(self): + sample = _abe_wrap_response({ + "status": 201, + "body": { + "author": { + "name": "Some", + "url": "http://example.com/user/1" + } + } + }) + response = Mock() + response.status_code = 201 + response.data = { + "author": { + "name": "Something", + "url": "http://testserver/user/25" + } + } + + self.assertRaises( + AssertionError, + self.assert_matches_response, + sample, response, non_strict=['author.url'] + ) + + def test_strict_response_checks_presence_of_sample_fields(self): + sample = _abe_wrap_response({ + "status": 201, + "body": { + "id": 1, + "name": "Some" + } + }) + response = Mock() + response.status_code = 201 + response.data = { + "name": "Some", + } + + self.assertRaises( + AssertionError, + self.assert_matches_response, + sample, response + ) + + def test_non_strict_response_checks_presence_of_sample_fields(self): + sample = _abe_wrap_response({ + "status": 201, + "body": { + "id": 1, + "name": "Some" + } + }) + response = Mock() + response.status_code = 201 + response.data = { + "name": "Some", + "url": "http://testserver/user/25" + } + + self.assertRaises( + AssertionError, + self.assert_matches_response, + sample, response, non_strict=['url'] + ) + + def test_non_strict_list_value_matches(self): + sample = _abe_wrap_response({ + "status": 200, + "body": { + "contributors": [ + {"name": "Jack", "id": 1}, + {"name": "Jill", "id": 2}, + ] + } + }) + response = Mock() + response.status_code = 200 + response.data = { + "contributors": [ + {"name": "Jack", "id": 12}, + {"name": "Jill", "id": 23}, + ] + } + + self.assert_matches_response( + sample, response, non_strict=['contributors.id'] + ) + + def test_non_strict_list_value_mismatch(self): + sample = _abe_wrap_response({ + "status": 200, + "body": { + "contributors": [ + {"name": "Jack", "id": 1}, + {"name": "Jill", "id": 2}, + ] + } + }) + response = Mock() + response.status_code = 200 + response.data = { + "contributors": [ + {"name": "Joe", "id": 12}, + {"name": "Jill", "id": 23}, + ] + } + + self.assertRaises( + AssertionError, + self.assert_matches_response, + sample, response, non_strict=['contributors.id'] + ) + + +class TestFilenameInstantiation(TestCase): + + def setUp(self): + self.filename = join(DATA_DIR, 'sample.json') + + def test_can_still_use_deprecated_instantiation(self): + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + + AbeMock(self.filename) + + self.assertEqual(len(w), 1) + self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) + + def test_from_filename(self): + AbeMock.from_filename(self.filename) diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 0000000..2c52a51 --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,9 @@ +from unittest import TestCase + +from abe.utils import subkeys + + +class TestSubkeys(TestCase): + def test_subkeys(self): + new_keys = subkeys(['key.one', 'key.two', 'hello', 'keyring'], 'key') + self.assertEqual(new_keys, ['one', 'two'])