Comprehensive Guide to Pytest: Installation, Execution, Fixtures, Marks, and Parameterization
This article provides a detailed tutorial on Python's Pytest framework, covering installation, test discovery rules, execution methods, setup/teardown, fixture usage, assertions, skip mechanisms, custom marks, and parameterization with extensive code examples for practical automation testing.
1. Pytest Overview and Installation Pytest is a Python unit‑testing framework similar to unittest but more concise and feature‑rich. Install it via pip install -U pytest and verify the version with pip show pytest ; it requires Python 3.8+.
2. Running Tests Test files must follow the test_*.py or *_test.py naming pattern, and test functions must start with test_ . Tests can be run by invoking pytest -s test_file.py , using pytest.main() in code, or by matching all tests in a directory.
3. Setup and Teardown Pytest provides ten built‑in hooks such as setup_module , teardown_module , setup_function , teardown_function , setup_class , teardown_class , and their equivalents, allowing actions before and after modules, functions, or classes.
4. Fixtures Fixtures replace traditional setup/teardown by defining reusable preconditions. They can be scoped, autouse, and parameterized. Example: @pytest.fixture def case(): print("login functionality") and used in tests as def test_one(case): ... .
5. Assertions Use the built‑in assert statement for checks. Pytest enhances assertion introspection, making failures easier to diagnose.
6. Skipping Tests Tests can be skipped with pytest.skip() (runtime) or @pytest.mark.skip / @pytest.mark.skipif (declaration). Example shows skipping after five loop iterations.
7. Marks Custom marks categorize tests, e.g., @pytest.mark.login . Run specific marks with pytest -m login , combine with logical operators, or exclude with not .
8. Parameterization Use @pytest.mark.parametrize to run a test with multiple input sets. Example evaluates arithmetic expressions: @pytest.mark.parametrize("num, result", [("10 + 10", 20), ("30 - 10", 20), ("4 * 5", 20), ("40 / 2", 20)]) def test_case(num, result): assert eval(num) == result
9. Additional Features Mentioned plugins include pytest‑rerunfailures , pytest‑HTML , pytest‑repeat , pytest‑xdist , and allure‑pytest for extended reporting, parallel execution, and retry capabilities.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.