add test for config.randomString func

This commit is contained in:
Danny 2018-05-15 13:54:36 +02:00
parent c30e5b3120
commit 1bd093b8a4
2 changed files with 88 additions and 0 deletions

54
pkg/config/config.go Normal file
View File

@ -0,0 +1,54 @@
package config
import (
"math/rand"
"github.com/joho/godotenv"
"github.com/kelseyhightower/envconfig"
log "github.com/sirupsen/logrus"
"github.com/usefathom/fathom/pkg/datastore/sqlstore"
)
type Config struct {
Database *sqlstore.Config
Secret string
}
func Parse(file string) *Config {
var cfg Config
var err error
if file != "" {
err = godotenv.Load(file)
if err != nil && file != ".env" {
log.Fatalf("error parsing config file: %s", err)
}
}
err = envconfig.Process("Fathom", &cfg)
if err != nil {
log.Fatalf("error parsing config from environment values: %s", err)
}
// alias sqlite to sqlite3
if cfg.Database.Driver == "sqlite" {
cfg.Database.Driver = "sqlite3"
}
// if secret key is empty, use a randomly generated one
if cfg.Secret == "" {
cfg.Secret = randomString(40)
}
return &cfg
}
func randomString(len int) string {
bytes := make([]byte, len)
for i := 0; i < len; i++ {
bytes[i] = byte(65 + rand.Intn(25)) //A=65 and Z = 65+25
}
return string(bytes)
}

34
pkg/config/config_test.go Normal file
View File

@ -0,0 +1,34 @@
package config
import (
"os"
"testing"
)
func TestParse(t *testing.T) {
// empty config, should not fatal
cfg := Parse("")
if cfg.Secret == "" {
t.Errorf("expected secret, got empty string")
}
os.Setenv("FATHOM_DATABASE_DRIVER", "sqlite")
cfg = Parse("")
if cfg.Database.Driver != "sqlite3" {
t.Errorf("expected %#v, got %#v", "sqlite3", cfg.Database.Driver)
}
}
func TestRandomString(t *testing.T) {
r1 := randomString(10)
r2 := randomString(10)
if r1 == r2 {
t.Errorf("expected two different strings, got %#v", r1)
}
if l := len(r1); l != 10 {
t.Errorf("expected string of length %d, got string of length %d", 10, l)
}
}