How to execute a selected test from a collection of tests in Pytest?


We can execute a selected test from a collection of tests in Pytest. Pytest is a test framework in python. To install pytest, we need to use the command pip install pytest. After installation, we can verify if python has been installed by the command pytest –version. The version of pytest shall be known.

Pytest can be used for creating and executing test cases. It can be used in a wide range of testing API, UI, database, and so on. The test file of pytest has a naming convention that it starts with test_ or ends with _test keyword and every line of code should be inside a method that should have a name starting with test keyword. Also, each method should have a unique name.

In order to print the console logs, we need to use the command py.test –v –s. Again, if we want to run tests from a specific pytest file, the command is py.test <filename> -v.

Let us consider a pytest file having test methods.

def test_CalculateLoan():
   print("Loan calculation")
def test_CalculateLease():
   print("Lease calculation")

Let us consider another pytest file having test methods.

def test_CalculateRepay():
   print("Loan calculation")
def test_FindLease():
   print("Lease search")

To execute the test methods having a particular string within its name, we need to execute the command, pytest -k <substring> -v. Here -k <substring> is the substring to look for in the test methods and v means verbose.

For our case, the command should be pytest -k Calculate –v. The test methods having Calculate in their names, shall be chosen for execution. In this case, CalculateLoan(), CalculateLease()and CalculateRepay() will be executed.

Updated on: 19-Nov-2021

476 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements