Testscenarios is a Python library that extends `unittest` to provide clean dependency injection, enabling a single test method to be run with multiple scenarios. This is particularly useful for interface testing (testing many implementations via a single test suite) or for classic dependency injection, where test dependencies are provided externally. The library is currently at version 0.5.0, offering a stable approach to scenario-based testing.
pip install testscenariosVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates defining multiple scenarios directly within a `unittest.TestCase` by inheriting from `TestWithScenarios`. Each scenario is a tuple containing a descriptive name and a dictionary of parameters. These parameters are injected as instance attributes into the test method when executed, allowing the same test logic to run with different data sets. To run, save as a Python file and execute with `python -m unittest your_test_file.py`.
Ensure `TestWithScenarios` is the leftmost base class (e.g., `class MyTest(TestWithScenarios, unittest.TestCase):`). Avoid overriding `run()` or `__call__()` in your test classes.
Always access the scenario-provided module/dependency via `self.attribute_name` within your test methods, where `attribute_name` is defined in your scenario dictionary.
If dynamic scenario generation is needed, ensure that scenarios are uniquely generated or cloned per test object if there's a risk of shared state, or use the `load_tests` hook (e.g., `load_tests_apply_scenarios`) which explicitly handles scenario generation before tests are added to the suite.
Ensure your project runs on Python 3.10 or a newer compatible version.