Pytest beginners guide

Julia Suarez
Jun 25, 2019 · 10 min read
Powered by


In this guide, you will learn how to get started with pytest. Before we start you should be already familiar with unitary tests and why they are important. The goal of this article is to show you how to set up pytest and why should you use it.

Now, let’s begin. Unit tests are pieces of code that allows you to test the smallest parts of your application like modules, classes, components, etc.

They must be concise and test one thing at the time, that’s why their name is unit tests. There are several frameworks that will help you write unit tests effortless. For Python, the most popular is pytest according to Slant.

Before getting started

For this tutorial I will assume you know the following, also I’ll be using Python 3.6.5:

  • What is a CLI
  • How to create a virtual environment
  • Python basic syntax (Dictionary, arrays, etc)
  • How to install packages
  • How to create Python modules

If you are okay with that, let’s go before you get bored of me first!

Pytest basics

Here is a summary of what will be cover in this basics guide:

  • Setup instructions
  • Test discovery
  • Configuration files
  • Fixtures
  • Asserts
  • Markers

Setup instructions

  • Create a folder for your project
  • Create a virtual environment with python3
  • Install pytest
  • Create a Python module named example and Python file for your source code (Mine will be

That’s all the setup we will need for now. You should have a directory like this:

Let’s run a hello world test, create a function to check if a number is even:

Now we create our first test with something like:

And we run our test with:

And success! Our output will be something like:

Note: You will see a . (dot) when a test pass, if it fails you will see an F.

But guess what? You didn’t need to specify the file. If you run pytest in your terminal, you will get the same output thanks to pytest test discovery convention.

Test discovery

This is the file naming conventions `pytest` uses to find the tests. Here is an extract from the documentation:

pytest implements the following standard test discovery:

- If no arguments are specified then collection starts from testpaths (if configured) or the current directory. Alternatively, command line arguments can be used in any combination of directories, file names or node ids.

- Recurse into directories, unless they match norecursedirs.

- In those directories, search for test_*.py or * files, imported by their test package name.

- From those files, collect test items:
-test_ prefixed test functions or methods outside of class
-test_ prefixed test functions or methods inside Test prefixed test classes (without an __init__ method)

In summary, it means that by default pytest will find all files which match the regex test_*.py or * Inside those files, it will collect all functions with the prefix test_ and then execute them.

The testpaths option allows you to change the root tests directory.

Configuration files

You can specify the initial configuration for pytest using a pytest.ini file. In it, you can choose the tests directories, name pattern, etc.

There are several files that you can use to setup pytest. This is an extract of the docs:

It establishes which is the precedence of the configuration files. If your project has several of these files when you run pytestit will tell you which file is using.

In this docs you can see all the options you can use on a configuration file.

So far you learned how to create a simple test, how test discovery works and how to customize pytest configuration with a setup file. Now let’s start with the main features of pytest!

Pytest features

In here we will cover enough to get you started writing real-world tests. This is the list of features we will cover:

  • Asserts
  • Fixtures
  • Markers


In pytest the asserts are simple and self-explanatory. You use the assert keyword with some expression that must be valid. Otherwise, the test will fail. Here is how it looks like when a test fails. (This is another extract from pytest docs):

It will tell you exactly what is failing in your expression. For more information about the assert keyword, check the docs here.


We finally got to the main feature of pytest. I had a hard time understanding pytest fixtures at the beginning. I felt like everybody was talking about how great they were and nobody was explaining what the hell they actually are.

Fixtures are an example of dependency injection (you can read it in pytest docs here). Their goal is to inject some calculated values/objects that can be reused on your tests. Here is an extract from pytest docs:

Fixtures: a prime example of dependency injection

Fixtures allow test functions to easily receive and work against specific pre-initialized application objects without having to care about import/setup/cleanup details. It’s a prime example of dependency injection where fixture functions take the role of the injector and test functions are the consumers of fixture objects.

Fixtures are functions decorated with the pytest decorator @pytest.fixture. By convention, all fixtures should be declared on the file on the root directory of every Python module detected by pytest. Remember, pytest only detects modules according to the testpaths defined on your ini file.

Here is a example:

Now we can change our old test with something like:

If you execute it again you will see the test passed. I hope you see the fixtures huge potential. You can create complex objects for particular tests and reuse them.

Pytest workflow looks something like this:

  • Find and read a configuration file
  • Identify all declared fixtures on files and collect them
  • Collect all tests that match the specified directories and pattern on the ini file
  • Before executing each test, pytest will check the test arguments to see if it matches any collected fixture. If it does, it will execute the fixture and use the returned value as the parameter with the fixture name
  • After all pytest executes all the fixtures and replaced their respective value, it will run the test.


By default pytest executes all fixtures once per function. This can be expensive if, for example, you request data from an API. Each test with that fixture name as a parameter will make an API request, slowing down your tests. In summary, be aware of the following:

Every time an argument of any test matches the name of a collected fixture, pytest will execute the fixture and use the returned value as the parameter to the function. EVEN IF THE PARAMETER IS NOT USED.

For these situations, we have the scope parameter. This parameter allows us to reuse a fixture instance between tests. The possible values of the scope parameter are: function, class, module, package or session.

In the pytest docs there is a great example of an smtp connection object:

In this example, we can reuse the smtp connection object between all the tests in the same Python module. Imagine we want to execute some code after the smtp_connection fixture's execution:

Before we move to another pytest feature, I want to clarify that you can have several files. You can have one file per Python module detected by pytest, look at this example:

Notes: Tests defined in the can use the fixtures defined in tests/, but the can use all fixtures from tests/ and tests/api/


Markers are a pytest decorator that allows you to classify your tests or perform some specific action.

To list all the markers you have defined execute:

You will have an output with default markers, here you can see a summary of the most relevant ones:

The description is pretty much self-explanatory but let’s see some examples:

  • @pytest.mark.skip(reason=None): With this marker pytest will skip the test, you can add a reason to explain why.

Also, there is a variation from this marker to skip the test if a condition is True: @pytest.mark.skipif(condition)

  • @pytest.mark.xfail(condition, reason=None, run=True, raises=None, strict=False): With this, you can mark the test as Expected to fail if the condition parameter is True. This is useful if you write a test with a feature that hasn’t been implemented or when the functionality you were testing has changed and you know the test will fail.
  • @pytest.mark.parametrize(argnames, argvalues): This marker will allow you to reuse a test with different parameters so you include more cases or situations as input for your test.

If you execute this, you will see that 4 tests pass because of each input count as an independent test

Here is a summary of the tests with markers and some distinct syntax you can use:

If you run all these tests, the output would be like:


  • All expected to fail tests that actually fail will show a lowercase x. In the other hand, if the test has the xfail marker but it passes, it will count as Unexpected passes. In the result, they will appear with an uppercase X.
  • pytest marks the skipped test with an s.
  • If you use the parametrize marker, pytest will run an independent test for each combination of parameters. You can mark a specific instance as Expected to fail.
  • If you want to see the reason for each marked test, you can add the -r flag, this is the description from the CLI help:
  • For example, you can use this to get the extra summary for all cases:

Some final tips

If you have a lot of tests and need some kind of report, I would recommend you to try the Python package pytest-html. You can use it with the following command:

You will get something like:

It can be useful if you have tons of tests. Also, if you use PyCharm as your code editor, use pytest scripts instead of Python scripts. The whole UI is completely different and you can see the results categorized per module and test.

Be aware of using fixtures which value isn’t actually used. Because they will be dead time, making your tests slower.

If you can, avoid making calls to external API, this is another huge factor that can make your tests REALLY slow. Consider using Mocking. I didn’t cover it on this guide, but it’s a good practice that helps you keep your test concise and small. Remember, is important to test one functionality at the time. Sometimes our units of code have a lot of logic within like a backend endpoint. For those cases try using several unit tests instead of a big one. Or consider using other types of tests like Integration Tests.

For a small introduction to Mocking, check this great article.

I hope this article was useful to you. I tried to include all the small things about pytest that took me a while to understand. Now go and write some awesome unitary tests with pytest!


Stories about development, technology and our experience…