How to load configuration from .yaml file before executing all go test files?

Viewed 843

I wrote a go test file in a package then run go test ./... to execute all tests.

The problem is some test need app config which is stored in .yaml file in project root dir. Normally when I run main.go file in root, it works well since the current working dir os.Getwd() will be the root dir. But when running test, the current working dir becomes the test file path which make the config file cannot be found.

I was thinking of 2 solution:

  • Initialize config before for all tests
  • Update the config init function to use to project root dir instead of current working dir

I tried searching but haven't found any solution yet.

Thank you in advance!

1 Answers

If you want a collection of tests to share logic/state, then I'd suggest looking at TestMain.

From there you can optionally pre-load alternative logic and make it available to all or a subset of your tests:

var (
    testConfig *Config // use this global config in tests
)

func TestMain(m *testing.M) {

    // optional alternative config via ENV VAR `CONFIG`
    if path := os.Getenv("CONFIG"); path != "" {
        
        conf, err := LoadConfig(path)
        if err != nil {
            log.Fatalf("Failed to load config file %q : %v", path, err)
        }

        testConfig = &conf

    } else {
        testConfig = &DefaultConfig // no override - so use default config
    }

    // call flag.Parse() here if TestMain uses flags
    os.Exit(m.Run())
}
Related