Using pytest, is it possible for a unit test to know that it is being run with code coverage monitoring on?

时间:2018-01-23 19:13:26

标签: python unit-testing pytest coverage.py

I am currently developing some tests using python py.test / unittest that, via subprocess, invoke another python application (so that I can exercise the command line options, and confirm that the tool is installed correctly).

I would like to be able to run the tests in such a way that I can get a view of the code coverage metrics (using coverage.py) for the target application using pytest_cov. By default this does not work as the code coverage instrumentation does not apply to code invoked with subprocess.

Code Coverage of the code does work if I update the tests to directly invoke the entry class for the target application (rather than running via the command line).

Ideally I want to have a single set of code which can be run in two ways:

  1. If code coverage monitoring is not enabled then use command line
  2. Otherwise execute the main class of the target application.

Which leads to my question(s):

  • Is it possible for a python unit test to determine if it is being run with code coverage enabled?
  • Otherwise: is there any easy way to pass a command line flag from the pytest invocation that can be used to set the mode within the code.

1 个答案:

答案 0 :(得分:0)

Coverage.py可以自动衡量产生的子流程的覆盖范围:http://coverage.readthedocs.io/en/latest/subprocess.html