Skip to content

Coverage ignores implicit else in try blocks #3590

@HalfWhitt

Description

@HalfWhitt

Describe the bug

I know I already mentioned this in #3569 and #3589, but I think it should have its own place.

I've discovered something I find unnerving... If you have a try / except with no else, Coverage doesn't make sure you've tested it without catching the exception.

nedbat/coveragepy#877

Steps to reproduce

Consider the following code, from the issue linked above:

def f(x):
    try:
        y = 1/x
    except ZeroDivisionError:
        y = 0
    return y

One would presumably like to test at least two cases: one in which the ZeroDivisionError is encountered, and one in which it isn't. However, if you only test f(0), Coverage will tell you there are no missed branches. In order for Coverage to consider the no-error case, you need an explicit else:

def f(x):
    try:
        y = 1/x
    except ZeroDivisionError:
        y = 0
    else:
        pass
    return y

Expected behavior

Ideally, we would have a way to make sure we're exercising both options in a try / except — or potentially more than two, if the except catches more than one type of error.

Environment

Coverage 7.9.1

Additional context

I've not attempted anything close to an exhaustive search, but there are definitely try blocks in Toga's code that have no else. We might be testing both the exception and no-exception cases, but currently we have no way of systematically ensuring this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA crash or error in behavior.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions