Overview Effective testing separates amateur scripts from professional software. Pytest transforms the grueling chore of verification into a streamlined, automated workflow. By adopting a minimalist approach, you reduce the friction of writing tests, ensuring your codebase remains resilient as it scales. This guide focuses on building a clean, manageable testing environment that mirrors your project structure and utilizes modern tooling. Prerequisites To follow this tutorial, you should have a solid grasp of **Python** fundamentals, specifically modules and functions. Familiarity with the command line and a code editor like VS Code is essential. Knowledge of virtual environments will help you manage dependencies without polluting your system Python installation. Key Libraries & Tools * **Pytest**: The primary framework for writing and running small, readable tests. * **uv**: A high-performance Python package installer and resolver. * **Pytest-mock**: A plugin that simplifies mocking objects and patching imports. * **Poetry**: An alternative dependency management tool for Python projects. Code Walkthrough 1. Installation Isolate your testing tools by installing them as development dependencies. Using the `uv` package manager ensures speed and reliability. ```bash uv add --test dev pytest ``` 2. VS Code Configuration To enable the visual testing interface in VS Code, you must explicitly configure your workspace settings. This allows the editor to discover tests within your designated directory. ```json { "python.testing.pytestEnabled": true, "python.testing.unittestEnabled": false, "python.testing.pytestArgs": [ "test" ] } ``` 3. Writing Unit Tests Test files must follow the `test_*.py` naming convention. Match your `test/` folder structure to your `src/` folder for easy navigation. Below is a test for a duration conversion function. ```python from datetime import timedelta from src.timestamp_utils import to_timestamp def test_negative_duration(): duration = timedelta(seconds=-10) assert to_timestamp(duration) == "0:00:00" def test_specific_time(): duration = timedelta(hours=1, minutes=2, seconds=3) assert to_timestamp(duration) == "1:02:03" ``` Syntax Notes Pytest relies on standard Python `assert` statements rather than the verbose helper methods found in the legacy `unittest` library. Functions must start with the `test_` prefix to be automatically discovered by the runner. For more complex scenarios, **Mocking** replaces real objects with fake ones to isolate the logic under test. Practical Examples Testing is vital for external API integrations, such as OpenAI. Instead of making real network calls during testing, you can **patch** the translator function to return a static string. This keeps your test suite fast and avoids unnecessary costs. Tips & Gotchas * **Filter by Keyword**: Use `pytest -k "keyword"` to run specific subsets of tests. * **Reset State**: Always ensure one test does not depend on the outcome of another; isolation is king. * **Check Performance**: Use the `--durations=10` flag to identify the slowest tests in your suite.
pytest-mock
Products
- Mar 21, 2025