Python’s Pytest
Pytest is a powerful and feature-rich testing framework for Python, designed to make testing simple and scalable. This guide will walk you through setting up Pytest in an existing Python project to start writing and running tests effortlessly.
Prerequisites
Ensure the following tools are installed in your environment:
-
Python 3.3 or later: Early AI supports Python version 3.3 and above. Install the latest version of Python from python.org.
-
Virtual Environment (Optional): Create a virtual environment to isolate dependencies:
python -m venv venv
source venv/bin/activate # For Linux/MacOS
venv\Scripts\activate # For Windows -
Pytest: Install Pytest in your project using pip:
pip install pytest-mock
-
Pytest-Mock: Install pytest-mock for mocking functionality:
pip install pytest
Configuration Steps
-
Organize Your Project Structure
Pytest automatically discovers tests based on file and folder names. Use the following recommended structure:
project/
│
├── src/
│ └── my_module.py
├── tests/
│ └── test_my_module.py
└── requirements.txt
- src/: Contains your source code.
- tests/: Contains test files named with the test_ prefix or ending with _test.
-
Create a Sample Test
Write a simple test in the tests/ folder. For example, tests/test_my_module.py:
# src/my_module.py
def add(a, b):
return a + b
# tests/test_my_module.py
from src.my_module import add
def test_add():
assert add(1, 2) == 3
-
Run Pytest
Run Pytest to execute your tests:
pytest
You’ll see an output similar to this:
========================== test session starts ==========================
collected 1 item
tests/test_my_module.py . [100%]
=========================== 1 passed in 0.02s ===========================
-
Add Pytest to Your Workflow
Include Pytest in your requirements.txt or pyproject.toml file for dependency management. For example, in requirements.txt:
pytest==<latest-version>
pytest-mock==<latest-version>Install all dependencies with:
pip install -r requirements.txt
That's it. Happy pyTesting!