How to get code coverage percentage value for Pytest?

1.5k views Asked by At

I want to send code coverage percentage value for my pytest tests to external system. Xml or Html reports are not compatible for me since they contain a lot of redundant information. Is it possible to get this value in some pytest fixture to send it to external system after test execution?

1

There are 1 answers

0
hoefling On

You can access the coverage instance via the cov fixture. However, IIRC you need to actually generate a report to get the percentage (or calculate it yourself in a custom coverage plugin). In the below example, I use a session-scoped, autouse fixture so it is called automatically once per test run and write the report to a disposable file object:

import io
import pytest


@pytest.fixture(scope="session", autouse=True)
def upload_coverage(cov):
    yield
    cov.save()
    percentage = cov.report(file=io.StringIO())
    # percentage is a float which you can upload now