beeware / beeware/toga

Coverage ignores implicit else in try blocks

Open
#3,590 11 comments 0 reactions 0 assignees View on GitHub
bug
Dominant language
Python
Stars
5.4k
Forks
827
Avg merge
15h 39m
Merged PRs (30d)
40

Description

### 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.

https://github.com/nedbat/coveragepy/issues/877

### Steps to reproduce

Consider the following code, from the issue linked above:

```python
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`:

```python
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.

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the minimal f(x) example with Coverage 7.9.1, then read the linked coverage.py issue and the discussion in #3569 and #3589. Check whether the needed branch accounting belongs in Toga or coverage.py; done means establishing a concrete, project-appropriate change that verifies both the exception and no-exception paths.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing-qa
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.