Here are two common ways to “move” your test‐data out into a resources/ folder so that your tests stay tidy.
1) Treat resources/ as plain files and read from disk
Project layout
myproject/
├── src/
│ └── constants.py ← your production code
└── tests/
├── resources/
│ └── welcome.txt ← just a text file
└── test_reading.py
-
Create tests/resources/welcome.txt
Hello, pytest!
-
In your test, use pathlib (or even open) to load it:
# tests/test_reading.py
from pathlib import Path
def test_welcome_length():
# locate the file next to this test:
p = Path(__file__).parent / "resources" / "welcome.txt"
text = p.read_text(encoding="utf-8")
assert text.startswith("Hello")
assert len(text) > 0
pytest will happily run that—no imports, no packaging, just file I/O.
2) Treat resources/ as a Python package
If you’d rather import constants from a module, turn resources/ into a mini‐package:
myproject/
├── src/
│ └── constants.py
└── tests/
├── resources/
│ ├── __init__.py ← makes it a package
│ └── constants.py ← defines WELCOME
└── test_reading.py
-
tests/resources/constants.py
# tests/resources/constants.py
WELCOME = "Hello, pytest!"
-
In your test, just import it:
# tests/test_reading.py
from tests.resources.constants import WELCOME
def test_welcome_length():
assert WELCOME.startswith("Hello")
pytest adds your project root to sys.path, so tests.resources will import out of the box.
3) (Bonus) Use importlib.resources for “real” package data
If you want to bundle files and access them via an API, you can leverage Python’s importlib.resources (3.7+):
myproject/
└── tests/
├── resources/
│ ├── __init__.py
│ └── welcome.txt
└── test_reading.py
# tests/test_reading.py
import importlib.resources as pkg_resources
import tests.resources as res_pkg
def test_welcome_length():
text = pkg_resources.read_text(res_pkg, "welcome.txt")
assert "Hello" in text
This approach keeps your tests portable (even if you zip them up) and avoids manual path juggling.
Pick whichever feels cleanest:
- File-based (
pathlib) if you just need a dump of text/data.
- Package-based if you want to import Python constants.
- importlib.resources if you want a little more robustness around package data.
Let me know if you need more details on any of these! 🚀