rillig / gobco

Measure branch coverage of golang tests
62 stars 12 forks source link

TestMain injection with `_test` package suffix fails #32

Closed Evertras closed 5 months ago

Evertras commented 5 months ago

As a minimum way to recreate, have these two files in a directory:

// add.go
package add

func Add(x, y int) int {
    return x + y
}
// add_test.go
package add_test

import (
    "os"
    "testing"

    "my-module/pkg/add"
)

func TestMain(t *testing.M) {
    os.Exit(t.Run())
}

func TestAdd(t *testing.T) {
    result := add.Add(1, 2)
    if result != 3 {
        t.Errorf("Got %d but wanted 3", result)
    }
}

The error is:

# Cutting out extra bits
$ gobco
./add_test.go:11:10: undefined: gobcoCounts

If I remove TestMain, it works. Looking at gobco -keep, it looks like gobcoCounts is defined in its own file that would use package add, not package add_test. We use the _test pattern to help enforce testing external behavior, and we can't move TestMain out because it also initializes some connections that are referenced in the actual tests.

rillig commented 5 months ago

Thanks for the detailed bug report. I already had all ingredients for fixing this use case, so the actual fix is quite small.

Evertras commented 5 months ago

Awesome, thank you so much for an incredibly fast fix! This has been a very helpful tool for us to deal with auditing.