liveBook · Manning

Branch coverage

As explained in Practices of the Python Pro

Branch coverage is a test coverage metric measuring which branches of a program's control flow have been executed by tests.

Branch coverage measures whether tests execute the alternative branches in a program’s control flow. Each if, while, and similar decision creates different preconditions to test. section 9.1.3

Use it to find untested paths, often associated with edge cases. Perfect coverage still does not prove that the code works; it only proves that those parts ran. section 9.1.3

Conditional and loop branches

For has_long_words, tests should exercise non-string and string inputs, an input containing a word longer than ten characters, and inputs where no word meets that condition. section 9.1.3

Listing 9.1. A function with conditionals and a loop
def has_long_words(sentence):
    if isinstance(sentence, str):          #1
        sentence = sentence.split(' ')

    for word in sentence:                  #2
        if len(word) > 10:                 #3
            return True

    return False                           #4

Inspect the compact function to identify its conditional, loop, early return, and final return paths. section 9.1.3

How Practices of the Python Pro covers it

How deep it goes
Defines execution-path coverage and its limitation, then points to tooling without developing measurement internals.
Examples
Uses a Python function with type checking, a loop, a length condition, an early return, and a fallback return.
What you can do after
Apply it via the Coverage package to inspect branch coverage metrics for tests.
How it connects
Connects branch coverage with control flow, test coverage, edge cases, and cyclomatic complexity.

Also explained in

Compare how 3 books explain branch coverage →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practices of the Python Pro. The section links point to the parts of the book it draws on.