I'm using python pytest to run my unit tests. My project folders are:
Main
- contains data file: A.txt
Main\Tests
- the folder from which I run pytest
Main\Tests\A_test
- folder that contains a test file
The test in A_test folder uses the file A.txt
(that is in Main folder).
My problem is that when I run py.test the test fails because it can't find A.txt
.
I found out that it is because pytest uses the path Main\Test
when running the test instead of changing the path to Main\Tests\A_test
(I'm using relative path when opening A.txt
inside the test file)
My question: is there a way to make pytest change directory to the folder of the test it executes for each test? so that relative paths inside the tests will still work?
Is there some other generic way to solve it? (I don't want to change everything to absolute paths or something like this, also this is an example, in real life I have several hundreds tests).
Thank you,
Noam
While the pytest discovery mechanism can find tests anywhere, pytests must be placed into separate directories from the product code packages. These directories may either be under the project root or under the Python package.
Running pytestWe can run a specific test file by giving its name as an argument. A specific function can be run by providing its name after the :: characters. Markers can be used to group tests. A marked grouped of tests is then run with pytest -m .
Run Multiple Tests From a Specific File and Multiple Files To run all the tests from all the files in the folder and subfolders we need to just run the pytest command. This will run all the filenames starting with test_ and the filenames ending with _test in that folder and subfolders under that folder.
Assuming you need your root Main
in the sys.path
.
Giving your current dir is Main/
:
$python -m pytest Tests/A_test
This will append Main
to the sys.path
and run tests in the A_test
subdirectory.
More about pythonpath and pytest relationship here: http://doc.pytest.org/en/latest/pythonpath.html#pythonpath
I think the "truest" answer (perhaps subject to opinion) comes from the pytest docs themselves: the testpaths
configuration option can be set in a setup.cfg
, pytest.ini
, tox.ini
, or pyroject.toml
file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With