61 lines
1.7 KiB
Go
61 lines
1.7 KiB
Go
|
package config
|
||
|
|
||
|
import (
|
||
|
"os"
|
||
|
"testing"
|
||
|
|
||
|
"github.com/rs/zerolog"
|
||
|
"github.com/spf13/viper"
|
||
|
)
|
||
|
|
||
|
// writeTestConfigFile creates a test config file at given filename location
|
||
|
func writeTestConfigFile(t *testing.T, filename string) {
|
||
|
testdata := []byte("[application]\nlisten = \"127.0.0.1\"\n[database]\nport = 54321\ntestbool = false")
|
||
|
err := os.WriteFile(filename, testdata, 0644)
|
||
|
if err != nil {
|
||
|
t.Fatalf("Can't write test file %q: %v", filename, err)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// removeTestConfigFile removes given config file
|
||
|
func removeTestConfigFile(t *testing.T, filename string) {
|
||
|
err := os.Remove(filename)
|
||
|
if err != nil {
|
||
|
t.Fatalf("Can't remove test file %q: %v", filename, err)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// TestLoadConfigFile calls config.loadConfigFile
|
||
|
// to check if a valid Configuration can be loaded.
|
||
|
func TestLoadConfigFile(t *testing.T) {
|
||
|
logger := NewLogger(zerolog.InfoLevel)
|
||
|
dir, err := os.Getwd()
|
||
|
if err != nil {
|
||
|
t.Fatalf("Can't get current working directory")
|
||
|
}
|
||
|
|
||
|
testFile := dir + "/" + "config_unittest.toml"
|
||
|
|
||
|
writeTestConfigFile(t, testFile)
|
||
|
|
||
|
defer removeTestConfigFile(t, testFile)
|
||
|
|
||
|
loadConfigFile(testFile, logger)
|
||
|
|
||
|
if viper.GetString("application.listen") != "127.0.0.1" {
|
||
|
t.Fatalf(`viper.GetString("application.listen") = %q, want "127.0.0.1"`, viper.GetString("application.listen"))
|
||
|
}
|
||
|
|
||
|
if viper.GetInt("database.port") != 54321 {
|
||
|
t.Fatalf(`viper.GetInt("database.port") = %q, want 54321`, viper.GetInt("database.port"))
|
||
|
}
|
||
|
|
||
|
if viper.GetBool("database.testbool") != false {
|
||
|
t.Fatalf(`viper.GetBool("database.testbool") = true, want false`)
|
||
|
}
|
||
|
|
||
|
if viper.GetString("invalid.config.value") != "" {
|
||
|
t.Fatalf(`viper.GetString("invalid.config.value") = %q, want ""`, viper.GetString("invalid.config.value"))
|
||
|
}
|
||
|
}
|