Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

10 Awesome Features of Pytest

DZone 's Guide to

10 Awesome Features of Pytest

Pytest for the win!

· Web Dev Zone ·
Free Resource

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.
You may also like: Improve Your Selenium WebDriver Tests With Pytest

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

Topics:
pytest ,python ,open source ,test automation ,devops ,extensibility ,plugins

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}