DjangoRestFramework API checker¶
This module offers some utilities to avoid unwanted changes in Django Rest Framework responses, so to keep stable contracts
The purpose is to guarantee that any code changes never introduce ‘contract violations’ changing the Serialization behaviour.
Contract violations can happen when:
- fields are removed from Serializer
- field representation changes (ie. date/number format, )
- Response status code changes (optional)
- Response headers change (optional)
How it works:¶
First time the test run, the response and model instances are serialized and saved on the disk; any further execution is checked against this first response.
Test data are saved in the same directory where the test module lives,
Fields that cannot be checked by value (ie timestamps/last modified) can be tested writing
In case of nested objects, method names must follow the field “path”.
This module can also intercept when a field is added,
in this case it is mandatory recreate stored test data; simply delete them from the disk
API_CHECKER_RESET environment variable and run the test again,
In case something goes wrong the output will be
Field values mismatch
AssertionError: View `<class 'path.to.module.CustomerListAPIView>` breaks the contract. Field `name` does not match. - expected: `Partner 0` - received: `Partner 11`
AssertionError: View `<class 'path.to.module.CustomerListAPIView'>` breaks the contract. Field `id` is missing in the new response
AssertionError: View `<class 'path.to.module.CustomerListAPIView'>` returned more field than expected. Action needed api_customers.response.json need rebuild. New fields are: `['country']`
Support for django test is provided by:
pytest is supported via decorators: