Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
What actually is a pytest fixture?
Pytest uses fixtures. Their docs explain what fixtures do: https://docs.pytest.org/en/stable/explanation/fixtures.html
But what actually is a fixture? Is there a definition for it? Is this a term from computer science, or something pytest invented?
1 answer
The term long predates Pytest and is not at all specific to Python. The idea is described on Wikipedia:
In the context of software a test fixture (also called "test context") is used to set up system state and input data needed for test execution.[2][3] For example, the Ruby on Rails web framework uses YAML to initialize a database with known parameters before running a test.[4] This allows for tests to be repeatable, which is one of the key features of an effective test framework.[2]
Essentially, it's some object that the test framework (Pytest in this case) creates automatically to represent the environment in which the test code will run - a dependency which is injected into the code, similar to a "context" variable passed to a drawing function in JavaScript.
In the Pytest implementation, the dependency injection takes the form of automatically passing that object as a parameter to the test code; when Pytest analyzes a test module to "discover" tests, it also dynamically sets up the necessary logic to construct and pass that value, along with whatever else might be required (such as parameter values for a parametrized test).
There are simpler, if less automatic, ways to do this sort of thing, too. For example, one could simply set up a global variable (such that the calling code finds it in the enclosing global scope), and use a context manager to repeatedly initialize the environment, call a test function and clean up again.
The term is used by analogy from electronic and other physical devices: in these cases, the fixture physically fixes the device in place for testing, to ensure consistent and reproducible test conditions.
1 comment thread