Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Code
2.1.
Case 1
2.2.
Case 2
2.3.
Unit test testing
2.3.1.
Output
3.
How to use
3.1.
Installation
3.2.
Bringing Coverage in operation 
3.2.1.
Pytest
3.2.2.
Unittest
4.
Frequently Asked Questions
4.1.
Why is coverage used?
4.2.
How does coverage.py work?
4.3.
What is unittest?
4.4.
What is Pytest?
4.5.
What is Anaconda Distribution?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Coverage

Author Ankit Kumar
1 upvote

Introduction

When code runs perfectly, it's all rainbow and unicorn for programmers. But what if there is an issue in the code. Or maybe some part of it is correct. Or even code is compiling and running, but it fails a particular test case. Now that is a serious issue, so what is the solution?

Well, testing is done. It is like checking code line by line so that you aren’t surprised by your code in the runtime. The tool coverage.py is there to bail you out. Basically, Coverage assessment is commonly used to assess the efficiency of tests. It can reveal which sections of your code are being tested and which are not. 

 A sample coverage report

Source: https://dzone.com/articles/an-intro-to-coveragepy

 

Coverage monitors our program, recording which sections of the code have been run, and then analyses the source code to find code that should have been executed but wasn't. 

Now moving to the next section, first, we'll see our testing code.

Also See, Intersection in Python,Swapcase in Python

Also Read, Divmod in Python

Code

We have some simple Python code, such as a function that, when given a name, would print out a hello statement with the name, and if no input is provided, it will print out a hello statement with ‘stranger’ rather than the name. We also have some code that prompts the user for input before passing it to the function that prints out the greeting statement.

# tutorial.py
def say_hello(name=None):
   if name != "":
       print("Hello", name)
   else:
       print("Hello Stranger")
if __name__ == "__main__":
   say_hello(input("What is your name? "))
You can also try this code with Online Python Compiler
Run Code

Case 1

Case 2

Unit test testing

With the help of unittest, there will be one more file, test_tut.py, whose work is to test the function say_hello by passing in "test" and checking the output is "Hello test".

#test_tut.py
from tutorial import say_hello
from unittest import TestCase
from io import StringIO
from unittest.mock import patch

class PrintingTest(TestCase):
    def test_say_hello(self):
        name = 'test'
        expected_output = 'Hello {}\n'.format(name)
        with patch('sys.stdout', new=StringIO()) as fake_out:
            say_hello(name)
            self.assertEqual(fake_out.getvalue(), expected_output)
            
    def test_say_hello_noname(self):
        name = ''
        expected_output = 'Hello Stranger\n'
        with patch('sys.stdout', new=StringIO()) as fake_out:
            say_hello(name)
            self.assertEqual(fake_out.getvalue(), expected_output)
You can also try this code with Online Python Compiler
Run Code

 

Output

In the upcoming section, we will get to know how coverage is to be used.

You can practice by yourself with the help of online python compiler.

How to use

Installation

Step 1: Firstly, install coverage.py

pip install coverage

 

If working on Anaconda Distribution

conda install coverage

 

Verification of coverage can be done by

coverage -version

Bringing Coverage in operation 

Well, the coverage is to be used along with the test runner. Coverage will operate through the command line and it is really simple. Firstly we’ll see the command which will put coverage in action with pytest and then we’ll see how coverage works with unittest. 

So with this move and see the pytest part.

Pytest

As we know pytest is a testing framework based on python. It is mainly used to write API test cases.

If you're using pytest, you may prefix the command with coverage -m.

pytest arg1 arg2 arg3

 

It will change to

coverage run -m pytest arg1 arg2 arg3

Now we’ll see how to do the same with unittest.

Unittest

Well, the unit test framework in python is called unittest, which comes packaged with python. Unit testing makes the code future proof since programmers anticipate the cases where the code could potentially fail or produce a bug.

When doing with unittest, simply replace python -m with coverage run -m.

python -m unittest test_code.py

 

Coverage will do all the work, and then for the report, the command is:

coverage report

 

Now our code will look like

> coverage run -m unittest test_tut.py.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Ran 1 test in 0.001s
OK
>coverage report
Name                 Stmts      Miss      Cover
— — — — — — — — — — — — — — — — — — — — — — — — —
test_tut.py        11          0      100%
tutorial.py              6          2       67%
— — — — — — — — — — — — — — — — — — — — — — — — —
TOTAL                   17          2       88%

 

You may wonder why the coverage is 88 percent. If we look at tut.py again, we can see that the if statement has another branch, which is what it must do in the event of "otherwise." Our testing must also cover that. As a result, we may add another method to the testing class to cover that branch. 

# test_tut.py
class PrintingTest(TestCase):
   .........
   def test_say_hello_noname(self):
       name = ''
       expected_output = 'Hello Stranger\n'
       with patch('sys.stdout', new=StringIO()) as fake_out:
           say_hello(name)
           self.assertEqual(fake_out.getvalue(), expected_output)
You can also try this code with Online Python Compiler
Run Code

 

An empty string is passed to check the output if it is “Hello Stranger” or not. Now let’s see the report that is generated.

> coverage run -m unittest test_tut.py
..
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Ran 2 tests in 0.001s
OK
>coverage report
Name                  Stmts      Miss      Cover
— — — — — — — — — — — — — — — — — — — — — — — — — — —
test_tut.py         17         0       100%
tutorial.py               6         1        83%
— — — — — — — — — — — — — — — — — — — — — — — — — — —
TOTAL                    23         1        96%

 

Improvement? Yes, of course, but still not 100%. So how to reach 100%? Well, if we see this is due to the snippet of code at the end of the tut.py, the part that asks for user input and then calls the function, that part of the code is not covered by testing. So to do so, just add " # pragma: no cover".

........
if __name__ == "__main__":
   say_hello(input("What's your name? "))  # pragma: no cover

 

Now let us again go to coverage to see the report.

...........
Name                  Stmts     Miss    Cover
— — — — — — — — — — — — — — — — — — —— — — — —
test_tut.py         17        0     100%
tutorial.py               5        0     100%
— — — — — — — — — — — — — — — — — — — — — — — —
TOTAL 22 0 100%

 

Woah, now it is 100%. To get the complete detailed report with each and every piece of information included, pass the command.

coverage html

 

From this command, a web page with a graphical interface will be generated. To access it, just go to folder "htmlcov" and double click index.html. 

Must Recommended Topic, Floor Division in Python and Convert String to List Python.

So, now it's time to check with exciting FAQs.

Also read,  Python filename extensions

Frequently Asked Questions

Why is coverage used?

Coverage assessment is commonly used to assess the efficiency of tests. It can reveal which sections of your code are being tested and which are not. 

How does coverage.py work?

Coverage monitors your programme, recording which sections of the code have been run, and then analyses the source code to find code that should have been executed but wasn't. 

What is unittest?

The unit test framework in python is called unittest, which comes packaged with python. Unit testing makes the code future proof since programmers anticipate the cases where the code could potentially fail or produce a bug.

What is Pytest?

Pytest is a testing framework based on python. It is mainly used to write API test cases.

What is Anaconda Distribution?

Anaconda is a Python and R programming language distribution aimed for simplifying package management and deployment in scientific computing (data science, machine learning applications, large-scale data processing, predictive analytics, and so on).

Let us now move to the conclusion part of the article.

Conclusion

In this article, we have extensively discussed Coverage in Python. At first, we saw the concept of coverage and why is there a need for coverage. Then we discussed an example of a Python script. And after that, we learned about the installation of coverage. Then we got to know how coverage is used. And at the end, we answered some frequently asked questions related to the topic. 

After reading about Coverage in python, are you not feeling excited to read/explore more articles on related topics? Don’t worry Coding ninjas has you covered. To learn see Testing Framework in PythonTesting in Python using DocTest, and Testify in Python.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problems, interview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass