Deleting py.test tmpdir directory after successful test case

Kanguros picture Kanguros · Jun 1, 2016 · Viewed 7.5k times · Source

I'm running tests that create a lot of large files during execution. For this purpose I would like to delete the tmpdir directory if a test has passed. But if a test fails the contents of tmpdir should be left unchanged.

I know how to determine the result of the test:

from _pytest.runner import runtestprotocol

def pytest_runtest_protocol(item, nextitem):
    reports = runtestprotocol(item, nextitem=nextitem)
    for report in reports:
        if report.when == 'call':
            # value will be set to passed or filed
            test_outcome = report.outcome
            # But what next?

return True

but I don't know how to find out the path of the created tmpdir directory.

Answer

Nils Werner picture Nils Werner · Jun 1, 2016

You should create a tmpdir fixture that creates the tempdir, passes it into your code and afterwards deletes it.

Additionally, the fixture must be set to always delete the tempdir, even on failure. Otherwise you may leave behind an unclean state, which could cause other tests to fail (without the user noticing).

Instead I recommend either

  1. Using --pdb to drop into Python Debugger on errors. The fixture will not yet have cleaned up and you can inspect the files.
  2. Creating a custom option that allows you to disable cleanup of the tmpdir.
  3. Creating a custom tmpdir fixture that copies all tmpfiles to a user-configurable place (again, using a custom option) and cleans up the tmpdir afterwards.

In any case an unclean tmpdir state will be a conscious decision by the user and will prevent unexpected sideeffects.