To move test strings into a resources subdirectory and access them in pytest, here are several approaches:
1. Create a Python Module in the Resources Directory
Create a resources directory with an __init__.py file to make it a Python package:
project/
├── tests/
│ ├── __init__.py
│ ├── resources/
│ │ ├── __init__.py
│ │ └── test_strings.py
│ └── test_example.py
# tests/resources/test_strings.py
TEST_STRING = "Hello, World!"
API_URL = "https://api.example.com"
ERROR_MESSAGE = "Something went wrong"
# tests/test_example.py
from tests.resources.test_strings import TEST_STRING, API_URL
def test_string():
assert TEST_STRING == "Hello, World!"
2. Using Relative Imports
If your test file is in the same tests directory:
# tests/test_example.py
from .resources.test_strings import TEST_STRING
def test_string():
assert TEST_STRING == "Hello, World!"
3. Reading from Text/JSON Files
For larger strings or data, you might want to use actual resource files:
project/
├── tests/
│ ├── resources/
│ │ ├── test_data.json
│ │ └── sample_text.txt
│ └── test_example.py
# tests/test_example.py
import json
from pathlib import Path
def get_resource_path(filename):
return Path(__file__).parent / "resources" / filename
def test_json_data():
with open(get_resource_path("test_data.json")) as f:
data = json.load(f)
assert data["message"] == "Hello, World!"
def test_text_file():
text = get_resource_path("sample_text.txt").read_text()
assert "expected content" in text
4. Using a Fixture to Load Resources
Create a fixture that provides easy access to resources:
# tests/conftest.py
import pytest
from pathlib import Path
@pytest.fixture
def resource_dir():
return Path(__file__).parent / "resources"
@pytest.fixture
def load_resource(resource_dir):
def _load(filename):
return (resource_dir / filename).read_text()
return _load
# tests/test_example.py
def test_with_resource(load_resource):
content = load_resource("sample.txt")
assert "expected" in content
5. Using pytest-datadir Plugin
Install the pytest-datadir plugin for more advanced resource handling:
pip install pytest-datadir
Then organize your files:
project/
├── tests/
│ ├── test_example/
│ │ └── sample_data.txt
│ └── test_example.py
# tests/test_example.py
def test_with_datadir(datadir):
content = (datadir / "sample_data.txt").read_text()
assert "expected" in content