[Python] Coverage Discrepancies in pytest: Code Executed but Not Tracked

Discussão em 'Python' iniciado por Stack, Janeiro 31, 2025.

  1. Stack

    Stack Membro Participativo

    I discovered that when I run pytest with coverage, the coverage report shows that the tests do not fully cover the code, even though the tests execute the relevant code.

    Full Coverage Command (100% Coverage)


    coverage run --source=/root/MyProject/lib_python -m pytest /root/MyProject/tests/lib_python/test_something.py

    Partial Coverage Command (50% Coverage)

    • cd /root/MyProject; coverage run --source=lib_python -m pytest
    • cd /root/MyProject; coverage run --source=lib_python -m pytest /root/MyProject/tests/lib_python/

    Using the second command, the coverage report indicates that the lines return a + b and return a - b in lib_python/something.py are not covered.

    Context:

    • PYTHONPATH: /root/MyProject/lib_python
    • My module doesn't have a package name. It is unusual but it's due to legacy reasons.
    Code Files:

    lib_python/something.py


    def add(a, b):
    return a + b


    def sub(a, b):
    return a - b

    tests/lib_python/test_something.py


    python

    from something import add, sub

    def test_add():
    assert add(1, 2) == 3
    assert add(-1, 1) == 0
    assert add(0, 0) == 0

    def test_sub():
    assert sub(2, 1) == 1
    assert sub(1, 1) == 0
    assert sub(0, 1) == -1


    How do I get my coverage command to find and match coverage with the actual file?

    Continue reading...

Compartilhe esta Página