What are fixtures in Pytest?


The fixtures are methods that shall execute before each test method to which it is associated 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.

The fixtures are associated with test methods that are responsible for URL declaration, handling some input data, database connections, and so on. So it can be treated as a preconditioning method for every test method.

A method that has a fixture should have the syntax − @pytest.fixture. To access the fixture method, the test methods have to specify the name of the fixture as an input parameter.

Also to use fixtures, we have to import pytest to our test file.

Example

Let us consider a pytest file having test methods.

import pytest
@pytest.fixture
def Login():
   print("Login is successful")
def test_CalculateLease(Login):
   print("Lease calculation")
def test_CalculateLoan(Login):
   print("Loan calculation")

In the above example, we have a fixture method Login() which is passed as a parameter to the test methods CalculateLease() and CalculateLoan(). At first, the Login() fixture method shall be executed followed by the other methods.

To execute the above test methods, we need to run the command py.test -k Calculate –v.

A fixture has the drawback in that its scope is limited to the test file where it is mentioned and not outside of it.

Updated on: 19-Nov-2021

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements