Tip:
Highlight text to annotate it
X
Back to coverage metrics.
We just talked about statement coverage, which is closely related to line coverage,
but it's a bit more fine-grained,
and now let's talk about what is probably the only other test coverage metric
that will matter in your day-to-day life unless you go build avionics software.
Branch coverage is a metric where a branch in a code is covered, if it executes both ways.
For example, to get 100% branch coverage for the statement that tests whether x = 0,
it would be needed to be executed in a state where x was zero
and also in a state where x was not equal to zero.
And so, in many cases, branch coverage and statement coverage have the same effect.
For example, if our code only contained if-then-else loops,
the metrics would be equivalent.
On the other hand for code like this that's missing the else branches they're not quite equivalent.
We can take as inputs to this code x =0 and y is -1.
These inputs were sufficient to get 100% statement coverage.
On the other hand, these are not sufficient to get 100% branch coverage.
What happens is these cause the taken branch of the if to be executed but not the else branch.
Then the taken branch of the second if to be executed, but not the else branch.
There are different ways to score branch coverage, but one way we can do it
is there are two ways to take this branch, two ways to take this branch,
so we could say this is 50% branch coverage.
The other thing we could do, however, it do what our Python module for coverage is going to do,
we could say that both of these branches were partially executed.
That is to say, one of their possibilities was realized during testing.
No branches were completely missed, and no branches were totally covered.
So, let's go ahead and see how our coverage module tells us this.
Right, so as you see here, I've typed into an editor window the same code that I wrote down
by hand on the left part of the slide.
And so we're going to invoke the function foo with x being 0 and y being -1.
Let's see what happens.
We're going run this under the coverage tool,
but this time we're going to give the coverage run command, and argument--branch.
That simply tells it to measure branch coverage instead of just measuring statement coverage.
It's again going to render some HTML as a result,
and if we look at the output, it's going to tell us that out of six statements
all six of them were run, and there were zero missing statements.
So, at the statement level, we've achieved 100% coverage.
On the other hand, at the branch level, we had two branches that were partially executed--
that is to say, only one of their two possibilities was realized during execution.
Now, if we change this a little bit by calling foo a second time with 0 and -2,
run the coverage tool again, what we'll see is that the second branch,
the test of y now is executed both ways.
On the other hand, the first branch, the one that tests x still is partially executed.