Unit Testing
Overview - pytest¶
Library has a pytest plugin, with the objective of clearing out dependencies at the start of each unit test run.
This use useful when session/clients needs to be created after a mock installed. If the code-base uses a Dependency to grab a requests-session (for example), when a new unit-test runs it will allocate a new requests session, and mock will therefore work and start out blank, ready to be configured by the unit-test function that is currently running.
While at the same time the code in prod/deployed code it will just use a shared session via the dependency, as that will stick around between lambda events, and so on and allow code to reuse already established connections (which is what you want to happen in deployed code).
All you need to do is write a normal unit-test to take advantage of this feature:
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | |
Implementation Details¶
This is just extra info in case your intrested.
Before the start of each pytest unit-test function run, the current dependencies are deactivated and a new blank XContext (which contains the dependencies) is created.
This means that by default, at the start of each running unit test function there will be no dependencies 'visible'.
PyTest Plugin Details
This project contains a pytest plugin to automatically install a brand-new app-root and thread-root XContext's at the start of each unit test run.
This is important, it ensures a blank root-context is used each time a unit test executes.
This is accomplished via an autouse=True fixture.
The fixture is in a pytest plugin module. This plugin module is automatically found and loaded by pytest. pytest checks all installed dependencies in the environment it runs in, so as long as xinject is installed in the environment as a dependency it will find this and autoload this fixture for each unit test.
If curious The xinject_test_context
fixture is how it's implemented.
The result is for each unit test executed via pytest, it will always start with no resources from a previous unit-test execution. So no dependencies changes/state will 'leak' between each unit test function run.
Each unit-test will therefore always start out in the same state. This allows each unit test to run in any order, as it should not affect the dependencies of the next unit-test function that runs.