From a1b863002e02dc2ed2096f3cf4cfae969b6521d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Sat, 12 Sep 2015 19:52:57 +0200 Subject: [PATCH 01/26] Add built-in support for unittest --- .gitignore | 1 + README.md | 103 +++++++++++++++++++++++++++++++++++++++++- abe/unittest.py | 118 ++++++++++++++++++++++++++++++++++++++++++++++++ abe/utils.py | 29 ++++++++++++ 4 files changed, 249 insertions(+), 2 deletions(-) create mode 100644 abe/unittest.py create mode 100644 abe/utils.py diff --git a/.gitignore b/.gitignore index 19a9887..def9845 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ *.pyc .ropeproject *.swp +tags diff --git a/README.md b/README.md index a0974fb..e5c9d01 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,104 @@ -Api By Example for 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/unittest.py b/abe/unittest.py new file mode 100644 index 0000000..fddbb2a --- /dev/null +++ b/abe/unittest.py @@ -0,0 +1,118 @@ +from copy import copy +from operator import attrgetter +import os + +from .mocks import AbeMock +from .utils import to_unicode + + +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_file = os.path.join(self.samples_root, sample_path) + return AbeMock(sample_file) + + 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_data_equal(self, data1, data2): + """ + Two elements are recursively equal without taking order into account + """ + try: + if isinstance(data1, list): + self.assertIsInstance(data2, list) + self.assert_data_list_equal(data1, data2) + elif isinstance(data1, dict): + self.assertIsInstance(data2, dict) + self.assert_data_dict_equal(data1, data2) + else: + data1 = to_unicode(data1) + data2 = to_unicode(data2) + self.assertIsInstance(data2, data1.__class__) + self.assertEqual(data1, data2) + except AssertionError as exc: + message = str(exc) + '\n{}\n{}\n\n'.format(data1, data2) + raise type(exc)(message) + + def assert_data_dict_equal(self, data1, data2): + """ + Two dicts are recursively equal without taking order into account + """ + self.assertEqual( + len(data1), len(data2), + msg='Number of elements mismatch: {} != {}\n'.format( + data1.keys(), data2.keys()) + ) + for key in data1: + self.assertIn(key, data2) + self.assert_data_equal(data1[key], data2[key]) + + def assert_data_list_equal(self, data1, data2): + """ + Two lists are recursively equal without taking order into account + """ + self.assertEqual( + len(data1), len(data2), + msg='Number of elements mismatch: {} {}'.format( + data1, data2) + ) + + data1_elements = copy(data1) + for element2 in data2: + fails, exceptions, found = [], [], False + while data1_elements and not found: + element = data1_elements.pop() + try: + self.assert_data_equal(element, element2) + found = True + except AssertionError as exc: + exceptions.append(exc) + fails.append(element) + if not data1_elements: + message = '\n*\n'.join( + map(attrgetter('message'), exceptions) + ) + raise type(exceptions[0])(message) + data1_elements.extend(fails) + + def assert_matches_sample(self, path, label, url, response): + """ + 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 url: + The actual URL we want to compare with the sample + :param response: + The actual API response we want to match with the sample + """ + sample = self.load_sample(path) + sample_request = sample.examples[label].request + sample_response = sample.examples[label].response + + self.assertEqual(url, sample_request.url) + self.assertEqual(response.status_code, sample_response.status) + self.assert_data_equal(response.data, sample_response.body) diff --git a/abe/utils.py b/abe/utils.py new file mode 100644 index 0000000..6343957 --- /dev/null +++ b/abe/utils.py @@ -0,0 +1,29 @@ +from datetime import datetime +import decimal +import sys + +_PY3 = sys.version_info >= (3, 0) + + +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 to_unicode(data): + """ + Ensure that dates, Decimals and strings become unicode + """ + if isinstance(data, datetime): + data = datetime_to_string(data) + elif isinstance(data, decimal.Decimal): + data = str(data) + + if not _PY3: + if isinstance(data, str): + data = unicode(data) + return data From adb65f5d5581ab8978cebe5d395b63685d6edf57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Sun, 13 Sep 2015 21:36:35 +0200 Subject: [PATCH 02/26] Version bump --- abe/__init__.py | 2 +- setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/abe/__init__.py b/abe/__init__.py index b794fd4..7fd229a 100644 --- a/abe/__init__.py +++ b/abe/__init__.py @@ -1 +1 @@ -__version__ = '0.1.0' +__version__ = '0.2.0' 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', From 0d75821354644955871f5adc4dc37c146c0e56ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Thu, 17 Sep 2015 11:27:42 +0200 Subject: [PATCH 03/26] Cater for empty body --- abe/unittest.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/abe/unittest.py b/abe/unittest.py index fddbb2a..bf79233 100644 --- a/abe/unittest.py +++ b/abe/unittest.py @@ -1,5 +1,4 @@ from copy import copy -from operator import attrgetter import os from .mocks import AbeMock @@ -91,7 +90,7 @@ def assert_data_list_equal(self, data1, data2): fails.append(element) if not data1_elements: message = '\n*\n'.join( - map(attrgetter('message'), exceptions) + map(str, exceptions) ) raise type(exceptions[0])(message) data1_elements.extend(fails) @@ -115,4 +114,5 @@ def assert_matches_sample(self, path, label, url, response): self.assertEqual(url, sample_request.url) self.assertEqual(response.status_code, sample_response.status) - self.assert_data_equal(response.data, sample_response.body) + if 'body' in sample_response: + self.assert_data_equal(response.data, sample_response.body) From 828b57f7db82f6c24795dca8f7badc404c51fbcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Fri, 16 Oct 2015 15:41:37 +0200 Subject: [PATCH 04/26] Fix to_unicode to work for DRF hyperlink fields --- abe/unittest.py | 6 ++++-- abe/utils.py | 3 +-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/abe/unittest.py b/abe/unittest.py index bf79233..6b2e213 100644 --- a/abe/unittest.py +++ b/abe/unittest.py @@ -106,7 +106,8 @@ def assert_matches_sample(self, path, label, url, response): :param url: The actual URL we want to compare with the sample :param response: - The actual API response we want to match with the sample + The actual API response we want to match with the sample. + It is assumed to be a Django Rest Framework response object """ sample = self.load_sample(path) sample_request = sample.examples[label].request @@ -115,4 +116,5 @@ def assert_matches_sample(self, path, label, url, response): self.assertEqual(url, sample_request.url) self.assertEqual(response.status_code, sample_response.status) if 'body' in sample_response: - self.assert_data_equal(response.data, sample_response.body) + response_parsed = response.data + self.assert_data_equal(response_parsed, sample_response.body) diff --git a/abe/utils.py b/abe/utils.py index 6343957..1aaeba7 100644 --- a/abe/utils.py +++ b/abe/utils.py @@ -1,5 +1,4 @@ from datetime import datetime -import decimal import sys _PY3 = sys.version_info >= (3, 0) @@ -20,7 +19,7 @@ def to_unicode(data): """ if isinstance(data, datetime): data = datetime_to_string(data) - elif isinstance(data, decimal.Decimal): + else: data = str(data) if not _PY3: From 842cc6059c4d0e753eb2662650866a3eecde2d41 Mon Sep 17 00:00:00 2001 From: Alex Couper Date: Wed, 28 Oct 2015 00:30:44 +0100 Subject: [PATCH 05/26] Add tests for ordering. --- abe/unittest.py | 34 +++++++++++++++------------------- tests/test_assertions.py | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 19 deletions(-) create mode 100644 tests/test_assertions.py diff --git a/abe/unittest.py b/abe/unittest.py index 6b2e213..8425682 100644 --- a/abe/unittest.py +++ b/abe/unittest.py @@ -36,7 +36,7 @@ def get_sample_request(self, path, label): def assert_data_equal(self, data1, data2): """ - Two elements are recursively equal without taking order into account + Two elements are recursively equal """ try: if isinstance(data1, list): @@ -69,7 +69,7 @@ def assert_data_dict_equal(self, data1, data2): def assert_data_list_equal(self, data1, data2): """ - Two lists are recursively equal without taking order into account + Two lists are recursively equal, including ordering. """ self.assertEqual( len(data1), len(data2), @@ -77,23 +77,19 @@ def assert_data_list_equal(self, data1, data2): data1, data2) ) - data1_elements = copy(data1) - for element2 in data2: - fails, exceptions, found = [], [], False - while data1_elements and not found: - element = data1_elements.pop() - try: - self.assert_data_equal(element, element2) - found = True - except AssertionError as exc: - exceptions.append(exc) - fails.append(element) - if not data1_elements: - message = '\n*\n'.join( - map(str, exceptions) - ) - raise type(exceptions[0])(message) - data1_elements.extend(fails) + exceptions = [] + for element, element2 in zip(data1, data2): + try: + self.assert_data_equal(element, element2) + except AssertionError as exc: + exceptions.append(exc) + + if exceptions: + message = '\n*\n'.join( + map(str, exceptions) + ) + raise type(exceptions[0])(message) + def assert_matches_sample(self, path, label, url, response): """ diff --git a/tests/test_assertions.py b/tests/test_assertions.py new file mode 100644 index 0000000..9b5ba63 --- /dev/null +++ b/tests/test_assertions.py @@ -0,0 +1,39 @@ +from unittest import TestCase + +from abe.unittest import AbeTestMixin + + +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 + ) From dbe8897afe14fa198fe89baf978e5bf94234b8a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Fri, 16 Oct 2015 15:48:27 +0200 Subject: [PATCH 06/26] Version 0.2.1 --- abe/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/abe/__init__.py b/abe/__init__.py index 7fd229a..fc79d63 100644 --- a/abe/__init__.py +++ b/abe/__init__.py @@ -1 +1 @@ -__version__ = '0.2.0' +__version__ = '0.2.1' From 4f7f6e57dc895a840d58be5f7a9424c94c5ce2d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Wed, 28 Oct 2015 15:11:43 +0100 Subject: [PATCH 07/26] Bump version to 0.2.2 --- abe/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/abe/__init__.py b/abe/__init__.py index fc79d63..020ed73 100644 --- a/abe/__init__.py +++ b/abe/__init__.py @@ -1 +1 @@ -__version__ = '0.2.1' +__version__ = '0.2.2' From ce592ede300bc3e7ecfa19d6cfc783e956c0f09d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Wed, 28 Oct 2015 15:19:13 +0100 Subject: [PATCH 08/26] Add a travis CI build --- .gitignore | 1 + .travis.yml | 11 +++++++++++ abe/unittest.py | 2 -- test-requirements.txt | 3 +++ tests/__init__.py | 0 5 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 .travis.yml create mode 100644 test-requirements.txt create mode 100644 tests/__init__.py diff --git a/.gitignore b/.gitignore index def9845..5e1bebb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +/build /dist *.egg-info *.pyc diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..115f452 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,11 @@ +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 + - flake8 abe diff --git a/abe/unittest.py b/abe/unittest.py index 8425682..6aa5564 100644 --- a/abe/unittest.py +++ b/abe/unittest.py @@ -1,4 +1,3 @@ -from copy import copy import os from .mocks import AbeMock @@ -90,7 +89,6 @@ def assert_data_list_equal(self, data1, data2): ) raise type(exceptions[0])(message) - def assert_matches_sample(self, path, label, url, response): """ Check a URL and response against a sample. diff --git a/test-requirements.txt b/test-requirements.txt new file mode 100644 index 0000000..afcc603 --- /dev/null +++ b/test-requirements.txt @@ -0,0 +1,3 @@ +-r requirements.txt + +flake8 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 From 564316172fa70bad11521c548b8325be8f84457a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Wed, 28 Oct 2015 15:37:00 +0100 Subject: [PATCH 09/26] Make flake8 pass on python3 --- abe/utils.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/abe/utils.py b/abe/utils.py index 1aaeba7..2d8af5f 100644 --- a/abe/utils.py +++ b/abe/utils.py @@ -3,6 +3,9 @@ _PY3 = sys.version_info >= (3, 0) +if _PY3: + unicode = str + def datetime_to_string(value): representation = value.isoformat() @@ -22,7 +25,6 @@ def to_unicode(data): else: data = str(data) - if not _PY3: - if isinstance(data, str): - data = unicode(data) + if not _PY3 and isinstance(data, str): + data = unicode(data) return data From e6ebc609850f764ef46a618081fbd61c1355806e Mon Sep 17 00:00:00 2001 From: Alex Couper Date: Thu, 5 Nov 2015 10:12:27 +0100 Subject: [PATCH 10/26] Add support for testing headers. --- abe/unittest.py | 23 +++++++++++++++++++++++ tests/test_assertions.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/abe/unittest.py b/abe/unittest.py index 6aa5564..0611446 100644 --- a/abe/unittest.py +++ b/abe/unittest.py @@ -89,6 +89,24 @@ def assert_data_list_equal(self, data1, data2): ) 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_matches_sample(self, path, label, url, response): """ Check a URL and response against a sample. @@ -108,6 +126,11 @@ def assert_matches_sample(self, path, label, url, response): sample_response = sample.examples[label].response self.assertEqual(url, sample_request.url) + if 'headers' in sample_request: + self.assert_headers_contain( + response.request, sample_request.headers + ) + self.assertEqual(response.status_code, sample_response.status) if 'body' in sample_response: response_parsed = response.data diff --git a/tests/test_assertions.py b/tests/test_assertions.py index 9b5ba63..ee7f312 100644 --- a/tests/test_assertions.py +++ b/tests/test_assertions.py @@ -37,3 +37,37 @@ def test_list_equality_ordering_nested_items(self): 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'}, + ) From 722bee4256729cbb6e7eec5908535f865ea823dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Sun, 8 Nov 2015 01:00:20 +0100 Subject: [PATCH 11/26] Add ep.yml and bump version number --- abe/__init__.py | 2 +- ep.yml | 16 ++++++++++++++++ test-requirements.txt | 3 ++- 3 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 ep.yml diff --git a/abe/__init__.py b/abe/__init__.py index 020ed73..d93b5b2 100644 --- a/abe/__init__.py +++ b/abe/__init__.py @@ -1 +1 @@ -__version__ = '0.2.2' +__version__ = '0.2.3' diff --git a/ep.yml b/ep.yml new file mode 100644 index 0000000..52a0ba0 --- /dev/null +++ b/ep.yml @@ -0,0 +1,16 @@ +ep: 0.1.2 +dependencies: + - python: + version: ">=2.6.0" + file: test-requirements.txt +run: + - flake8 abe + - coverage erase + - coverage run --omit="*/tests/*","*$VIRTUAL_ENV*" -m unittest discover + - coverage html +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/test-requirements.txt b/test-requirements.txt index afcc603..7626830 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -1,3 +1,4 @@ -r requirements.txt -flake8 +prospector +coverage From 571389f8b82b1560b481e2e5649e66d922f4b39b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Sun, 8 Nov 2015 01:11:16 +0100 Subject: [PATCH 12/26] Missing flake8 in test requirements --- test-requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test-requirements.txt b/test-requirements.txt index 7626830..5f691f1 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -1,4 +1,4 @@ -r requirements.txt -prospector +flake8 coverage From c13a46461b4bc6de07d26c8f4157708f2cdeaff8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Sun, 8 Nov 2015 01:15:28 +0100 Subject: [PATCH 13/26] Add travis badge to README --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index e5c9d01..0159f66 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +[![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 From 72684a4192bfec0a0ef4a10d3b0ab0a078b3d807 Mon Sep 17 00:00:00 2001 From: Alex Couper Date: Sun, 8 Nov 2015 23:57:31 +0100 Subject: [PATCH 14/26] Add checks for request body and method. --- abe/mocks.py | 19 ++++++++---- abe/unittest.py | 45 ++++++++++++++++++---------- tests/test_assertions.py | 63 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 106 insertions(+), 21 deletions(-) diff --git a/abe/mocks.py b/abe/mocks.py index 87e85bb..0cb4cd4 100644 --- a/abe/mocks.py +++ b/abe/mocks.py @@ -5,16 +5,11 @@ 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) - # map JSON fields to attributes self.__dict__ = data @@ -25,6 +20,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 index 0611446..9530d63 100644 --- a/abe/unittest.py +++ b/abe/unittest.py @@ -21,8 +21,8 @@ def load_sample(self, sample_path): """ Load a sample file into an AbeMock object. """ - sample_file = os.path.join(self.samples_root, sample_path) - return AbeMock(sample_file) + sample_filename = os.path.join(self.samples_root, sample_path) + return AbeMock.from_filename(sample_filename) def get_sample_request(self, path, label): """ @@ -107,7 +107,32 @@ def assert_headers_contain(self, response_data, spec_data): "header {0}".format(expected_header) ) - def assert_matches_sample(self, path, label, url, response): + def assert_matches_request(self, sample_request, wsgi_request): + """ + Check that the sample request and wsgi request match. + """ + self.assertEqual(wsgi_request.META['PATH_INFO'], sample_request['url']) + self.assertEqual(wsgi_request.META['REQUEST_METHOD'], + sample_request['method']) + + if 'headers' in sample_request: + self.assert_headers_contain( + wsgi_request.META, sample_request['headers'] + ) + + if 'body' in sample_request: + self.assert_data_equal(wsgi_request.POST, sample_request['body']) + + def assert_matches_response(self, sample_response, wsgi_response): + """ + Check that the sample response and wsgi response match. + """ + 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) + + def assert_matches_sample(self, path, label, response): """ Check a URL and response against a sample. @@ -115,8 +140,6 @@ def assert_matches_sample(self, path, label, url, response): The name of the sample file, e.g. 'query.json' :param label: The label for a specific sample request/response, e.g. 'OK' - :param url: - The actual URL we want to compare with the sample :param response: The actual API response we want to match with the sample. It is assumed to be a Django Rest Framework response object @@ -125,13 +148,5 @@ def assert_matches_sample(self, path, label, url, response): sample_request = sample.examples[label].request sample_response = sample.examples[label].response - self.assertEqual(url, sample_request.url) - if 'headers' in sample_request: - self.assert_headers_contain( - response.request, sample_request.headers - ) - - self.assertEqual(response.status_code, sample_response.status) - if 'body' in sample_response: - response_parsed = response.data - self.assert_data_equal(response_parsed, sample_response.body) + self.assert_matches_response(sample_response, response) + self.assert_matches_request(sample_request, response.wsgi_request) diff --git a/tests/test_assertions.py b/tests/test_assertions.py index ee7f312..6a2dc18 100644 --- a/tests/test_assertions.py +++ b/tests/test_assertions.py @@ -1,5 +1,7 @@ from unittest import TestCase +from mock import Mock +from abe.mocks import AbeMock from abe.unittest import AbeTestMixin @@ -71,3 +73,64 @@ def test_requires_key_and_value_match(self): {'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": {}, + "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/' + }, + ) + + 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 + ) From e657e8f1c55ef9a68ac7d01175147b8567bdeec7 Mon Sep 17 00:00:00 2001 From: Alex Couper Date: Tue, 10 Nov 2015 14:59:37 +0100 Subject: [PATCH 15/26] Add deprecation warning. --- abe/mocks.py | 9 +++++++++ tests/data/sample.json | 34 ++++++++++++++++++++++++++++++++++ tests/test_assertions.py | 23 +++++++++++++++++++++++ 3 files changed, 66 insertions(+) create mode 100644 tests/data/sample.json diff --git a/abe/mocks.py b/abe/mocks.py index 0cb4cd4..e335057 100644 --- a/abe/mocks.py +++ b/abe/mocks.py @@ -1,4 +1,5 @@ import json +import warnings from supermutes.dot import dotify @@ -10,6 +11,14 @@ def __init__(self, data): Initialise an ABE mock from data. """ + 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 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 index 6a2dc18..9dd14d2 100644 --- a/tests/test_assertions.py +++ b/tests/test_assertions.py @@ -1,9 +1,14 @@ +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 TestDataListEqual(TestCase, AbeTestMixin): @@ -134,3 +139,21 @@ def test_assertion_error_if_post_data_mismatch(self): self.assert_matches_request( self.sample_request, self.mock_wsgi_request ) + + +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") + + mock = AbeMock(self.filename) + + self.assertEqual(len(w), 1) + self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) + + def test_from_filename(self): + mock = AbeMock.from_filename(self.filename) From 48c777d0d16cf279250f16803e77f5b2704a4353 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Wed, 18 Nov 2015 00:33:07 +0100 Subject: [PATCH 16/26] Support non-strict matching of samples - assert_matches_sample includes an optional argument to skip matching certain response fields --- .travis.yml | 2 +- abe/unittest.py | 80 ++++++++++++++++--------- abe/utils.py | 12 +++- ep.yml | 2 +- test-requirements.txt | 1 + tests/test_assertions.py | 124 ++++++++++++++++++++++++++++++++++++++- tests/test_utils.py | 9 +++ 7 files changed, 195 insertions(+), 35 deletions(-) create mode 100644 tests/test_utils.py diff --git a/.travis.yml b/.travis.yml index 115f452..78e8220 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,4 +8,4 @@ python: install: pip install -r test-requirements.txt script: - python -m unittest discover || python -m unittest - - flake8 abe + - flake8 abe tests diff --git a/abe/unittest.py b/abe/unittest.py index 9530d63..90a0b63 100644 --- a/abe/unittest.py +++ b/abe/unittest.py @@ -1,7 +1,7 @@ import os from .mocks import AbeMock -from .utils import to_unicode +from .utils import normalize, subkeys class AbeTestMixin(object): @@ -33,53 +33,69 @@ def get_sample_request(self, path, label): sample_request = sample.examples[label].request return sample_request.body - def assert_data_equal(self, data1, data2): + 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, ignore=None): """ Two elements are recursively equal + + :param ignore: + Names of fields to ignore """ + ignore = ignore or [] try: - if isinstance(data1, list): - self.assertIsInstance(data2, list) - self.assert_data_list_equal(data1, data2) - elif isinstance(data1, dict): - self.assertIsInstance(data2, dict) - self.assert_data_dict_equal(data1, data2) + if isinstance(real, list): + self.assertIsInstance(sample, list) + self.assert_data_list_equal(real, sample, ignore) + elif isinstance(real, dict): + self.assertIsInstance(sample, dict) + self.assert_data_dict_equal(real, sample, ignore) else: - data1 = to_unicode(data1) - data2 = to_unicode(data2) - self.assertIsInstance(data2, data1.__class__) - self.assertEqual(data1, data2) + self.assert_item_matches(real, sample) except AssertionError as exc: - message = str(exc) + '\n{}\n{}\n\n'.format(data1, data2) + message = str(exc) + '\n{}\n{}\n\n'.format(real, sample) raise type(exc)(message) - def assert_data_dict_equal(self, data1, data2): + def assert_data_dict_equal(self, real, sample, ignore=None): """ Two dicts are recursively equal without taking order into account """ + ignore = ignore or [] self.assertEqual( - len(data1), len(data2), + len(real), len(sample), msg='Number of elements mismatch: {} != {}\n'.format( - data1.keys(), data2.keys()) + real.keys(), sample.keys()) ) - for key in data1: - self.assertIn(key, data2) - self.assert_data_equal(data1[key], data2[key]) + for key in real: + if key not in ignore: + self.assertIn(key, sample) + inner_ignore = subkeys(ignore, key) + self.assert_data_equal(real[key], sample[key], inner_ignore) - def assert_data_list_equal(self, data1, data2): + def assert_data_list_equal(self, real, sample, ignore=None): """ Two lists are recursively equal, including ordering. """ + ignore = ignore or [] self.assertEqual( - len(data1), len(data2), + len(real), len(sample), msg='Number of elements mismatch: {} {}'.format( - data1, data2) + real, sample) ) exceptions = [] - for element, element2 in zip(data1, data2): + for real_item, sample_item in zip(real, sample): try: - self.assert_data_equal(element, element2) + self.assert_data_equal(real_item, sample_item, ignore) except AssertionError as exc: exceptions.append(exc) @@ -123,16 +139,19 @@ def assert_matches_request(self, sample_request, wsgi_request): if 'body' in sample_request: self.assert_data_equal(wsgi_request.POST, sample_request['body']) - def assert_matches_response(self, sample_response, wsgi_response): + def assert_matches_response(self, sample_response, wsgi_response, + ignore=None): """ Check that the sample response and wsgi response match. """ + ignore = ignore 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) + self.assert_data_equal( + response_parsed, sample_response.body, ignore) - def assert_matches_sample(self, path, label, response): + def assert_matches_sample(self, path, label, response, ignore=None): """ Check a URL and response against a sample. @@ -143,10 +162,15 @@ def assert_matches_sample(self, path, label, response): :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 ignore: + 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. """ + ignore = ignore 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) + self.assert_matches_response(sample_response, response, ignore=ignore) self.assert_matches_request(sample_request, response.wsgi_request) diff --git a/abe/utils.py b/abe/utils.py index 2d8af5f..a55fedb 100644 --- a/abe/utils.py +++ b/abe/utils.py @@ -16,15 +16,23 @@ def datetime_to_string(value): return representation -def to_unicode(data): +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) - else: + elif not isinstance(data, int): data = str(data) if not _PY3 and isinstance(data, str): data = unicode(data) return data + + +def subkeys(ignore, key): + new_keys = filter(lambda s: s.startswith(key + '.'), ignore) + new_keys = map(lambda s: s[len(key) + 1:], new_keys) + return new_keys diff --git a/ep.yml b/ep.yml index 52a0ba0..9f0ce22 100644 --- a/ep.yml +++ b/ep.yml @@ -4,7 +4,7 @@ dependencies: version: ">=2.6.0" file: test-requirements.txt run: - - flake8 abe + - flake8 abe tests - coverage erase - coverage run --omit="*/tests/*","*$VIRTUAL_ENV*" -m unittest discover - coverage html diff --git a/test-requirements.txt b/test-requirements.txt index 5f691f1..021d3f6 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -2,3 +2,4 @@ flake8 coverage +mock diff --git a/tests/test_assertions.py b/tests/test_assertions.py index 9dd14d2..3a70720 100644 --- a/tests/test_assertions.py +++ b/tests/test_assertions.py @@ -10,9 +10,35 @@ DATA_DIR = join(dirname(abspath(__file__)), 'data') -class TestDataListEqual(TestCase, AbeTestMixin): +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]) @@ -141,6 +167,98 @@ def test_assertion_error_if_post_data_mismatch(self): ) +class TestAssertMatchesResponse(TestCase, AbeTestMixin): + + def setUp(self): + abe_mock = AbeMock({ + "method": "POST", + "url": "/resource/", + "examples": { + "OK": { + "response": { + "status": 201, + "body": { + "id": 12, + "name": "My Resource", + "url": "http://example.com/resource/12", + "author": { + "name": "Slough", + "url": "http://example.com/user/25" + } + } + } + } + } + }) + self.sample_response = abe_mock.examples['OK'].response + + def test_response_matches_strictly(self): + 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( + self.sample_response, response + ) + + def test_non_strict_response_matches(self): + 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( + self.sample_response, response, ignore=['id', 'url', 'author.url'] + ) + + def test_non_strict_list_value_matches(self): + abe_mock = AbeMock({ + "url": "/resource/", + "method": "GET", + "examples": { + "OK": { + "response": { + "status": 200, + "body": { + "contributors": [ + {"name": "Jack", "id": 1}, + {"name": "Jill", "id": 2}, + ] + } + } + } + } + }) + sample = abe_mock.examples['OK'].response + response = Mock() + response.status_code = 200 + response.data = { + "contributors": [ + {"name": "Jack", "id": 12}, + {"name": "Jill", "id": 23}, + ] + } + + self.assert_matches_response( + sample, response, ignore=['contributors.id'] + ) + + class TestFilenameInstantiation(TestCase): def setUp(self): @@ -150,10 +268,10 @@ def test_can_still_use_deprecated_instantiation(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") - mock = AbeMock(self.filename) + AbeMock(self.filename) self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) def test_from_filename(self): - mock = AbeMock.from_filename(self.filename) + 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']) From fbecfe405182d3006d36f8619aa9ffc65515fa7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Wed, 18 Nov 2015 22:22:05 +0100 Subject: [PATCH 17/26] Make python3 compatible --- abe/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/abe/utils.py b/abe/utils.py index a55fedb..0f47608 100644 --- a/abe/utils.py +++ b/abe/utils.py @@ -34,5 +34,5 @@ def normalize(data): def subkeys(ignore, key): new_keys = filter(lambda s: s.startswith(key + '.'), ignore) - new_keys = map(lambda s: s[len(key) + 1:], new_keys) + new_keys = list(map(lambda s: s[len(key) + 1:], new_keys)) return new_keys From 56a92359326eb08add69fad9f3f6965fd61fd6ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Thu, 19 Nov 2015 09:21:26 +0100 Subject: [PATCH 18/26] Rename ignore to non_strict --- abe/unittest.py | 71 ++++++++++++++++++++++++---------------- abe/utils.py | 12 +++++-- tests/test_assertions.py | 5 +-- 3 files changed, 56 insertions(+), 32 deletions(-) diff --git a/abe/unittest.py b/abe/unittest.py index 90a0b63..d163a43 100644 --- a/abe/unittest.py +++ b/abe/unittest.py @@ -44,48 +44,50 @@ def assert_item_matches(self, real, sample): sample = normalize(sample) self.assertEqual(real, sample) - def assert_data_equal(self, real, sample, ignore=None): + def assert_data_equal(self, real, sample, non_strict=None): """ Two elements are recursively equal - :param ignore: - Names of fields to ignore + :param non_strict: + Names of fields to match non-strictly. In current implementation, + only check for field presence. """ - ignore = ignore or [] + non_strict = non_strict or [] try: if isinstance(real, list): self.assertIsInstance(sample, list) - self.assert_data_list_equal(real, sample, ignore) + self.assert_data_list_equal(real, sample, non_strict) elif isinstance(real, dict): self.assertIsInstance(sample, dict) - self.assert_data_dict_equal(real, sample, ignore) + 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, ignore=None): + def assert_data_dict_equal(self, real, sample, non_strict=None): """ Two dicts are recursively equal without taking order into account """ - ignore = ignore or [] + 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 real: - if key not in ignore: + if key not in non_strict: self.assertIn(key, sample) - inner_ignore = subkeys(ignore, key) - self.assert_data_equal(real[key], sample[key], inner_ignore) + 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, ignore=None): + def assert_data_list_equal(self, real, sample, non_strict=None): """ Two lists are recursively equal, including ordering. """ - ignore = ignore or [] + non_strict = non_strict or [] self.assertEqual( len(real), len(sample), msg='Number of elements mismatch: {} {}'.format( @@ -95,7 +97,7 @@ def assert_data_list_equal(self, real, sample, ignore=None): exceptions = [] for real_item, sample_item in zip(real, sample): try: - self.assert_data_equal(real_item, sample_item, ignore) + self.assert_data_equal(real_item, sample_item, non_strict) except AssertionError as exc: exceptions.append(exc) @@ -123,35 +125,44 @@ def assert_headers_contain(self, response_data, spec_data): "header {0}".format(expected_header) ) - def assert_matches_request(self, sample_request, wsgi_request): + def assert_matches_request(self, sample_request, wsgi_request, + non_strict=None): """ Check that the sample request and wsgi request match. """ - self.assertEqual(wsgi_request.META['PATH_INFO'], sample_request['url']) - self.assertEqual(wsgi_request.META['REQUEST_METHOD'], - sample_request['method']) + non_strict = non_strict or [] - if 'headers' in sample_request: + 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 'body' in sample_request: + if 'body' in sample_request and 'body' not in non_strict: self.assert_data_equal(wsgi_request.POST, sample_request['body']) def assert_matches_response(self, sample_response, wsgi_response, - ignore=None): + non_strict=None): """ Check that the sample response and wsgi response match. """ - ignore = ignore or [] + 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, ignore) + response_parsed, sample_response.body, non_strict) - def assert_matches_sample(self, path, label, response, ignore=None): + def assert_matches_sample( + self, path, label, response, non_strict_response=None, + non_strict_request=None + ): """ Check a URL and response against a sample. @@ -162,15 +173,19 @@ def assert_matches_sample(self, path, label, response, ignore=None): :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 ignore: + :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. """ - ignore = ignore or [] + 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, ignore=ignore) - self.assert_matches_request(sample_request, response.wsgi_request) + 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 index 0f47608..733df80 100644 --- a/abe/utils.py +++ b/abe/utils.py @@ -32,7 +32,15 @@ def normalize(data): return data -def subkeys(ignore, key): - new_keys = filter(lambda s: s.startswith(key + '.'), ignore) +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/tests/test_assertions.py b/tests/test_assertions.py index 3a70720..7d3f5a4 100644 --- a/tests/test_assertions.py +++ b/tests/test_assertions.py @@ -223,7 +223,8 @@ def test_non_strict_response_matches(self): } self.assert_matches_response( - self.sample_response, response, ignore=['id', 'url', 'author.url'] + self.sample_response, response, + non_strict=['id', 'url', 'author.url'] ) def test_non_strict_list_value_matches(self): @@ -255,7 +256,7 @@ def test_non_strict_list_value_matches(self): } self.assert_matches_response( - sample, response, ignore=['contributors.id'] + sample, response, non_strict=['contributors.id'] ) From ec6bc59f080bfc711922a9626a7b59305f46ea0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Thu, 19 Nov 2015 09:21:53 +0100 Subject: [PATCH 19/26] Extend build commands to run doctests --- .travis.yml | 1 + ep.yml | 1 + 2 files changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index 78e8220..8243793 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,4 +8,5 @@ python: 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/ep.yml b/ep.yml index 9f0ce22..89f3ee2 100644 --- a/ep.yml +++ b/ep.yml @@ -8,6 +8,7 @@ run: - 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 From 50d4e1a69dfeb30542402f3cf6d7c436c7068322 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Thu, 19 Nov 2015 10:21:51 +0100 Subject: [PATCH 20/26] Ensure all sample keys are in real response data. - Includes additional coverage of strict/non-strict mismatching --- abe/unittest.py | 4 +- tests/test_assertions.py | 191 +++++++++++++++++++++++++++++++-------- 2 files changed, 154 insertions(+), 41 deletions(-) diff --git a/abe/unittest.py b/abe/unittest.py index d163a43..6e49c03 100644 --- a/abe/unittest.py +++ b/abe/unittest.py @@ -76,9 +76,9 @@ def assert_data_dict_equal(self, real, sample, non_strict=None): msg='Number of elements mismatch: {} != {}\n'.format( real.keys(), sample.keys()) ) - for key in real: + for key in sample: + self.assertIn(key, real) if key not in non_strict: - self.assertIn(key, sample) inner_non_strict = subkeys(non_strict, key) self.assert_data_equal( real[key], sample[key], inner_non_strict) diff --git a/tests/test_assertions.py b/tests/test_assertions.py index 7d3f5a4..1dbd796 100644 --- a/tests/test_assertions.py +++ b/tests/test_assertions.py @@ -167,32 +167,32 @@ def test_assertion_error_if_post_data_mismatch(self): ) +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 setUp(self): - abe_mock = AbeMock({ - "method": "POST", - "url": "/resource/", - "examples": { - "OK": { - "response": { - "status": 201, - "body": { - "id": 12, - "name": "My Resource", - "url": "http://example.com/resource/12", - "author": { - "name": "Slough", - "url": "http://example.com/user/25" - } - } - } + 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" } } }) - self.sample_response = abe_mock.examples['OK'].response - - def test_response_matches_strictly(self): response = Mock() response.status_code = 201 response.data = { @@ -206,10 +206,41 @@ def test_response_matches_strictly(self): } self.assert_matches_response( - self.sample_response, 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 = { @@ -223,29 +254,86 @@ def test_non_strict_response_matches(self): } self.assert_matches_response( - self.sample_response, response, + sample, response, non_strict=['id', 'url', 'author.url'] ) - def test_non_strict_list_value_matches(self): - abe_mock = AbeMock({ - "url": "/resource/", - "method": "GET", - "examples": { - "OK": { - "response": { - "status": 200, - "body": { - "contributors": [ - {"name": "Jack", "id": 1}, - {"name": "Jill", "id": 2}, - ] - } - } + def test_non_strict_response_mismatch(self): + sample = _abe_wrap_response({ + "status": 201, + "body": { + "author": { + "name": "Some", + "url": "http://example.com/user/1" } } }) - sample = abe_mock.examples['OK'].response + 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 = { @@ -259,6 +347,31 @@ def test_non_strict_list_value_matches(self): 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): From e4da4d0c0d420164ca3e3839967cd9de1fe61acc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Thu, 19 Nov 2015 11:12:37 +0100 Subject: [PATCH 21/26] Increase version to 0.3.0 --- abe/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/abe/__init__.py b/abe/__init__.py index d93b5b2..0404d81 100644 --- a/abe/__init__.py +++ b/abe/__init__.py @@ -1 +1 @@ -__version__ = '0.2.3' +__version__ = '0.3.0' From 0a059b5fd5248c342c5f0c147ff89c9c38fcd03a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Thu, 19 Nov 2015 23:45:42 +0100 Subject: [PATCH 22/26] Bug in non-strict request --- abe/unittest.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/abe/unittest.py b/abe/unittest.py index 6e49c03..80a65a9 100644 --- a/abe/unittest.py +++ b/abe/unittest.py @@ -144,8 +144,9 @@ def assert_matches_request(self, sample_request, wsgi_request, wsgi_request.META, sample_request['headers'] ) - if 'body' in sample_request and 'body' not in non_strict: - self.assert_data_equal(wsgi_request.POST, sample_request['body']) + 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): From db1c556a1b1d0692deaed8bda605bf43cc4b48ec Mon Sep 17 00:00:00 2001 From: Alex Couper Date: Fri, 20 Nov 2015 09:34:19 +0100 Subject: [PATCH 23/26] Add test for non-strict post requets. --- tests/test_assertions.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/test_assertions.py b/tests/test_assertions.py index 1dbd796..0059d84 100644 --- a/tests/test_assertions.py +++ b/tests/test_assertions.py @@ -166,6 +166,12 @@ def test_assertion_error_if_post_data_mismatch(self): 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 _abe_wrap_response(response): abe_mock = AbeMock({ From d482121e0f767651a11738ac63a90aff2317f613 Mon Sep 17 00:00:00 2001 From: Alex Couper Date: Wed, 12 Oct 2016 17:13:28 +0000 Subject: [PATCH 24/26] Test query params --- abe/unittest.py | 19 +++++++++++++++++++ tests/test_assertions.py | 15 +++++++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/abe/unittest.py b/abe/unittest.py index 80a65a9..0296e12 100644 --- a/abe/unittest.py +++ b/abe/unittest.py @@ -1,4 +1,5 @@ import os +import urlparse from .mocks import AbeMock from .utils import normalize, subkeys @@ -125,6 +126,18 @@ def assert_headers_contain(self, response_data, spec_data): "header {0}".format(expected_header) ) + def assert_query_params_equal(self, request_data, spec_data): + qs = urlparse.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): """ @@ -144,6 +157,12 @@ def assert_matches_request(self, sample_request, wsgi_request, 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) diff --git a/tests/test_assertions.py b/tests/test_assertions.py index 0059d84..5d76c8e 100644 --- a/tests/test_assertions.py +++ b/tests/test_assertions.py @@ -115,7 +115,10 @@ def setUp(self): "examples": { "OK": { "request": { - "queryParams": {}, + "queryParams": { + "foo": "1", + "bar": "2" + }, "body": { "name": "My Resource" }, @@ -133,7 +136,8 @@ def setUp(self): META={ 'HTTP_THIS_CUSTOM_HEADER': 'Foo', 'REQUEST_METHOD': 'POST', - 'PATH_INFO': '/resource/' + 'PATH_INFO': '/resource/', + 'QUERY_STRING': 'foo=1&bar=2' }, ) @@ -172,6 +176,13 @@ def test_matches_non_strict(self): 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({ From c6e27907f40398c5e92c8557439140eeb2ba7332 Mon Sep 17 00:00:00 2001 From: Alex Couper Date: Wed, 12 Oct 2016 17:21:34 +0000 Subject: [PATCH 25/26] Py3K --- abe/unittest.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/abe/unittest.py b/abe/unittest.py index 0296e12..46d1a28 100644 --- a/abe/unittest.py +++ b/abe/unittest.py @@ -1,5 +1,8 @@ import os -import urlparse +try: + from urlparse import parse_qs +except ImportError: + from urllib.parse import parse_qs from .mocks import AbeMock from .utils import normalize, subkeys @@ -127,7 +130,7 @@ def assert_headers_contain(self, response_data, spec_data): ) def assert_query_params_equal(self, request_data, spec_data): - qs = urlparse.parse_qs(request_data) + qs = parse_qs(request_data) for k, expected_value in spec_data.items(): try: actual_value = qs[k] From 1403710be46786583819f2909b0f89af02963cde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carles=20Barrobe=CC=81s?= Date: Wed, 12 Oct 2016 22:01:35 +0200 Subject: [PATCH 26/26] Increase version to 0.4.0 --- abe/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/abe/__init__.py b/abe/__init__.py index 0404d81..abeeedb 100644 --- a/abe/__init__.py +++ b/abe/__init__.py @@ -1 +1 @@ -__version__ = '0.3.0' +__version__ = '0.4.0'