Pytest
Pytest is a powerful and widely-used testing framework in the Python ecosystem. It is designed to simplify the process of writing and running tests, supporting both simple and complex projects. Pytest is known for its simplicity, flexibility, and Pythonic nature, making it a popular choice among developers for ensuring code quality and reliability.
Overview
Pytest offers a unique assertion syntax and a plugin-based architecture for extensibility. It uses raw assert statements for assertions, which are more intuitive and provide more readable output compared to traditional testing frameworks like unittest. Pytest supports automatic discovery of test cases, meaning you don't have to manually specify which tests to run. This feature, combined with its ability to scale from simple to complex projects, makes pytest a versatile tool for developers.
For more details, refer to the Publishing Python Packages and Practices of the Python Pro.
Installation and Setup
To use pytest, it must be installed in the same virtual environment as your package and its dependencies. This ensures that unit tests can execute your actual code, which must be importable. Installing pytest globally can lead to issues where pytest cannot locate your project's dependencies. To install pytest in your project's virtual environment, use the following command:
$ py -m pip install pytest
Once installed, you can run pytest with:
$ py -m pytest
This command prompts pytest to discover and execute any tests it finds. If no tests are present, the output will indicate that no tests were run.
Writing Tests with Pytest
When writing tests in pytest, you can organize them into classes, although it is not strictly necessary. Test classes should be named starting with 'Test', and there is no need to inherit from any base class. Here is an example of a test case written in pytest:
class TestProduct:
def test_transform_name_for_sku(self):
small_black_shoes = Product('shoes', 'S', 'black')
assert small_black_shoes.transform_name_for_sku() == 'SHOES'
def test_transform_color_for_sku(self):
small_black_shoes = Product('shoes', 'S', 'black')
assert small_black_shoes.transform_color_for_sku() == 'BLACK'
def test_generate_sku(self):
small_black_shoes = Product('shoes', 'S', 'black')
assert small_black_shoes.generate_sku() == 'SHOES-S-BLACK'
In this example, the test methods use raw assert statements to verify the expected outcomes, providing a more concise approach compared to unittest.
Test Discovery
Pytest is capable of discovering unit tests in a project using recursive pattern matching. It searches for functions or methods named test_* within the project's directories. By default, pytest will look for tests throughout the entire project, including the root directory and the src/ directory. It is recommended to place your tests in a dedicated test/ directory to keep them organized and separate from the source code.
Figure 5.1 pytest discovers the unit tests in a project using recursive pattern matching.
Running Tests
Running tests with pytest is straightforward. Simply navigate to the directory containing your test files and execute the following command:
pytest
This command will automatically discover and run all test cases in the directory and its subdirectories. Pytest's output includes the names of the test classes and methods, which helps in identifying where the tests are located and what they are testing.
For more information, see Tiny Python Projects.
Understanding Pytest Output
When you run pytest, you will see output similar to the following:
$ pytest -xv test.py
============================= test session starts ==============================
...
collected 6 items
test.py::test_exists FAILED [ 16%]
In this example, pytest has collected six test items from the test.py file. The line test.py::test_exists FAILED indicates that the test_exists test has failed. The [ 16%] shows the progress of the test execution.
Conclusion
Pytest is a comprehensive testing framework that simplifies the process of writing and running tests. Its use of raw assert statements, automatic test discovery, and lack of requirement for base class inheritance make it an attractive choice for Python developers. Whether you are writing new tests or converting existing ones from unittest, pytest offers a more streamlined and Pythonic approach to testing.
| Book Title | Usage of pytest | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|-----------------|-----------------|-------------------------------|---------------|-----------------------|
| [Publishing Python Packages: Test, share, and automate your projects](https://www.manning.com/books/publishing-python-packages) | Discusses pytest as a versatile tool for both simple and complex testing scenarios, emphasizing its plugin-based architecture and utilities like test fixtures and parameterized tests. [more](https://livebook.manning.com/book/publishing-python-packages/chapter-5/16) | Provides detailed instructions on installation and setup, including the importance of installing pytest in the same virtual environment as the package. [more](https://livebook.manning.com/book/publishing-python-packages/chapter-5/16) | Highlights the importance of organizing tests in a dedicated directory to avoid including them in packaged code. [more](https://livebook.manning.com/book/publishing-python-packages/chapter-5/43) | Includes examples of test discovery using recursive pattern matching. [more](https://livebook.manning.com/book/publishing-python-packages/chapter-5/43) | Emphasizes pytest's ability to scale with project complexity, making it a valuable tool for ensuring code quality. [more](https://livebook.manning.com/book/publishing-python-packages/chapter-5/16) |
| [Practices of the Python Pro](https://www.manning.com/books/practices-of-the-python-pro) | Highlights pytest's simplicity and flexibility, contrasting it with the `unittest` framework. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-5/173) | Explains the use of raw `assert` statements and automatic test discovery, enhancing readability and maintainability. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-5/179) | Discusses converting tests from `unittest` to pytest, showing how pytest aligns with Python's design philosophy. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-5/186) | Provides a detailed example of a test case using pytest, demonstrating the use of raw `assert` statements. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-5/179) | Focuses on the streamlined and Pythonic approach to testing, making pytest an attractive choice for developers. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-5/173) |
| [Tiny Python Projects: Learn coding and testing with puzzles and games](https://www.manning.com/books/tiny-python-projects) | Uses pytest to automate testing for exercises, ensuring code behaves as expected. [more](https://livebook.manning.com/book/tiny-python-projects/chapter-1/177) | Describes running tests with pytest using specific command-line options for detailed output. [more](https://livebook.manning.com/book/tiny-python-projects/chapter-1/177) | Focuses on interpreting pytest output to diagnose issues, emphasizing the importance of understanding test results. [more](https://livebook.manning.com/book/tiny-python-projects/chapter-1/177) | Provides examples of test execution and output interpretation, highlighting the use of color-coded and formatted output. [more](https://livebook.manning.com/book/tiny-python-projects/chapter-1/177) | Aims to teach debugging and code verification skills through practical exercises and puzzles. [more](https://livebook.manning.com/book/tiny-python-projects/chapter-1/177) |
FAQ (Frequently asked questions)
What is pytest?
What features does pytest provide?
How does pytest discover unit tests in a project?
Can pytest run unittest-based test suites?
What is the architecture of pytest?
What syntax does pytest provide for assertions?
What program is used to run test.py programs in Tiny Python Projects?
How can you execute tests using pytest in Tiny Python Projects?
Why is pytest considered more Pythonic than unittest?
How do you write a test case in pytest?
What is the benefit of using raw assert statements in pytest?
What makes pytest Pythonic?
How does pytest handle test discovery?
Do test classes in pytest need to inherit from a base class?