close

How to keep Unit tests and Integrations tests separate in pytest

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to keep Unit tests and Integrations tests separate in pytest in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to keep Unit tests and Integrations tests separate in pytest?

  1. How to keep Unit tests and Integrations tests separate in pytest?

    Now, from the command line, you can run pytest -m "not integtest" for only the unit tests, pytest -m integtest for only the integration test and plain pytest for all.

  2. keep Unit tests and Integrations tests separate in pytest

    Now, from the command line, you can run pytest -m "not integtest" for only the unit tests, pytest -m integtest for only the integration test and plain pytest for all.

Method 1

Yes, you can mark tests with the pytest.mark decorator.

Example:

def unit_test_1():
    # assert here

def unit_test_2():
    # assert here

@pytest.mark.integtest
def integration_test():
    # assert here

Now, from the command line, you can run pytest -m "not integtest" for only the unit tests, pytest -m integtest for only the integration test and plain pytest for all.

(You can also decorate your unit tests with pytest.mark.unit if you want, but I find that slightly tedious/verbose)

See the documentation for more information.

Method 2

You can also structurally separate unit and integration tests into specific directories. Here is a sample file structure from A. Shaw’s article Getting Started With Testing in Python:

enter image description here

With a structural approach, you:

  1. do not need to manually mark various tests with attributes or @pytest.mark.
  2. are not limited to a specific test runner. See examples below.

Examples

Here we run various test runners on integration tests alone. See the sample project/ directory in the figure above.

With unittest from the standard library:

λ python -m unittest discover -s tests/integration

With nose:

λ nose tests/integration

With pytest:

λ pytest tests/integration

Many test runners have an auto test-discovery mechanism that can find tests in sub-directories. This offers the choice to run all tests with ease, e.g.

λ cd <root_dir>
λ pytest project/

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read