0417-pytest
Certainly! Here's a general, best-practice guide to using pytestโincluding directory structure, naming conventions, output control, and common pitfalls. This is suitable for teaching others or serving as a quick reference.
โ
General Guide for Using pytest Effectively
pytest Effectively๐ 1. Recommended Project Structure
your_project/
โโโ src/ # Optional, for better namespace control
โ โโโ your_package/
โ โโโ __init__.py
โ โโโ module1.py
โ โโโ module2.py
โ
โโโ tests/ # All test files go here
โ โโโ __init__.py # Optional
โ โโโ test_module1.py
โ โโโ test_module2.py
โ
โโโ pyproject.toml # Recommended modern config
โโโ requirements.txt
โโโ README.mdAlternatively, if you're not using src/ layout:
your_project/
โโโ your_package/
โ โโโ __init__.py
โ โโโ module1.py
โ โโโ ...
โโโ tests/
โ โโโ test_module1.py
โโโ ...๐งช 2. Writing Tests
Test files: name them as
test_*.pyor*_test.pyTest functions: start names with
test_Example:
# tests/test_module1.py
from your_package import module1
def test_add():
assert module1.add(1, 2) == 3๐ฆ 3. Making Your Package Importable
From the root directory, run:
pip install -e .This allows test files to import your package using absolute imports like:
from your_package import module1๐จ๏ธ 4. Seeing print() Output
print() OutputBy default, pytest captures stdout, so you wonโt see print() unless:
The test fails, or
You run
pytestwith:
pytest -s # disables output capturing
pytest --capture=no # same effectโ ๏ธ 5. Common Pitfalls to Avoid
Placing test files in the same folder as code
Can cause import conflicts
Using relative imports in test files
Not robust; breaks easily
Naming a test file the same as a module
Import shadowing (test.py, math.py, etc.)
Forgetting to install in editable mode (-e .)
Causes ModuleNotFoundError in tests
Relying on print() without -s
Output wonโt appear unless test fails
โ๏ธ 6. Optional pyproject.toml Configuration
pyproject.toml Configuration[tool.pytest.ini_options]
addopts = "-ra -q -s"
testpaths = ["tests"]
python_files = ["test_*.py"]This simplifies your test command to just:
pytestWould you like a GitHub template or cookiecutter starter with this structure?
Last updated