Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Coverage and Ternary Operators

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?

like image 987
alecxe Avatar asked Dec 24 '17 04:12

alecxe


People also ask

What is the point of code coverage?

Code coverage is a metric that can help you understand how much of your source is tested. It's a very useful metric that can help you assess the quality of your test suite, and we will see here how you can get started with your projects.

Can ternary operator be nested in Javascript?

Ternary Operator in Javascript makes our code clean and simpler. It can be chained like an if-else if....else if-else block. It can also be nested like a nested if-else block. It helps to handle null or undefined values easily.

What is branch in jest coverage?

Branch coverage is a requirement that, for each branch in the program (e.g., if statements, loops), each branch have been executed at least once during testing. (It is sometimes also described as saying that each branch condition must have been true at least once and false at least once during testing.)


1 Answers

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.

like image 141
Ned Batchelder Avatar answered Sep 23 '22 16:09

Ned Batchelder