Pytest and rootdirectory - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Pytest and rootdirectory (/thread-27262.html) |
Pytest and rootdirectory - Master_Sergius - May-31-2020 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?
RE: Pytest and rootdirectory - Larz60+ - Jun-01-2020 Just issue another os.chdir to your base directory before executing each test. RE: Pytest and rootdirectory - Master_Sergius - Jun-01-2020 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 RE: Pytest and rootdirectory - Larz60+ - Jun-01-2020 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. RE: Pytest and rootdirectory - Master_Sergius - Jun-01-2020 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 |