Question: 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.

* When pytest is executed from the `sub_suite` folder (using CLI or IDE "play" button), the files are generated in the `sub_suite` folder, where I want them to be.
* However, when pytest is run from the `system_tests` folder to run all tests, all artifacts are created in the `system_tests` folder, which is not what I want.

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?

Answer: 
Instead of creating a fixture for each directory like suggested by @DV82XL you can simply use `monkeypatch` to achieve the same:

```py
import pytest
from pathlib import Path

@pytest.fixture
def base_path() -> Path:
    """Get the current folder of the test"""
    return Path(__file__).parent

def test_something(base_path: Path, monkeypatch: pytest.MonkeyPatch):
    monkeypatch.chdir(base_path / "data" )
    # Do something in the data folder

```
A different and, IMHO more robust approach: always reference your files by the complete path.

`__file__` is an automatically declared Python variable that is the name of the current module. So in your `test_B.py` file, it would have the value: `system_tests/suite_2/sub_suite_2a/test_B.py`. Just get the parent and choose where to write your files.

```
from pathlib import Path
test_data_dir = Path(__file__).parent / "test_data"

```

Now you have all of them in the same place and can tell your version control system to ignore them.

If the code is inside a library, better use an absolute path:

```
import os
from pathlib import Path

test_data_dir = Path(__file__).parent.absolute() / "test_data"

```