vendredi 2 octobre 2020

Are tests in Go sub-packages agglomerated into one executable?

I'm working on a Go project which has the usual package main in the top folder and two sub- packages which I'll name a and b.

For test purposes, I want to load the .env file. For that reason, I make use of the gotdotenv package and use its load command manually like so:

func TestMain(m *testing.M) {
    if err := godotenv.Load("../.env"); err != nil {
        fmt.Println("Error loading .env file", err)
        os.Exit(1)
    }
    os.Exit(m.Run())
}

Note: the autoload doesn't work for sub-packages because they are run from within one of the packages sub-directory instead of the root where the .env file resides.

When I had just one sub-package the tree was simple and the tests compiled. Now that I have two tests in separate sub-directories and different names, the go compiler tells me I have two of the same functions and that one has to go:

multiple definitions of TestMain

So it looks like go merges all the tests at the module level in one single executable.

Note that my main_test.go has a TestMain() along the module1/my_module_test.go and I am not getting an error about duplicates.

It is only when I added the module2/other_module_test.go that I see the "multiple def..." error.

My concern is that in this way only ONE sub-module has to initialize the tests of BOTH modules, which to me doesn't make sense. Is that indeed a limitation of the go test environment?

Is there something I missed to make it possible to initialize each package with its own initialization function?

Aucun commentaire:

Enregistrer un commentaire