Parallel Test execution in Python Pytest

In the pytest framework, we have executed test cases in sequential order. but in real life, a test suit will have numerous test cases and each file will have a bunch of tests. This will require a large execution time and overcome this problem we can rum over test cases parallelly by using the pytest xdist plugin.

Features of pytest-xdist

Pytest-xdist plugins provide some unique modes of executions such as

      • Multi-process load balancing – Multiple hosts or CPUs can simultaneously run tests. This will speed up the process using special resources of machinery.
      • LooponFail – When every test runs pytest again run all the test cases if some test might get failed it will run the test until and unless all tests would get passed.
      • Multi-platform coverage – Different platforms or Python interpreters can be used and parallel tests can be performed on them.

Prerequisites

  • Install pytest-xdist plugin – pip install pytest-xdist

How to run Parallel Testcases in Python Pytest

Create a test folder name with test_data in that folder create a test file named test_parallel.py. In that file write different test cases as shown in the below code.

import pytest
def test_1():
    return 'hello'
    assert True
    
def test_2():
    return [1,2,3,4]
    assert True
    
def test_3():
    s = 'hey'
    assert 'hey'==s

We can execute the code using the syntax pytest test_parallel.py -n where -n is the number of tests by multiple users. all test cases passed successfully.

Run parallel test case from multiple folders/files in Python Pytest

Now we will be running a test case from multiple test files.

  • Create a folder with multiple test files. your folder should have this file format.

  • Run a parallel test using command pytest test_multiple -n <num-of-cpus>. hence all 6 test cases are passed successfully.

And now we will be testing our test cases from multiple folders. but to test multiple folders in parallel we need to put all folders in a particular folder let’s say the parent folder and the test folder as subfolders.

Create a parent folder and add all test folders in that folder your directory should have this kind of format. here I have included multiple files and their subfolders.

Now for parallel testing of multiple folders, we can use the command pytest -n <num of cpus>. As we have executed the command all the test cases get passed successfully.

By testing test cases in parallel we can reduce the execution time to a great extent and also reduces the time complexity in automation testing. Thus In this tutorial, we have learned how to run the parallel test cases in pytest.