golang-app/pkg/config/Config_test.go

100 lines
2.8 KiB
Go

package config
import (
"github.com/stretchr/testify/assert"
"strconv"
"sync"
"testing"
)
const (
telegramToken = ":: telegram telegram token ::" //nolint:gosec // it is not real credentials
telegramOwner = 1234567890
pathDictionaries = `docs/dictionaries`
)
func TestGetConfig(t *testing.T) { //nolint:paralleltest // because this test mock globals
initTelegramBotEnvironment(t, telegramToken, telegramOwner, pathDictionaries)
defer resetConfig(t)
var config Config
assert.NotPanics(t, func() { config = GetConfig() })
assert.NotNil(t, config)
assert.Equal(t, telegramToken, config.API.Token)
assert.Equal(t, telegramOwner, config.API.Owner)
assert.Equal(t, pathDictionaries, config.Paths.Docs)
}
func TestGetConfigTwice(t *testing.T) { //nolint:paralleltest // because this test mock globals
initTelegramBotEnvironment(t, telegramToken, telegramOwner, pathDictionaries)
defer resetConfig(t)
config1 := GetConfig()
config2 := GetConfig()
assert.NotNil(t, config1)
assert.NotNil(t, config2)
assert.Equal(t, config1, config2)
assert.NotSame(t, config1, config2)
}
func TestGetConfigAndSingletonIsImmutable(t *testing.T) { //nolint:paralleltest // because this test mock globals
initTelegramBotEnvironment(t, telegramToken, telegramOwner, pathDictionaries)
defer resetConfig(t)
config1 := GetConfig()
assert.Equal(t, telegramToken, config1.API.Token)
assert.Equal(t, telegramOwner, config1.API.Owner)
assert.Equal(t, pathDictionaries, config1.Paths.Docs)
config1.API.Token = ":: some another telegram token ::"
config1.API.Owner = 1
config1.Paths.Docs = ":: some else path ::"
config2 := GetConfig()
assert.Equal(t, telegramToken, config2.API.Token)
assert.Equal(t, telegramOwner, config2.API.Owner)
assert.Equal(t, pathDictionaries, config2.Paths.Docs)
}
func TestGetConfigWithOnlyRequiredEnvironment(t *testing.T) { //nolint:paralleltest // because this test mock globals
t.Setenv("TOKEN", telegramToken)
t.Setenv("OWNER", strconv.Itoa(telegramOwner))
resetConfig(t)
defer resetConfig(t)
config := GetConfig()
assert.NotEmpty(t, config)
assert.IsType(t, Config{}, config)
assert.Equal(t, telegramToken, config.API.Token)
assert.Equal(t, telegramOwner, config.API.Owner)
assert.Equal(t, `docs`, config.Paths.Docs)
}
func TestGetConfigWithEmptyEnvironment(t *testing.T) { //nolint:paralleltest // because this test mock globals
resetConfig(t)
defer resetConfig(t)
assert.Panics(t, func() { GetConfig() })
}
func initTelegramBotEnvironment(t *testing.T, telegramToken string, telegramOwner int, pathDictionaries string) {
t.Helper()
t.Setenv("TOKEN", telegramToken)
t.Setenv("OWNER", strconv.Itoa(telegramOwner))
t.Setenv("DOCS_PATH", pathDictionaries)
resetConfig(t)
}
func resetConfig(t *testing.T) {
t.Helper()
cfg = Config{}
once = sync.Once{}
}