share
Stack OverflowPython coverage - skip or mock input method
[0] [1] Randy
[2017-11-11 11:25:59]
[ python bash unit-testing jenkins coverage.py ]
[ https://stackoverflow.com/questions/47237373/python-coverage-skip-or-mock-input-method ]

Context

I have a python application that I'm unit testing. Half the application is working and I have a very high test accuracy.

The application requires one-time user input for installation purposes.

This means that, if you run the code, there has to be interaction with a user.


Problem

Coverage [1] is a Python plugin for coverage reports. I use coverage with this command:

coverage run application.py

Coverage runs my application, goes through my tests, and delivers a coverage report.

The problem is that the command to run those tests, executes my application and I have to provide input. That's not that big of a deal, but I cannot do that on my CI server using Jenkins (or can I?).


Question

I want to run the coverage tool without user input. In my tests, the input function is mocked out. Running all my tests without coverage works fine. How can I prevent coverage from requiring user input?

[+1] [2017-11-11 16:50:56] Olivier Le Floch [ACCEPTED]

You should probably have 2 different code paths, one for running the tests, and one for running the app:

coverage run tests.py

with tests.py importing application.py, mocking methods as necessary, then running the actual application.

Or you could allow user input via command line arguments:

coverage run application.py --user=input --other="etc."

Finally, if there truly are portions of your app that cannot be tested or reasonably mocked (it happens, say you're calling out into a third party exception tracking library/service that you can't load in your tests), you can instruct coverage to ignore those lines for the purposes of computing coverage, by adding # pragma: no cover at the end of the instruction that you won't be fully testing:

my = "code"
goes = "here"

if debug:  # pragma: no cover
    call_untestable(code=True)
    this_portion(ignored_for_coverage=True)

covered_code = "yes, again!"

See more here:

http://coverage.readthedocs.io/en/coverage-4.2/excluding.html


Awesome answer. Thank you! - Randy
1