8 Useful Pytest Plugins To Make Your Python Unit Tests Easier, Faster and Prettier

Testing is a critical component of software development, and Pytest is one of the most popular testing frameworks out there.

It provides a powerful and flexible testing environment, allowing you to write concise, maintainable and easy-to-understand tests.

One of the beautiful things about Pytest is that it can be easily extended using plugins, which provide additional functionality and make it even easier to write and maintain your unit tests.

This is a great way to customize and enchance your testing environment, whether measuring code coverage, running tests in parallel, or mocking external services.

In this article, we’ll explore some of the most popular and useful Pytest plugins, and discuss how they can help streamline your testing workflow and improve code quality.

Whether you’re new to Pytest or a seasoned veteran, you’ll find plugins that can help take your testing workflow to the next level.

  • How Pytest Plugins Can Benefit Your Testing Workflow
    • Improved Functionality
    • Greater Flexibility
    • Reduced Boilerplate Code
    • Easier Collaboration
    • Community Support
    • Documentation And Reporting
  • How To Install Pytest Plugins?
  • 8 Popular Pytest Plugins
    • 1. pytest-cov
    • 2. pytest-mock
    • 3. pytest-xdist
    • 4. pytest-timeout
    • 5. pytest-asyncio
    • 6. pytest-sugar
    • 7. pytest-html
    • 8. pytest-profiling
  • Conclusion

Let’s get started then?

Link To GitHub Repo

How Pytest Plugins Can Benefit Your Testing Workflow

If you’re not convinced already, here are a few Pytest plugins can greatly improve your testing workflow.

Improved Functionality

Plugins can add additional functionality to your test suite, making it easier to write and maintain tests.

They can also help with everything from mocking and patching objects to measuring test coverage and performance.

Greater Flexibility

Pytest plugins allow you to customise your testing environment to your specific needs.

Whether that means running tests in parallel, controlling the order in which tests are run, or integrating with external tools and libraries.

Reduced Boilerplate Code

Pytest plugins can help reduce the amount of boilerplate code needed to write tests, making it faster and easier to create tests that accurately reflect the behavior of your application as you can focus more on testing the functionality.

Easier Collaboration

Pytest plugins can help make it easier to collaborate with other developers on your team, as plugins (just like packages) can provide a consistent testing environment across multiple projects.

Community Support

Pytest has a large and active community of developers who contribute plugins and provide support to other users.

This means that if you have a specific testing need, chances are there is a Pytest plugin that can help you address it.

Documentation And Reporting

Popular Pytest plugins like pytest-coverage help you track the % test coverage of your source code while producing beautiful and shareable reports.

This can be easily logged in your CI pipeline and give your team confidence that the code is well-tested.

How To Install Pytest Plugins?

Installing Pytest plugins is a straightforward process.

To install a Pytest plugin:

1. Check the requirements:

Before installing a plugin, make sure you have the correct version of Pytest installed, and that the plugin is compatible with that version.

2. Install the plugin:

You can install a Pytest plugin using pip, the package installer for Python.

1
pip install <plugin-name>

Where <plugin-name> is the name of the plugin you want to install.

3. Verify the installation:

After installing the plugin, you can verify that it was installed correctly by running Pytest with the -h option.

For example, if you installed the pytest-cov plugin, you can run the following command to verify that it was installed:

1
pytest -h | grep cov

That’s it! Once you have installed a Pytest plugin, you can start using it in your test suite right away.

Just import the plugin and any necessary modules into your test code, and you’re good to go.

Now that you’re convinced of the benefits let’s take a look at some of the popular Pytest plugins and how to use them.

We’ll work with an example repository.

Quick Repo Explanation

Our repo consists of a couple of simple string transformation methods

  1. Count the # of vowels in a string
  2. Remove spaces
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def count_vowels(sentence: str) -> int:
"""
Count the number of vowels in a sentence
:param sentence: The sentence to count the vowels in
:return: The number of vowels in the sentence
"""
vowels = "aeiou"
count = 0
for letter in sentence.lower():
if letter in vowels:
count += 1
return count


def remove_spaces_in_string(sentence: str, delay_length: int) -> str:
"""
Remove spaces in a string
:param delay_length: Duration of the delay
:param sentence: The sentence to remove spaces in
:return: The sentence without spaces
"""
delay(length=delay_length)
return sentence.replace(" ", "")

def delay(length: int) -> None:
time.sleep(length)

As usual the unit tests are located under /tests/unit directory.

1. pytest-cov

pytest-cov is a popular Pytest plugin that provides code coverage reporting for Python projects.

With pytest-cov, you can measure the code coverage of your test suite and generate reports that show which parts of your code have been tested and which have not.

The plugin can be easily integrated into a continuous integration (CI) pipeline.

pytest-cov works by using the coverage.py library to measure code coverage, and can be configured to include or exclude specific files or directories from the coverage report.

We previously covered pytest coverage reports in a standalone article so you can take a look at that too.

To generate a coverage report, run:

1
coverage run -m pytest tests/unit/test_string_transform.py  -v -s

And access the report in the CLI using

1
coverage report -m

pytest-plugins-coverage

2. pytest-mock

pytest-mock is a Pytest plugin that provides simple but powerful mocking functionality.

It allows you to easily replace parts of your code with mock objects, allowing isolation and testing of individual components in a controlled environment.

It provides a range of methods for creating and configuring mock objects, such as mocker.patch and mocker.spy, and supports a variety of assertion helpers to simplify testing.

Additionally, it can be used with other Pytest plugins, such as pytest-cov, to measure the code coverage.

In our example, we mock the delay function and as you can see below the test passed in 0.01 sec (in spite of the 3-second delay).

This is very useful when mocking external objects, functions, classes, API calls or cloud resources.

1
2
3
4
5
def test_remove_spaces_in_string_mock_delay(mocker):
mocker.patch("string_transformations.core.delay", return_value=None)
assert (
remove_spaces_in_string("This is a random string", 3) == "Thisisarandomstring"
)

pytest-plugins-mock

3. pytest-xdist

pytest-xdist is a Pytest plugin that enables parallel testing for Python projects.

With pytest-xdist, you can run your test suite on multiple CPUs or even on multiple machines, greatly reducing the time required to run large test suites.

The plugin allows you to split your test suite into multiple independent parts, and run each part in a separate process, either on the same machine or on multiple machines.

pytest-xdist also supports various scheduling algorithms to ensure efficient use of resources.

We covered an article on speeding up your test suite using pytest-xdist which can you can take a look through here.

To enable execution of your tests in parallel, include the -n auto flag to your pytest run command.

1
pytest tests/unit/test_string_transform.py -v -s -n auto

pytest-plugins-xdist

4. pytest-timeout

pytest-timeout is a Pytest plugin that provides a simple way to set timeouts for your test functions.

You can specify a maximum time limit for each test, after which the test will be terminated and marked as a failure.

This helps to prevent long-running tests from causing delays or blocking other tests from running, and can also help to identify tests that are taking too long to execute.

You can configure timeouts for each test or for all tests.

pytest-timeout helps to limit test execution time and prevent slow tests from affecting your overall test suite performance.

Here’s an example of an delay applied to our tests, resulting in timeout.

pytest-plugins-timeout1

pytest-plugins-timeout2

Note: You can override the overall Pytest CLI timeout command by adding the @pytest.mark.timeout(x) to each test.

5. pytest-asyncio

pytest-asyncio allows you to test async code with ease.

It includes an event loop fixture that allows you to run asyncio tasks and coroutines in your tests.

It also provides several useful plugins that make testing with asyncio even easier.

For example, the pytest-asyncio-timeout plugin adds support for timeouts in asyncio tests, allowing you to specify a maximum time limit for each test.

The pytest-asyncio-threads plugin allows you to test asyncio code that uses threads, by providing a fixture that creates a new thread for each test and waits for the thread to complete before moving on to the next test.

We covered the pytest-asyncio plugin in great detail with examples in our article on testing asynchronous functions in Python.

6. pytest-sugar

pytest-sugar is a Pytest plugin that enhances the output of Pytest’s test execution progress by providing a more detailed and visually appealing representation of test results.

The plugin replaces Pytest’s default output format with a colourful and informative output format, with features such as progress bars, verbose error messages, and a summary of test results at the end of the test run.

It also supports a number of customization options, such as the ability to change the colour scheme or modify the output format.

Here’s an example.

Pytest Default Output

pytest-plugins-coverage

With pytest-sugar

pytest-plugins-sugar

7. pytest-html

pytest-html is a Pytest plugin that generates HTML reports for your test results, providing a more detailed and user-friendly output than the standard text-based reports.

With pytest-html, you can easily visualize your test results in a web browser, making it easier to understand the overall state of your test suite and identify any issues or failures.

The plugin provides a range of customizable options, such as the ability to include screenshots or other files with your report, and supports a variety of templates for formatting and styling your report.

Additionally, pytest-html can be integrated with continuous integration (CI) tools such as GitHub Actions, Jenkins or Travis CI to automatically generate and publish reports.

To generate a pytest html report, run

1
pytest tests/unit/test_string_transform.py -v -s --html=report.html --self-contained-html

pytest-plugins-html

You can see a sample HTML report like this

pytest-html-report

8. pytest-profiling

pytest-profiling is a Pytest plugin that provides easy profiling of your code during test execution.

It collects profiling data as your tests run and generates a report showing which functions or lines of code are taking the most time to execute.

This helps identify performance bottlenecks and can guide optimization efforts.

<INSERT IMAGE FROM https://pypi.org/project/pytest-profiling/ >

You can generate the profile image using the --profile command which will generate a profile table.

We can also generate an SVG file using the --profile-svg flag.

--profile and profile-svg flags can be used together.

1
pytest tests/unit/test_string_transform.py -v -s --profile-svg --profile

pytest-plugins-profiling

pytest-profiling-output

Profiling Example from our string transformation

pytest-profiling-web-example

Profiling Web Example

Conclusion

So here’s our list of 8 useful pytest-plugins to help you write more extensive, readable, faster and maintainable unit tests.

Pytest plugins offer a great way to enhance the functionality and extend the capabilities of Pytest, making it an even more powerful and flexible testing tool.

From test coverage analysis to profiling and visualization of test results, there are many popular Pytest plugins that help make testing faster, more efficient, and more enjoyable.

You can choose the plugins that best suit your needs and streamline your overall testing process.

I’ll be adding coverage for additional plugins over time so if you think we should cover any specific and important ones, please send me a message via Twitter, GitHub or Email.

Till the next time… Cheers!