This is an example of how to use gunicorn server hooks to run coverage on a flask app. In short:
- The post_fork hook starts coverage for each worker.
- The worker_exit hook stops and saves coverage for each worker.
This allows you to use kill -HUP <master pid>
to produce
coverage files. The HUP signal kills all of the worker
processes, letting them write their coverage data, and then
restarts the entire server.
pip install -r requirements.txt
First start the server:
gunicorn --workers 2 app:app
Make a note of the PID of the master process.
Then invoke endpoints on your server via curl or a browser. Once you've probed it (or not!), you can restart the server:
kill -HUP <master PID>
This will generate worker-specific coverage files in the form .coverage.<host>.<PID>.<random #>
.
You can combine these (together with any existing .coverage file) with:
coverage combine
This will produce a .coverage
file which can be used to report coverage.
Note that by default the coverage combine
command will lose any existing coverage results. That is,
if a .coverage
file exists before running combine
, it will be cleared before combining the new
results into it.
If you want to keep existing results and merge in the new coverage data, you can use coverage combine --append
.
There are other ways to control how combining work which you can find here or by running coverage combine --help
.
To generate a report of coverage for the lib.py
module, use:
coverage report lib.py
The HUP
signal causes the server to restart, so you can continue using it afterward.
If you want to start coverage analysis afresh, you
should kill the server entirely. Then remove .coverage
if it exists, along with any partial .coverage.<host>.<PID>.<random #>
files. DO NOT DELETE .coveragerc
!`