Handling Viper Config File Path During Go Tests
Asked Answered
B

3

6

So I have a pretty basic configuration with Viper reading a .env file from my base directory. I fatal kill the process if there's no .env file. All goes well when running my app normally. When I run my tests with go test -v ./.., the test framework seems to step into each file's directory, and calls my config init() function each time, so the viper.AddConfigPath(".") is pointing to the wrong location.

this is my directory structure:

/
  /restapi
    items.go
    items_test.go
  /util
    env.go
  main.go
  .env

env.go

package util

imports...

// global variables available via util package
var (
  Port     int
  DbURI    string
)

func init() {
  viper.SetDefault(PORT, 8080)
  viper.SetConfigFile(".env")
  viper.AddConfigPath(".")
  viper.AutomaticEnv()

  fmt.Println("---------to see in test printout")
  cwd, _ := os.Getwd()
  fmt.Println(cwd)
  fmt.Println("---------")

  if err := viper.ReadInConfig(); err != nil {
    log.Fatal("no environment file!")
  }

  Port = viper.GetInt("PORT")
  DbURI = viper.GetString("DB_URI")
}

Every package basically relies on my util package and this init function therefore runs for every test. Is there some way to have viper always pull the .env file from the base directory even when there are tests running? I've tried a few different AddConfigPath() calls. Kinda new to Go. Or is this structure setup for environment variables not going to work since it fails my tests each time?

Beeswing answered 18/3, 2021 at 1:24 Comment(0)
B
3

So apparently the viper.SetConfigFile() call does not respect the viper.AddConfigPath() call... I modified this to using viper.SetConfigName(".env") and it would actually pick up the calls to AddConfigPath, so I could then add config paths for the current directory and parent.

Beeswing answered 30/3, 2021 at 1:59 Comment(0)
I
1

The problem is the path you are giving to the viper.AddConfigPath(".") method, but your env file relative path is not on the test file based on the folder structure tree you shared, it must be this: viper.AddConfigPath("./../util").

Indocile answered 7/6, 2021 at 14:54 Comment(0)
A
1

in my case, config.json is beside go.mod (root of project) and i use this func for get config:


func FindConfigFile() {
    var err error
    path := "./"
    for i := 0; i < 10; i++ {

        viper.AddConfigPath(path)
        viper.SetConfigName("config")
        viper.SetConfigType("json")
        err = viper.ReadInConfig()
        if err != nil {
            if strings.Contains(err.Error(), "Not Found") {
                path = path + "../"
                continue
            }
            panic("panic in config parser : " + err.Error())
        } else {
            break
        }
    }
    

}

because test files are in nested directory of project , Finally we catch config.json :)

Anisole answered 7/8, 2023 at 13:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.