Pytest is a Python testing tool. It is an open source testing tool used for testing all types of software’s. Internet is shifted from unittest or nose to pytest because it provides powerful features.
"pytest is a framework that makes building simple and scalable tests easy" - Pytest
For using pytest we need to install pytest library using pip. Latest versions of Python already comes with pip module in the standard library. Go to command prompt and using pip, install pytest by typing
"pip install -U pytest" and press enter.
Let us look into a very basic pytest example :-
return ["dog", "cat"]
assert get_string() == "Selenium"
assert "elephant" in get_list()
Pytest expects our tests to be located in files whose names begin with test_ or end with _test.py.
Let's create a file called firstExample.py, and write 'test_string_equal()' function which asserts Selenium text and 'test_in_list()' function checks if the value is present in the list returned by get_list().
We will write tests and prefix function names with test_, since pytest expects our test functions to be named.
How to run tests using pytest ?
If the file is named as test_firstExample.py, we can run as
Once you have multiple tests, you can group them into a class. pytest makes it easy to create a class containing more than one test like above example.
pytest will pick and run all files of the form test_*.py or *_test.py in the current directory and its subdirectories. We can also simply run any module by passing its filename as above.
In the above example, we have used asserts in two functions
assert get_string() == "Selenium" which checks if the strings are equal and
assert "elephant" in get_list() which asserts for value in the list.
pytest allows us to use the standard python asserts for verifying expectations and values in Python tests and these assertions are very important when testing. Assertions help us to identify if test was successful/failed.
Below is the output :-
The first test passed and the second failed. You can clearly see the values in the assertion to help you understand the reason for the failure.
We will discuss more about pytest features in coming tutorials.