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 main def 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)
cube()function that will accept a number and return the cube.
main.pyfile to access the
Now, let’s see what type of output you can get when the test cases are not passed.
import main def 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)
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.
View all Courses