pytest
?When you are developing an application in any programming language or framework and you don’t test it, your application could crash unexpectedly. So, it is advisable to perform the testing of your application with different test cases: both positive and negative.
pytest
is a Python testing framework that helps users write the test cases to test their applications. It offers various features, like detailed messages when your test case fails, support for unittest and nose test, etc.
Before moving on, let’s first install the package by running the following command:
pip install pytest
We will be creating a separate test.py
file that will contain the test cases for our Python code.
To run the test file, we need to use the below command in our command prompt:
python -m pytest test.py
We will be creating a simple function, that will return the cube of a number, and then write its test cases. Now, let’s see the code.
import maindef test_case_1():assert 27 == main.cube(3)def test_case_2():assert 64 == main.cube(4)def test_case_3():assert 125 == main.cube(5)
Explanation:
main.py
file:
cube()
function that will accept a number and return the cube.test.py
file:
main.py
file to access the cube()
function.cube()
function.Now, let’s see what type of output you can get when the test cases are not passed.
import maindef test_case_1():assert 27 == main.cube(3)def test_case_2():assert 60 == main.cube(4)def test_case_3():assert 125 == main.cube(5)
Explanation:
So, in this way, you can write your own tests and make sure that your application is well tested before it is deployed in production.