136 lines
2.1 KiB
Go
136 lines
2.1 KiB
Go
package conf
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"reflect"
|
|
"slices"
|
|
"testing"
|
|
)
|
|
|
|
func TestRead(t *testing.T) {
|
|
tc := []struct {
|
|
name string
|
|
in []byte
|
|
res *Conf
|
|
err error
|
|
}{
|
|
{
|
|
name: "empty",
|
|
in: []byte{},
|
|
res: &Conf{
|
|
values: nil, // no reads, so the slice has not been initialized
|
|
},
|
|
err: nil, // if the reader just returned io.EOF, which isn't an error for us
|
|
},
|
|
{
|
|
name: "single key with spaces",
|
|
in: []byte("key = value"),
|
|
res: &Conf{
|
|
values: []*kv{
|
|
{
|
|
k: "key",
|
|
v: Value("value"),
|
|
},
|
|
},
|
|
},
|
|
err: nil,
|
|
},
|
|
{
|
|
name: "single key no spaces",
|
|
in: []byte("key=value"),
|
|
res: &Conf{
|
|
values: []*kv{
|
|
{
|
|
k: "key",
|
|
v: Value("value"),
|
|
},
|
|
},
|
|
},
|
|
err: nil,
|
|
},
|
|
{
|
|
name: "single key with newline",
|
|
in: []byte("key=value\n"),
|
|
res: &Conf{
|
|
values: []*kv{
|
|
{
|
|
k: "key",
|
|
v: Value("value"),
|
|
},
|
|
},
|
|
},
|
|
err: nil,
|
|
},
|
|
{
|
|
name: "single key with comment and newline",
|
|
in: []byte("key =value # this is a comment\n"),
|
|
res: &Conf{
|
|
values: []*kv{
|
|
{
|
|
k: "key",
|
|
v: Value("value"),
|
|
},
|
|
},
|
|
},
|
|
err: nil,
|
|
},
|
|
}
|
|
|
|
for _, c := range tc {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
r := bytes.NewReader(c.in)
|
|
|
|
conf, err := Read(r)
|
|
if !errors.Is(err, c.err) {
|
|
t.Fatalf("want error: %v have: %v", c.err, err)
|
|
}
|
|
|
|
if !reflect.DeepEqual(c.res, conf) {
|
|
t.Fatalf("want: %+v, have: %+v", c.res, conf)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestOpen(t *testing.T) {
|
|
conf, err := Open("./testdata/test.conf")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
const (
|
|
key = "key"
|
|
value = "value"
|
|
)
|
|
for _, n := range []string{"1", "2", "3", "4"} {
|
|
v := conf.Get(key + n)
|
|
if v.String() != value+n {
|
|
t.Errorf("want: %s got: %s", value+n, v)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestKeys(t *testing.T) {
|
|
c := Conf{
|
|
values: []*kv{
|
|
{
|
|
k: "1",
|
|
v: Value(""),
|
|
},
|
|
{
|
|
k: "2",
|
|
v: Value(""),
|
|
},
|
|
{
|
|
k: "3",
|
|
v: Value(""),
|
|
},
|
|
},
|
|
}
|
|
|
|
if !slices.Equal([]string{"1", "2", "3"}, c.Keys()) {
|
|
t.Fatal("Keys method returns incorrect values")
|
|
}
|
|
}
|