简体   繁体   中英

How to run unittest tests using coverage API

I am trying to generate a coverage report using the coverage -API ( https://coverage.readthedocs.io/en/6.3.2/api.html#api ).

The simple use-case described on the linked page tells me to wrap my executed code inside the snippet they provide. I am using unittest.main() to execute tests. The below code runs without an error but neither is any report information created nor is print("Done.") executed.

I guess unittest.main() calls a sys.exit() somewhere along the way? How does one use the API to execute all unittest-tests?

Example

import coverage
import unittest


def func(input):
    return input


class testInput(unittest.TestCase):
    def test_func(self):
        self.assertEqual(func(1), 1)

    
if __name__ == '__main__':
    cov = coverage.Coverage()
    cov.start()

    unittest.main()

    cov.stop()
    cov.save()

    cov.html_report()
    print("Done.")

Yes, it looks like unittest.main() is calling sys.exit(). Are you sure you need to use the coverage API? You can skip coverage and most of unittest:

# foo.py
import unittest


def func(input):
    return input


class testInput(unittest.TestCase):
    def test_func(self):
        self.assertEqual(func(1), 1)

Then:

$ python -m coverage run -m unittest foo.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

$ python -m coverage report -m
Name     Stmts   Miss  Cover   Missing
--------------------------------------
foo.py       6      0   100%
--------------------------------------
TOTAL        6      0   100%

To get the example to work you can simply put the call to unittest.main() in a try/except statement so the cov.stop() will be called once the unit test has completed.

# testInput.py
import coverage
import unittest

def func(input):
    return input

class testInput(unittest.TestCase):
    def test_func(self):
        self.assertEqual(func(1), 1)

if __name__ == '__main__':
    cov = coverage.Coverage()
    cov.start()

    try:
        unittest.main()
    except:  # catch-all except clause
        pass

    cov.stop()
    cov.save()

    cov.html_report()
    print("Done.")

This will run as desired, including printing Done. at the end:

python3 testInput.py 
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
Done.

The HTML coverage report will have been created in the htmlcov directory in the current working directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM