Fundamentals 5 min read

Introduction to pytest: Installation, Usage, and Advanced Features

This article provides a comprehensive guide to pytest, covering its advantages over unittest, installation steps, basic and class‑based test writing, execution commands, assertion handling, custom markers, fixture scopes, and useful plugins for enhancing Python testing workflows.

360 Quality & Efficiency
360 Quality & Efficiency
360 Quality & Efficiency
Introduction to pytest: Installation, Usage, and Advanced Features

pytest is a Python unit‑testing framework that offers a simpler, more efficient alternative to the built‑in unittest module, featuring easy onboarding, rich documentation, parameterization, selective test skipping, repeat‑run of failures, compatibility with nose/unittest tests, and extensive third‑party plugins.

Installation : run pip install -U pytest to upgrade to the latest version, then verify with pytest --version .

Basic usage : create a source file (e.g., caculate.py ) with functions, then write test cases in test_demo01.py . Execute with pytest -v test_demo01.py to see detailed results.

Class‑based tests : define a class in test_demo02.py and place test methods inside; pytest will run all methods automatically.

Execution options and discovery rules : use pytest -v for verbose output, pytest -s to show prints, pytest -q for quiet mode; pytest discovers files matching test_*.py or *_test.py and classes prefixed with Test and methods prefixed with test_ .

Assertions and markers : pytest relies on Python's assert statement for checks; you can skip tests with @pytest.mark.skip , mark expected failures with @pytest.mark.xfail , and select subsets using custom markers (e.g., pytest -m android ).

Fixtures : define reusable setup/teardown logic in functions decorated with @pytest.fixture . Control their scope (function, class, module, session) to manage when they run; place common fixtures in conftest.py for global availability.

Plugins : enhance pytest with plugins such as pytest‑sugar (colorful output), pytest‑xdist (parallel execution), pytest‑ordering (control order), and pytest‑assume (continue after multiple assertion failures). Install plugins via pip install plugin-name .

unit testingpluginspytestpython testingfixturesMarkers
360 Quality & Efficiency
Written by

360 Quality & Efficiency

360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.