golang-app/config/Config_test.go

106 lines
2.8 KiB
Go

package config
import (
"github.com/stretchr/testify/assert"
"os"
"strconv"
"sync"
"testing"
)
func TestGetConfig(t *testing.T) {
telegramToken := ":: telegram telegram token ::"
telegramOwner := 1234567890
pathDictionaries := `docs/dictionaries`
initTelegramBotEnvironment(telegramToken, telegramOwner, pathDictionaries)
defer cleanTelegramBotEnvironment()
var config Config
assert.NotPanics(t, func() { 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, pathDictionaries, config.Paths.Docs)
}
func TestGetConfigTwice(t *testing.T) {
initTelegramBotEnvironment(":: telegram telegram token ::", 1234567890, `docs/dictionaries`)
defer cleanTelegramBotEnvironment()
config1 := GetConfig()
config2 := GetConfig()
assert.NotEmpty(t, config1)
assert.NotEmpty(t, config2)
assert.Equal(t, config1, config2)
assert.NotSame(t, config1, config2)
}
func TestGetConfigAndSingletonIsImmutable(t *testing.T) {
telegramToken := ":: telegram telegram token ::"
telegramOwner := 1234567890
pathDictionaries := `docs/dictionaries`
initTelegramBotEnvironment(telegramToken, telegramOwner, pathDictionaries)
defer cleanTelegramBotEnvironment()
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) {
telegramToken := ":: telegram telegram token ::"
telegramOwner := 1234567890
_ = os.Setenv("TOKEN", telegramToken)
_ = os.Setenv("OWNER", strconv.Itoa(telegramOwner))
defer cleanTelegramBotEnvironment()
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) {
cleanTelegramBotEnvironment()
assert.Panics(t, func() { GetConfig() })
}
func initTelegramBotEnvironment(telegramToken string, telegramOwner int, pathDictionaries string) {
resetConfig()
_ = os.Setenv("TOKEN", telegramToken)
_ = os.Setenv("OWNER", strconv.Itoa(telegramOwner))
_ = os.Setenv("DOCS_PATH", pathDictionaries)
}
func cleanTelegramBotEnvironment() {
_ = os.Unsetenv("TOKEN")
_ = os.Unsetenv("OWNER")
_ = os.Unsetenv("DOCS_PATH")
resetConfig()
}
func resetConfig() {
cfg = Config{}
once = sync.Once{}
}