I'm working on a CLI program using click, and I want to start adding some tests with code coverage analysis using coverage.py.
I thought a good way to implement the tests would be to run the CLI itself using subprocess. However, coverage.py reports zero code coverage, presumably because the Python instance spawned by subprocess doesn't have the coverage.py instrumentation.
I found this link that says I can drop a sitecustomize.py
file in my PYTHONPATH to always force Python to start coverage measurement, but I'm using Tox to create a venv and run tests. I couldn't find any Tox settings that deal with this.
I found this answer that says I should just run my CLI through coverage run
, but it looks like that only works if given a path to a Python script, and I'm trying to run my CLI through the entry point defined in setup.py
. i.e. I have to change all my command lines in test code from myprogram
to coverage run myprogram/cli/cli.py
. I'd rather not do this because it's not the way I expect users to run the program.
So it seems like the two options are:
figure out a way to make
sitecustomize.py
work in Tox environments, orall command lines in test code to use a script path instead of an entry point (probably easier in the long run, but makes tests slightly more brittle and harder to understand). Wondering if there's anything else I'm missing.
os.environ
andsys.argv
as expected and then callmyprogram.main()
directly. This approach works well withtox
,coverage
, and other tools I've used. – Molybdenoussys.argv
. You can add that as an answer if you want. This answer says you should mocksys.argv
withunittest.mock
, but that feels like overkill without knowing some specific reasons why... – Undrapeargparse.ArgumentParser:parse_args()
. – Undrape