Python Testing with Pytest | Write Your First Unit Test
Do you want to learn writing unit test cases for python testing with pytest?
You are at the right place.
Your code is incomplete without doing unit testing. Being a developer, it’s your job to test your code and all the corner cases before merging your code to the master branch.
If you look at most of today’s job descriptions (8 out of 10 job profiles) ask your experience writing unit test cases.
Learning how to write unit test cases will add value to your candidature when you step out for job opportunities. And in fact, being developer you should hone this skill.
In this tutorial, we will learn how to write the unit test case to test your Python code.
Install and Setup Pytest
I’m assuming, you already have Python installed on your system.
To set up the testing environment, first of all, you need to install
pytest Python module. You can install it using pip command.
Here is the simple command to install.
pip install pytest
It will install the latest version of pytest module from official Python PyPI repository. To execute this command, make sure you are connected to the internet.
That’s all. No further setup is required.
Let’s see how to write code for python testing with pytest.
Writing Your First Testcase using Pytest
Pytest testcase is nothing but the special function inside which you can execute the code required for testing.
Here are some of the mandatory rules you need to follow while writing test-cases.
- Testcase function should start with the keyword
- Python file name should start with
test_or end with
Typically, assert statement are used to verify the testcases.
Example 1: Successful Testcase
def test_func_sample(): a = 2 b = 2 assert a==b
Let’s save this Python program file as
Executing Test Case:
As I said, this is the special Python program file and we can not execute it using typical Python command.
You have to execute it using pytest command.
> pytest test_sample.py ================================================= test session starts ================================================= platform win32 -- Python 3.8.0, pytest-6.0.1, py-1.9.0, pluggy-0.13.1 rootdir: C:\Users\user\Desktop\code\py plugins: mock-3.2.0 collected 1 item test_sample.py . ================================================== 1 passed in 0.50s ==================================================
You can see the output “1 passed”. This means our one test case is passed.
Here value of the ‘a’ and ‘b’ is equal. So, the assert will be True and will not throw any exception.
If you remember a couple of syntax and formatting, its very easy to write test cases in Python. Isn’t it?
Example 2: Failed Testcase
Let’s make the change in the testcase to assert to fail.
No one write a test case to fail. We are doing it intentionally to learn. 😉
def test_func_sample(): a = 1 b = 2 assert a==b
Here the assert statement is false as the value of ‘a’ and ‘b’ are different.
When the assert statement is false, it will through an exception.
Let’s execute the test case again, using
pytest test_sample.py ================================================= test session starts ================================================= platform win32 -- Python 3.8.0, pytest-6.0.1, py-1.9.0, pluggy-0.13.1 rootdir: C:\Users\user\Desktop\code\py plugins: mock-3.2.0 collected 1 item test_sample.py F ====================================================== FAILURES ======================================================= _____________________________________ test_func_sample ______________________________________
assert 1==2E assert 1 == 2 test_sample.py:9: AssertionError =============================================== short test summary info =============================================== FAILED test_sample.py::test_func_sample - assert 1 == 2 ================================================== 1 failed in 0.33s ==================================================
From the output, we can see that the test case has failed with
From these two examples, I hope you learned how test cases execute.
Now, we will learn how to write unit test cases to verify your Python code.
Writing TestCase for Unitesting a Function
To make it simple, your task is to write the function that returns the square of the given number.
Let’s say the function name is
get_square that returns the square of the given number.
def get_square(val): return val*val
Let’s save this code (says as sample.py).
We want to write a test case for the unit-testing of this function.
In writing a test case, there are two steps involved.
- Calling actual function to test
- Matching the desired output with the return value from the actual function
We are calling the get_square method from our test case method. First of all, you need to import this function to our test case file.
The assert statement is to verify the return value from the get_square method. In this case, the get_square method should return 100 for input value 10.
from .sample import get_square def test_get_square(): out = get_square(10) assert out == 100
Let’s save this code as test_sample.py and execute it.
> pytest test_sample.py ================================================= test session starts ================================================= platform win32 -- Python 3.8.0, pytest-6.0.1, py-1.9.0, pluggy-0.13.1 rootdir: C:\Users\user\Desktop\code\py plugins: mock-3.2.0 collected 1 item test_sample.py . [100%] ================================================== 1 passed in 0.21s ==================================================
You can see the test case has passed.
If you unknowingly use the + sign instead of * inside the get_square method, your test case will fail. This way you can catch even the small errors in your code.
We are demonstrating a simple example here. But, not catching the small error in the Project code can lead to a big failure.
You might need to write multiple test cases to verify the behavior and corner cases of the single function.
Here are some of the frequently asked questions and Google searches related to the Pytest.
Some of these questions are also asked in the technical Python interview. Check PyTest interview questions and answers asked in job interviews.
By default, you can not see the print output in the console.
Use -s option while running the pytest command. If you have any print statements in your code, they will get printed on the console.
pytest <testcase_to_execute> -s
This can come handy while debugging.
Here are two basic rules you should remember while writing test cases.
1. Testcase function should start with the keyword
2. Python file name should start with
test_ or end with
The best way is to have a dedicated Python file where you can add multiple test cases to execute.
There are different ways to execute the test cases.
1. Execute all test cases from all the Python files in the given directory.
2. Execute all the test cases from the given Python file name.
3. Execute specific test cases from the given Python file.
This is all about this tutorial on Python testing with pytest. I hope you learn to write the basic test cases to test your Python code.
If you have any specific questions to ask me or if you have any thoughts about this tutorial, let me know by commenting below.
We will learn how to mock unit test cases in the upcoming tutorial. Stay tuned.
Leave a Reply