Commit b8a31c37 authored by Mike Jones's avatar Mike Jones 馃尪
Browse files

Add permitted stat types with test

parent 76709211
package util
import (
"log"
"errors"
"os"
"strings"
)
const (
influxAddrKey = "INFLUXDB_ADDRESS"
influxUserKey = "INFLUXDB_USERNAME"
influxPassKey = "INFLUXDB_PASSWORD"
influxAddrKey = "INFLUXDB_ADDRESS"
influxUserKey = "INFLUXDB_USERNAME"
influxPassKey = "INFLUXDB_PASSWORD"
permittedStatTypesKey = "PERMITTED_STAT_TYPES"
)
// Config is a container for the application's config.
......@@ -19,32 +20,41 @@ type Config struct {
Username string
Password string
}
PermittedStatTypes []string
}
// Check validates the config has all required values
func (c *Config) Check() bool {
return c.InfluxDB.Address != "" &&
c.InfluxDB.Username != "" &&
c.InfluxDB.Password != ""
c.InfluxDB.Password != "" &&
len(c.PermittedStatTypes) > 0
}
// NewConfig creates a new Config{} from environment variables
func NewConfig() *Config {
func NewConfig() (*Config, error) {
var err error
c := &Config{}
c.InfluxDB.Address = os.Getenv(influxAddrKey)
c.InfluxDB.Password = os.Getenv(influxPassKey)
c.InfluxDB.Username = os.Getenv(influxUserKey)
c.PermittedStatTypes = strings.Split(os.Getenv(permittedStatTypesKey), ",")
for i := range c.PermittedStatTypes {
c.PermittedStatTypes[i] = strings.TrimSpace(c.PermittedStatTypes[i])
}
if !c.Check() {
log.Fatalf("A required environment variable is missing. Required: %s.",
strings.Join([]string{
influxAddrKey,
influxPassKey,
influxUserKey,
}, ", "),
)
err = errors.New("Missing environment variables: " + strings.Join([]string{
influxAddrKey,
influxPassKey,
influxUserKey,
permittedStatTypesKey,
}, ", "))
}
return c
return c, err
}
package util
import (
"os"
"strings"
"testing"
)
func TestNewConfig(t *testing.T) {
t.Run("Empty config", func(t *testing.T) {
_, err := NewConfig()
if err == nil && !strings.HasPrefix("Missing env", err.Error()) {
t.Fail()
}
})
os.Setenv(influxAddrKey, "foo")
os.Setenv(influxUserKey, "foo")
os.Setenv(influxPassKey, "foo")
t.Run("Valid config, single item", func(t *testing.T) {
os.Setenv(permittedStatTypesKey, "stat")
c, err := NewConfig()
if c.PermittedStatTypes[0] != "stat" || err != nil {
t.Fail()
}
})
t.Run("Valid config, two items, no space", func(t *testing.T) {
os.Setenv(permittedStatTypesKey, "stat,stat2")
c, err := NewConfig()
if len(c.PermittedStatTypes) != 2 || c.PermittedStatTypes[1] != "stat2" || err != nil {
t.Fail()
}
})
t.Run("Valid config, two items, space", func(t *testing.T) {
os.Setenv(permittedStatTypesKey, "statx, staty")
c, err := NewConfig()
if err != nil {
t.Fail()
}
if c.PermittedStatTypes[0] != "statx" || c.PermittedStatTypes[1] != "staty" {
t.Logf("Stat types incorrect: '%s', '%s'", c.PermittedStatTypes[0], c.PermittedStatTypes[1])
t.Fail()
}
})
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment