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
Alternatively, if you're not using src/
layout:
π§ͺ 2. Writing Tests
Test files: name them as
test_*.py
or*_test.py
Test functions: start names with
test_
Example:
π¦ 3. Making Your Package Importable
From the root directory, run:
This allows test files to import your package using absolute imports like:
π¨οΈ 4. Seeing print()
Output
print()
OutputBy default, pytest
captures stdout, so you wonβt see print()
unless:
The test fails, or
You run
pytest
with:
β οΈ 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
ConfigurationThis simplifies your test command to just:
Would you like a GitHub template or cookiecutter starter with this structure?
Last updated