11

Consider we have this function under test located in the module.py:

def f(a, b):
    return (a - b) if a > b else 1 / 0

And, we have the following test case in the test_module.py:

from unittest import TestCase

from module import f


class ModuleTestCase(TestCase):
    def test_a_greater_than_b(self):
        self.assertEqual(f(10, 5), 5)

If we run tests with pytest with the enabled "branch coverage" with the HTML output reporting:

pytest test_module.py --cov=. --cov-branch --cov-report html

The report is going to claim 100% branch coverage with all the "partial" branches covered:

enter image description here

But, we clearly have not covered the else 1 / 0 part at all.

Is there a way to improve reporting to see the non-covered parts of the ternary operators?

1
  • 3
    Unlike the keyword version the operator version of if / else is not a control structure but a boolean operation. The actual control structure is hidden in the implementation of the operation, out of the sight of coverage. I agreed that it would be a good idea to have that implemented into the coverage package. Commented Dec 24, 2017 at 5:09

1 Answer 1

14
+50

Branch coverage can only measure branching from one line to another, since Python's trace facility currently only supports per-line tracing. Python 3.7 introduces some bytecode-level tracing, but it would require significant work to make use of it.

https://github.com/nedbat/coveragepy/issues/509 is an issue about this.

Sign up to request clarification or add additional context in comments.

2 Comments

Now that Python 3.7 is in pre-release, shouldn't the referenced issue be reopened (I ask because I see you are the maintainer)? PS. "opened" != "solved right away", but it is surely an important feature, no?
It would be better to discuss the issue on the issue, no?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.