Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic block coverage - what's the precise definition?

Let's say I have this piece of C/C++ code:

int c = 12; // Should I count this line as basic block?
if (a != 0 && b > 10) {
    c += (a + b);
} else {
    c += 1;
}
printf("%d", c); // Should I count this line as basic block?

What is the basic block coverage for test case a = 1, b = 12?

Is it 75% or 50%?

Should I count 1st and last lines as basic blocks? What is the precise definition of basic block?

Another point of confusion:

int c = 16;
d += c;

Is it one basic block or 2 basic blocks? Should every line be counted as a basic block?

like image 336
Maciej Ziarko Avatar asked Jan 14 '12 10:01

Maciej Ziarko


People also ask

What is block coverage?

Block coverage, sometimes known as line coverage, describes whether a block of code, defined as not having any branch point within (i.e. the path of execution enters from the beginning and exits at the end) is executed or not.

What is line coverage?

The Line Coverage of a program is the number of executed lines divided by the total number of lines. Only lines that contain executable statements are considered, not those with pure declarations.

What is function coverage in unit testing?

Function coverage criteria is simply how many of your functions are under test. In our example, we only have a single function. And we called it in our test, so our function coverage is 100%.


1 Answers

A basic block contains all instructions which have the property that if one of them is executed then all of the others in the same basic block are. Naming the first instruction of the basic block a leader we get to the following definition of a basic block: the set of all instructions following a leader which get executed if the leader is executed. The leader is the start of the basic block.

To determine the leader find all jump instructions in your code. Each jump target and each instruction after a jump is a leader. The first instruction in a method is also a leader.

To find the basic blocks simply go through all instructions from a leader to the next.

Your first example:

int c = 12; // Leader
if (a != 0 && b > 10) { // Jump
    c += (a + b); // Leader
} else {
    c += 1; // Leader
}
printf("%d", c); // Leader -- target of jump from the end of the true branch

You have 4 basic blocks there: one for each branch of the if, one for the printf after the if and one for the initialization of c. If a == 1 && b == 12 only three basic blocks are executed thus coverage is 75%.

Your second example has no jump instruction => there is only one basic block.

like image 166
Mihai Maruseac Avatar answered Oct 04 '22 22:10

Mihai Maruseac