Now, we will start with our first pytest program. We will first create a directory and thereby, create our test files in the directory.
Let us follow the steps shown below −
Create a new directory named automation and navigate into the directory in your command line.
Create a file named test_square.py and add the below code to that file.
import math def test_sqrt(): num = 25 assert math.sqrt(num) == 5 def testsquare(): num = 7 assert 7*7 == 40 def tesequality(): assert 10 == 11
Run the test using the following command −
The above command will generate the following output −
test_square.py .F ============================================== FAILURES ============================================== ______________________________________________ testsquare _____________________________________________ def testsquare(): num=7 > assert 7*7 == 40 E assert (7 * 7) == 40 test_square.py:9: AssertionError ================================= 1 failed, 1 passed in 0.06 seconds =================================
See the first line of the result. It displays the file name and the results. F represents a test failure and dot(.) represents a test success.
Below that, we can see the details of the failed tests. It will show at which statement the test has failed. In our example, 7*7 is compared for equality against 40, which is wrong. In the end, we can see test execution summary, 1 failed and 1 passed.
The function tesequality is not executed because pytest will not consider it as a test since its name is not of the format test*.
Now, execute the below command and see the result again −
-v increases the verbosity.
test_square.py::test_sqrt PASSED test_square.py::testsquare FAILED ============================================== FAILURES ============================================== _____________________________________________ testsquare _____________________________________________ def testsquare(): num = 7 > assert 7*7 == 40 E assert (7 * 7) == 40 test_square.py:9: AssertionError ================================= 1 failed, 1 passed in 0.04 seconds =================================
Now the result is more explanatory about the test that failed and the test that passed.
Note − pytest command will execute all the files of format test_* or *_test in the current directory and subdirectories.