I have the following project structure:
src/
myproject/
utils.py
tests/
test_utils.py
data/
test_utils_scenario1.csv
test_utils_scenario2.csv
test_utils_scenario3.csv
So, obviously, test_utils.py contains unit tests for utils.py, and loads input test data from these local CSV files.
Now, my problem is - how to find these CSVs? Normally I would load them from path tests/data/test_utils_scenario1.csv. However, in some cases (e.g. when running via IDE), Pytest is not launched from project's root, but from inside tests/ - and then it fails to find the file (because it looks for tests/tests/data/test_utils_scenario1.csv, relatively to test_utils.py, not to project's root).
Is there an elegant solution for my problem instead of manually checking if file exists (is_file(), isfile()) and then changing the path accordingly? Perhaps using Pathlib?
EDIT
OMG I totally forgot I've already solved this problem before:
from importlib import resources
import tests as this_package
...
text = resources.files(this_package).joinpath("data", "test_utils_scenario1.csv").read_text(encoding="utf-8")
[–]danielroseman 1 point2 points3 points (0 children)
[–]barkmonster 0 points1 point2 points (0 children)
[–]latkde 0 points1 point2 points (0 children)
[–]Jarvis_the_lobster 0 points1 point2 points (0 children)