python statistical code coverage

[demand] what is code coverage? Why code coverage?
1 Coverage is to count which codes are executed and invoked in a period of time. If there are 100 lines of code coverage statistics, it is the proportion of how many codes are executed from the beginning to the end of the statistics.
2 why use case to supplement testing. Received a test requirement, designed a test case according to business, etc., but did not have the bottom case in mind can cover all scenarios? Add the case before the code coverage is perfect.

Coverage statistics python code coverage

pip install coverage -i http://Pypi.douban.com/simple/--trusted-host pypi.douban.com plus domestic download sources to ensure successful download
C:\Users\Desktop>coverage --help               #Verify successful installation
Coverage.py, version 3.6
Measure, collect, and report on code coverage in Python programs.

usage: coverage <command> [options] [args]

Commands:
    annotate    Annotate source files with execution information.
    . . . 

[Use Tool Case]
First, find a test file to be counted, such as test.py (you can see that only statements after else do not execute)

import json
test = 'aaaaa'


def writejson():
    testdata = {
        "uris": ["files/6f49779435a62fe8211da0e9f515fe0d73b22fe4/logs/owl/storage"]
    }
    testdata = json.dumps(testdata)
    print(testdata)

    if test:
        print('22222222222222')
    else:
        print('33333333333333333')


writejson()

Start coverage statistics implementation

C:\Users\Desktop>coverage run test.py          #Start statistical execution and automatically generate A. coverage file after execution
C:\Users\chenyandong\Desktop>coverage report -m             #Command Line Statistical Summary, 90% Execution Rate
Name    Stmts   Miss  Cover   Missing
-------------------------------------
test       10      1    90%   15

C:\Users\chenyandong\Desktop>coverage html
C:\Users\chenyandong\Desktop>coverage html -d reportcoveragehtml  #The folder that generates the report coverage html, which contains the result report of html, looks more intuitive (as shown below)



Statistical results file, red background lines indicate no execution.
With several parameters, you can use it almost by yourself. For example: coverage annotate test.py will generate a test.py,cover file, the content is as follows (! Represents lines of code that are not executed)

> import json
> test = 'aaaaa'
  
  
> def writejson():
>     testdata = {
>         "uris": ["files/6f49779435a62fe8211da0e9f515fe0d73b22fe4/logs/owl/storage"]
>     }
>     testdata = json.dumps(testdata)
>     print(testdata)
  
>     if test:
>         print('22222222222222')
!     else:
!         print('33333333333333333')
  
  
> writejson()

Tags: JSON Python pip

Posted on Sun, 06 Oct 2019 17:00:33 -0700 by gdogfunk