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
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Why Your Test Automation Is Always Behind the Code And the Architecture That Fixes It
  • Good Data, Bad Metric: A Mutation Testing Pattern for Analytics Engineering
  • Agentic Testing: Moving Quality From Checkpoint to Control Layer
  • Why Your QA Engineer Should Be the Most Stubborn Person on the Team

Trending

  • Bringing Intelligence Closer to the Source: Why Real-Time Processing is the Heart of Edge AI
  • How to Set Up and Run PostgreSQL Change Data Capture
  • Integrating AI-Driven Decision-Making in Agile Frameworks: A Deep Dive into Real-World Applications and Challenges
  • Optimizing Databricks Spark Pipelines Using Declarative Patterns
  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
·
Oct. 10, 19 · Presentation
Likes (10)
Comment
Save
Tweet
Share
48.5K 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

  • Why Your Test Automation Is Always Behind the Code And the Architecture That Fixes It
  • Good Data, Bad Metric: A Mutation Testing Pattern for Analytics Engineering
  • Agentic Testing: Moving Quality From Checkpoint to Control Layer
  • Why Your QA Engineer Should Be the Most Stubborn Person on the Team

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook