pythonpytestworking-directory

Change pytest working directory to test case directory


I have the following pytest directory structure:

system_tests/
  ├── conftest
  ├── pytest.ini
  │
  ├── suite_1/
  │    └── test_A.py
  │   
  └── suite_2/
       └── sub_suite_2a/
            └── test_B.py

When each test method runs, a number of third-party libraries/processes generate artifacts in the current working directory.

Is there an easy way to force pytest to always use the test class folder as the working directory so I get the same results regardless of how or where I run a test from?


Solution

  • EDIT: Improved Solution

    Using monkeypatch as suggested by @Kound removes the boilerplate code to restore the cwd. You can also enable autouse to automatically apply this fixture to all test functions. Add the following fixture to conftest.py to change the cwd for all tests:

    @pytest.fixture(autouse=True)
    def change_test_dir(request, monkeypatch):
        monkeypatch.chdir(request.fspath.dirname)
    

    Any processes that are kicked off by the test will use the test case folder as their working directory and copy their logs, outputs, etc. there, regardless of where the test suite was executed.

    Original Solution

    The following function-level fixture will change to the test case directory, run the test (yield), then change back to the calling directory to avoid side-effects, as suggested by @hi2meuk:

    @pytest.fixture
    def change_test_dir(request):
        os.chdir(request.fspath.dirname)
        yield
        os.chdir(request.config.invocation_params.dir)