Add config and config tests.

This commit is contained in:
Cody Soyland 2013-11-26 11:13:26 -06:00
parent 2562bd6cf9
commit 43554244c8
3 changed files with 68 additions and 13 deletions

View file

@ -1,20 +1,48 @@
package config
import (
"flag"
"log"
"io/ioutil"
"launchpad.net/goyaml"
"os"
"sync"
)
var config map[string]interface{}
var lock sync.RWMutex
var loaded bool
func ensureLoaded() {
if !loaded {
loadConfig()
}
}
func loadConfig() {
config = make(map[string]interface{})
config_file := os.Getenv("PILOSA_CONFIG")
if config_file == "" {
config_file = "pilosa.yaml"
}
data, err := ioutil.ReadFile(config_file)
if err != nil {
log.Fatal("Problem with config file. ", err)
}
goyaml.Unmarshal(data, &config)
}
func GetSafe(key string) (interface{}, bool) {
lock.RLock()
ensureLoaded()
defer lock.RUnlock()
value, ok := config[key]
return value, ok
}
func Get(key string) interface{} {
lock.RLock()
ensureLoaded()
defer lock.RUnlock()
return config[key]
}
@ -39,15 +67,3 @@ func GetString(key string) string {
}
return ""
}
func init() {
log.Println("Start config")
config = make(map[string]interface{})
config_file := flag.String("config", "pilosa.yaml", "Path to config file.")
flag.Parse()
data, err := ioutil.ReadFile(*config_file)
if err != nil {
log.Fatal("Problem with config file. ", err)
}
goyaml.Unmarshal(data, &config)
}

36
config/config_test.go Normal file
View file

@ -0,0 +1,36 @@
package config
import (
"testing"
"os"
. "github.com/smartystreets/goconvey/convey"
)
func TestConfig(t *testing.T) {
err := os.Setenv("PILOSA_CONFIG", "test.yaml")
if err != nil {
t.Fatal("Error setting PILOSA_CONFIG")
}
Convey("config.Get()", t, func() {
So(Get("port_tcp").(int), ShouldEqual, 12000)
So(Get("port_http").(int), ShouldEqual, 15000)
So(Get("temp").(string), ShouldEqual, "/tmp")
So(Get("notfound"), ShouldEqual, nil)
})
Convey("config.GetSafe()", t, func() {
val, ok := GetSafe("port_tcp")
So(ok, ShouldEqual, true)
So(val.(int), ShouldEqual, 12000)
val, ok = GetSafe("derp")
So(ok, ShouldEqual, false)
So(val, ShouldEqual, nil)
})
Convey("config.GetInt()", t, func() {
So(GetInt("port_tcp"), ShouldEqual, 12000)
So(GetInt("port_http"), ShouldEqual, 15000)
So(GetInt("notfound"), ShouldEqual, 0)
})
Convey("config.GetString()", t, func() {
So(GetString("temp"), ShouldEqual, "/tmp")
})
}

3
config/test.yaml Normal file
View file

@ -0,0 +1,3 @@
port_tcp: 12000
port_http: 15000
temp: /tmp