I'm using a joblib.Memory
to cache expensive computations when running tests with py.test
. The code I'm using reduces to the following,
from joblib import Memory
memory = Memory(cachedir='/tmp/')
@memory.cache
def expensive_function(x):
return x**2 # some computationally expensive operation here
def test_other_function():
input_ds = expensive_function(x=10)
## run some tests with input_ds
which works fine. I'm aware this could be possibly more elegantly done with tmpdir_factory
fixture but that's beside the point.
The issue I'm having is how to clean the cached files once all the tests run,
pytest-cache 1.0 The plugin provides two options to rerun failures, namely --lf to only re-run the failures and --ff to run all tests but the failures from the last run first. For cleanup (usually not needed), a --clearcache option allows to remove all cross-session cache contents ahead of a test run.
The pytest-cache plugin adds a config. cache object during the configure-initialization of pytest. This allows other plugins, including conftest.py files, to safely and flexibly store and retrieve values across test runs because the config object is available in many places.
conftest.py is where you setup test configurations and store the testcases that are used by test functions. The configurations and the testcases are called fixture in pytest.
Repeating a test Each test collected by pytest will be run count times. If you want to override default tests executions order, you can use --repeat-scope command line option with one of the next values: session , module , class or function (default). It behaves like a scope of the pytest fixture.
is it possible to share a global variable among all tests (which would contains e.g. a list of path to the cached objects) ?
I wouldn't go down that path. Global mutable state is something best avoided, particularly in testing.
is there a mechanism in py.test to call some command once all the tests are run (whether they succeed or not)?
Yes, add an auto-used session-scoped fixture into your project-level conftest.py
file:
# conftest.py
import pytest
@pytest.yield_fixture(autouse=True, scope='session')
def test_suite_cleanup_thing():
# setup
yield
# teardown - put your command here
The code after the yield will be run - once - at the end of the test suite, regardless of pass or fail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With