Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pytest and rootdirectory

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:
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 as fp:
    zingodata =
Nice, but I decided to solve it in the following way:
import os
import pytest


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

Possibly Related Threads…
Thread Author Replies Views Last Post
  Pytest with requests a21250450 3 1,374 Mar-21-2019, 03:24 PM
Last Post: buran
  pytest and caplog lazyliv 0 1,985 May-16-2018, 02:36 PM
Last Post: lazyliv

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020