The fixtures are methods which 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 wide range 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 which 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 which are responsible for URL declaration, handling some input data, database connections and so on. So it can be treated as a precondition 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.
Let us consider a pytest file having test methods.
@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 a drawback that its scope is limited to the test file where it is mentioned and not outside of it.
In addition to the questions we have discussed here, go through your previous assignments that you did with the topic. Also, ensure that you are able to speak with conviction in the interview.
If you are applying for a fresher role, the questions are mostly asked on the basic concepts. Keep cool and prepare for the interview. Tutorialspoint wishes you good luck and be positive.