Home > Net >  Change the directory that pytest uses for testing, but not output location
Change the directory that pytest uses for testing, but not output location

Time:06-21

I have this kind of directory structure:

repo/
├── src/
|   ├── assets
|   |   └── wordlist.txt
|   └── main.py
└── tests
     └── test_cases.py

And I want to test a class in the main.py file. That classes reads from a word list in the assets directory. But when i run the test from the tests directory it uses that directory as the starting point so when init. the class it can't find the word list. And I get the error FileNotFoundError: [Errno 2] No such file or directory: assets/wordlist.txt .

So how do I change the directory pytest usages for the test but still keep the output in the tests folder. I tried to use the pytest.ini file and change the pythonpath = . src but that just seems to move the output to the repo directory and keeps the file not found error.

CodePudding user response:

I fixed the issue, but not by changing the the setting for pytest. But by changing my input path, so instead of hardcoding it in like assets/wordlists.txt. I changed it to:

directory_path = os.path.dirname(os.path.abspath(__file__))
new_path = os.path.join(directory_path, "assets/English_5words.txt")
  • Related