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
Well I kind of solved it, not sure it is the best way but it is working:
In each of the tests:
\Main\Tests\Main\Tests then I chdir to \Main\Tests\A_testI do this under the def setUpClass method.
For example:
@classmethod
def setUpClass(cls):
if (os.path.exists(os.path.join(os.curdir, "A_test"))):
os.chdir("A_test")
This makes the test pass no matter if it is executed from Tests folder (with pytest) or from A_test folder (through pycharm)