python unittest: relative paths to files – pycharm vs cli

Question:

I have unittests that require access to files. this is due to the nature of the project that generates files as output and I want to compare to the expected output.

Currently my directory structure is:

project root/tests/files

In the test setup I have the following:

 def setUp(self):
    self.test_file = 'files/my_reference.txt'

Running this test in pycharm works perfectly fine.

I now want to create a github actions that runs these tests on push (especially to also be able to test easily on different OS). For that I have the command:

python -m unittest discover -s ./tests  -p "*_tests.py"

However this command fail locally as all the test files are not found as this runs in the root folder so the relative path is wrong. (eg it will look in project root/files instead of project root/tests/files. When changing the cwd to project root/tests, then the test fails because it then can’t find my module that is being tested (obviously).

So how do I have to set the paths to the test files correctly so that running the test works in pycharm and by cli/github actions?

Asked By: beginner_

||

Answers:

Try:

export PYTHONPATH=/project-root
cd /project-root/tests

python -m unittest discover -s ./ -p "*_tests

PYTHONPATH changes sys.path, which is where the python interpreter searches for modules when importing modules.

It changes how import works, but maybe not how CLI works, hence you may need to create a custom py-script in tests folder which imports the unittest module.


Of course, another option would be hard-coding little more:

def setUp(self):
    self.test_file = 'tests/files/my_reference.txt'

I mean, cd-ing into tests folder may break other tests.

Answered By: Top-Master