condition was never false
Opened this issue · 2 comments
Summary
The target function is below.(This is code that occurs the issue.)
def main(value):
result = None
try:
try:
result = 1 / value
finally:
if result is not None:
print(result)
except ZeroDivisionError as ex:
print(ex)
The test function is below.
import pytest
from target import main
@pytest.mark.parametrize('value', [
1,
0,
])
def test(value):
main(value)
Expected vs actual result
- Expected
- I want complete branch coverage on line 7.
- actual
line 7 didn't return from function 'main', because the condition on line 7 was never false
line 7 didn't return from function 'main', because the condition on line 7 was always true
(5.0.0)
Reproducer
Versions
title | value |
---|---|
Python | 3.9.18 |
Platform | Linux-5.4.0-181-generic-x86_64-with-glibc2.31 |
Packages | pytest: 7.4.2 |
pluggy: 1.3.0 | |
Plugins | html: 4.0.2 |
cov: 4.1.0 | |
metadata: 3.0.0 | |
mock: 3.12.0 | |
only: 2.0.0 |
Config
not use.
What has been tried to solve the problem
Add dummy code to line 9.
This is a complicated situation. In theory, the condition on line 7 could be False and the if could return from the function. We can tell by looking at the code and thinking about it that if that condition is False it won't return from the function, it will branch to the except ZeroDivisionError
on line 9. But coverage.py can't do that level of analysis, so it decides there is a possibility that has been missed. The message is a bit misleading, the missing branch isn't "because the condition on line 7 was never false", it's more complicated than that. (BTW: that message in the latest code has been flipped to "because the condition on line 7 was always true".)
You should had a partial branch pragma to the condition to quiet the message.
Thanks for your reply.
We can tell by looking at the code and thinking about it that if that condition is False it won't return from the function, it will branch to the
except ZeroDivisionError
on line 9. But coverage.py can't do that level of analysis, so it decides there is a possibility that has been missed.
It seems difficult to check such code correctly...
I know this code is bad, but I cannot refactor it right now.
So I wanted to know how to properly check it with coverage...