[Python] How can I measure code coverage of API integration tests?

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    In my company we have a Django project that has API endpoints. We are using Pytest as testing framework and some of our tests executing requests to such endpoints using requests.Session(). For example:

    The test perform a GET request to /api/account/data

    content of root/dir/tests/test_api.py


    def test_some_api(self):
    client = requests.Session()
    response = client.get('/api/account/data')
    assert response.status_code == 200


    When performing the request, the backend execute this function: `

    root/models/account/api.py


    def user_data(request, format=None):
    """
    @api {get} /api/account/data
    """
    if request.method == "GET":
    return APIResponse(code=200)


    We would like to measure the code executed in `user_settings` by the test, but I failed to make it work. We are using:

    coverage==4.5.4 # forced to use an old version as we have dependencies conflict

    pytest-cov==2.10.1

    To measure coverage I run this command from root

    pytest -v --cov-report html:html-report --cov=dir --cov-config=dir/.coveragerc

    .coveragerc - has only files to exclude


    I verified in backend logs that when the test runs, it execute the if block inside user_settings

    I have tried adding this code to conftest.py as written in coverage docs, but it still didn't measure user_settings code execution.

    @pytest.fixture(scope='session', autouse=True)
    def run_cov():
    process = coverage.process_startup()
    source_path = os.path.join(_home_path, "/models/account")
    cov = coverage.Coverage(config_file='root/.coveragerc', source=[source_path])
    cov.start()
    yield cov # Tests runs here
    cov.stop()
    cov.save()
    cov.html_report(directory='html-report')


    I've seen this solution How to generate coverage report for http based integration tests?, but failed to understand how to implement it on my end.

    I expected user_settings code to be measured by coverage report.

    Continue reading...

Compartilhe esta Página