incorrect branch reporting with __debug__

Issue #522 resolved
John Theodore Goetz
created an issue

Coverage report indicates a missing branch with __debug__ within an if/else block. Note if a pass is added after the if __debug__ then coverage is correctly shown as 100%.

for value in [True, False]:
    if value:
        if __debug__:
            x = 1
        #pass  # required for coverage to show 100%
    else:
        x = 2

Running coverage in both __debug__ and with python -O (appending the results):

python -mcoverage erase
python -mcoverage run --branch prog.py
python -O -mcoverage run --branch --append prog.py
python -mcoverage report -m

Results in the following:

Name       Stmts   Miss Branch BrPart  Cover   Missing
------------------------------------------------------
prog2.py       4      0      4      1    88%   2->1

Comments (8)

  1. Ned Batchelder repo owner

    A simpler case will show the problem:

    $ cat bug522.py
    one = 1
    for value in [True, False]:
        if value:
            if one:
                x = 1
        else:
            x = 2
    
    for value in [True, False]:
        if value:
            if 1:
                x = 1
        else:
            x = 2
    $ python -m coverage run --branch bug522.py
    $ python -m coverage report -m
    Name        Stmts   Miss Branch BrPart  Cover   Missing
    -------------------------------------------------------
    bug522.py      10      0     10      2    90%   4->2, 10->9
    

    The "if 1:" statement doesn't appear in the compiled bytecode, so it's being removed from consideration, which makes the branch be attributed to 10->9 rather than 11->9.

  2. Log in to comment