Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting branch coverage for golang tests

Tags:

go

Can someone suggest a way to me if we can get branch coverage for my golang tests? Let's say I have a golang code which looks like below:

package main

import (
    "fmt"
)

func HelloWorld(name string, printv int) string {
    if name == "tuk" || printv == 1 {
        fmt.Println("Hello tuk")
        return "Hello tuk"
    } else {
        fmt.Println("Who are you?")
        return "Who are you?"
    }
}

The corresponding test file looks like below:

package main

import "testing"

func TestHelloWorld(t *testing.T) {
    r := HelloWorld("tuk", 0)
    if r != "Hello tuk" {
        t.Error("Test Failed")
    }
}

If I execute the below test command, it is just giving me the statement coverage:

go test -coverprofile=cover.out .
ok      test    0.007s  coverage: 60.0% of statements

Is there a way I can get the branch coverage as well?

like image 643
tuk Avatar asked May 21 '16 13:05

tuk


People also ask

How do I get test coverage on go?

To do test coverage in Go we create a test file by adding a _test suffix. Then we simply use test functions in that file. To generate the coverage report, the -cover flag is added after that. This cover flag tells the test tool to generate coverage reports for the package we are testing.

How is branch coverage calculated in testing?

To calculate Branch Coverage, one has to find out the minimum number of paths which will ensure that all the edges are covered. In this case there is no single path which will ensure coverage of all the edges at once. The aim is to cover all possible true/false decisions.

What are the required test cases to obtain 100% branch coverage?

To achieve 100% condition coverage, test cases need to make a > 0 as true and false as well as b > 0 as true and false. However, t1 and t2 fail to make a > 0 as false so that the 100% condition coverage is not satisfied.

Does 100% path coverage imply 100% branch coverage?

Explanation: True : A minimal test set that achieves 100% path coverage will also achieve 100% statement coverage.


1 Answers

As of Go 1.11 (November 2018), the generated machine code for the coverage only covers each block of statements. It should be possible to take that code and adjust it to cover every branch of an expression.

It looks as if the gobco project has done exactly this, although only for single files and not for whole packages (again, as of November 2018).

I filed an issue to see whether branch coverage is considered to be worthwhile by the Go team. The decision is to keep the current code as simple as it is now, and that decision had already been documented in the code itself.

In the end I forked the gobco project and added all the features I need.

like image 102
Roland Illig Avatar answered Oct 15 '22 16:10

Roland Illig