Installing pytest
Getting started with pytest is straightforward. You need Python 3.7 or newer installed on your system.
pip install pytest
This installs pytest and all its core dependencies. You can verify the installation by checking the version:
pytest --version
Project Structure
A well-organized pytest project typically follows this structure:
my_project/
โโโ src/
โ โโโ my_package/
โ โโโ __init__.py
โ โโโ calculator.py
โโโ tests/
โ โโโ __init__.py
โ โโโ conftest.py
โ โโโ test_calculator.py
โโโ pytest.ini
โโโ requirements.txt
Keep your source code in src/ and your tests in tests/. This separation makes it clear what is production code and what is test code.
Configuration with pytest.ini
Create a pytest.ini file in your project root to configure pytest behavior:
[pytest]
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
addopts = -v --tb=short
This tells pytest where to find tests and how to format output. The addopts setting applies default command-line options every time you run pytest.
Using a Virtual Environment
Always use a virtual environment to isolate your project dependencies:
# Create virtual environment
python -m venv venv
# Activate it (Windows)
venv\Scripts\activate
# Activate it (macOS/Linux)
source venv/bin/activate
# Install pytest inside the environment
pip install pytest
This prevents version conflicts between projects and keeps your system Python clean.