Python Forum

Full Version: Pytest and rootdirectory
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello.

I have a lot of tests and run with pytest. Some code (in product, not in tests) perform operations like os.chdir(some_dir), thus tests which are looking for some testdata always fail after that if I run all tests. And these tests always work if run them separately. So, the question is - how to return back to root directory for each test? Probably, it should be a fixture, but how to determine root directory? Setup some variable during the first run?
Just issue another os.chdir to your base directory before executing each test.
Yeah, I was thinking about it. But how to determine and store my base directory if I can't hardcode absolute path? i.e. it will be running on any machine
using os, I usually set my starting directory as the directory containing the script,
then set everything relative from there using pathlib.

the os command I issue during script initialization is:
os.chdir(os.path.abspath(os.path.dirname(__file__)))
then using pathlib, immediately after that:
# add at top with other imports:
from pathlib import Path
...
# somewhere in initialization:
homepath = Path('.')
base_path = homepath / '..' / 'data'
Once this is established, you can set relative paths from there
widgetpath = base_path / 'widgets'

zingo_widgetfile = widgetpath / 'zingo.dat'
with zingo_widgetfile.open() as fp:
    zingodata = fp.read()
etc.
Nice, but I decided to solve it in the following way:
import os
import pytest


WORKING_DIR = None


@pytest.fixture
def working_dir(autouse=True, scope='function'):
    global WORKING_DIR
    if not WORKING_DIR:
        WORKING_DIR = os.getcwd()
    os.chdir(WORKING_DIR)
    return WORKING_DIR