Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pytest where test in subfolder

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

like image 258
Noam Avatar asked Nov 26 '17 16:11

Noam


People also ask

Where do I put the pytest test?

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.

Is there a way to specify which pytest tests to run from a file?

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 .

How do I run multiple tests in pytest?

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.


2 Answers

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

like image 200
klapshin Avatar answered Sep 18 '22 07:09

klapshin


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.

like image 25
A. Hendry Avatar answered Sep 20 '22 07:09

A. Hendry