DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Solid Testing Strategies for Salesforce Releases
  • Why We Still Struggle With Manual Test Execution in 2025
  • Why Testing is a Long-Term Investment for Software Engineers

Trending

  • Subtitles: The Good, the Bad, and the Resource-Heavy
  • Scaling InfluxDB for High-Volume Reporting With Continuous Queries (CQs)
  • Streamlining Event Data in Event-Driven Ansible
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. 10 Awesome Features of Pytest

10 Awesome Features of Pytest

Pytest for the win!

By 
Madhu Suresh Nandyala user avatar
Madhu Suresh Nandyala
DZone Core CORE ·
Oct. 10, 19 · Presentation
Likes (10)
Comment
Save
Tweet
Share
47.6K Views

Join the DZone community and get the full member experience.

Join For Free

girl-taking-test-on-desk.


Pytest is a test automation framework that lets you write simple to complex functional tests. This tutorial will walk you through the great features of Pytest, including: 

  • Easy to start with and simple syntax.
  • Open Source.
  • Build-in support for test discovery.
  • Command-line support.
  • Extensibility: Plug-ins, hooks.
  • Fixtures.
  • Works with built-in unit tests.
  • Large community support.

To install Pytest, run the following command: 

pip install pytest


1. Auto-Discovery of Tests

Pytest's default finds tests with the file name with the preface, "test," or the suffix "_test.py." However, we can configure Pytest to discover custom names by changing the Pytest configuration file “pytest.ini.” By adding the following extension, Pytest automatically discovers tests with the filename “check.” However, in this tutorial, we stick to the default extension "test."

[pytest]  
python_files = check_*.py 
python_classes = Check 
python_functions = *_check 


2. Creating Tests

It’s very easy to get started creating tests. Create a file, test_demo.py, and write the following code — this will create our first test.

import pytest 

def test_addition(): 
   assert 2+5 ==7 


 Output
: 'pytest -v' runs test

Pytest output Addition

Creating a test

3. Command Line Execution

Pytest provides several options to run tests from the command line.

pytest -v -s #verbosity and execution time of test
 e.g:pytest –v –s  

pytest <file_name>   #run tests in module/file  
 e.g:pytest test_demo.py 

pytest <path>       #run all tests below path 
 e.g:pytest c:/dev/pytestdemo 

pytest –k <name>  #run all the test with matching name 
 e.g:pytest –k add #runs all the test with add  

pytest filename::testName #runs only one test 
 e.g:pytest test_demo::test_addition 


4. Parameterization

Pytest supports parametrization. To enable parameterization, we need to import mark and annotate tests with a parameter marker. Parameterization tests look cleaner with large sets of data.

import pytest 
from pytest import mark 


@mark.parametrize("num1, num2 ,expected", 
                  [(2, 5, 7), 
                   (3, 7, 10)])  
def test_addition(num1, num2, expected): 
    assert num1 + num2 == expected 


 Output
:

Image title

Parameterization in Pytest

5. Fixtures

Fixtures are functions that run before each test function. Generally, fixtures are great to use to set up data to run tests. Common usages are to set up a database connection, URLs, and input data. Instead of running the same code, we can attach fixtures.

The following code uses input value 15 and verifies both test cases, division by 3 and division by 5.

import pytest 


@pytest.fixture 
def input_value(): 
    input = 15 
    return input 


def test_div_3(input_value): 
    input_value % 3 == 0 


def test_div_5(input_value): 
    input_value % 5 == 0 


6. Hooks

While we are running tests, it's quite common to run a test setup, tear down, and log events of test. Pytest allows users to customize these events using hooks.

Here are sample hooks defined on conftest.py.

import pytest 


def pytest_runtest_setup(item): 
    print("pytest_runtest_setup") 

def pytest_runtest_logreport(report): 
    print(f'Log Report:{report}') 

def pytest_sessionstart(session): 
    print("pytest_session start") 

def pytest_sessionfinish(session): 
    print("pytest_session finish") 

def pytest_collection_modifyitems(session, config, items): 
    for item in items: 
        print(f"pytest_collection_modify items{item}", item) 

def pytest_collection_finish(session): 
    print('pytest_collection_finish') 


Output:

Image title

Using hooks in Pytest

7. Markers: Grouping Tests

Markers are a great way to add meta-information to our tests. For example, there is an instance to run all P0 test cases, slow test, flaky test, or skipping a test

Example of marking regression test:

@mark.parametrize("num1, num2 ,expected", 
                  [(2, 5, 7), 
                   (3, 7, 10)]) 

@pytest.mark.regression 
def test_addition(num1, num2, expected): 
    assert num1 + num2 == expected


Skip a test:

@pytest.mark.skip 
def test_skip(): 
    pass


Output:

Image title

Skipping a test in Pytest

8. Plug-ins

The Pytest community has a rich test of plug-ins to extend the module's functionality.

8.1 Xdist

Xdist is a popular plug-in enables Pytest to tests in parallel

#installs plug-in  

pip install pytest-xdist   

#runs tests in parallel 

pytest –n <numberof CPU cycles> 


Output:

Image title

Example output

9. Reporting

Pytest supports generating reports in JUnit format. By creating the XML file CI/CD systems like Jenkins can read the log files.

pytest --junitxml=path 


Output:

Image title

Generating reports with Pytest

10. Unittest Compatibility

Pytest supporting running unittest based test out of the box. To run the existing unittest style test suite using Pytest.

pytest tests  


Pytest is very popular in the Python community, and it's growing year over year. Now, you should be able to take advantage of these features while creating tests. There is plug-in pytest-Django supports Django web applications.

List of third party plug-ins: https://pytest.readthedocs.io/en/2.7.3/plugins_index/index.html.

The following examples explain the above tutorial are shared on GitHub: https://github.com/gmadhusureshn/pytestdemo.


Further Reading

  • Dynamically Generating Python Test Cases.
Testing Awesome (window manager)

Opinions expressed by DZone contributors are their own.

Related

  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Solid Testing Strategies for Salesforce Releases
  • Why We Still Struggle With Manual Test Execution in 2025
  • Why Testing is a Long-Term Investment for Software Engineers

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!