test default prefix/indent values + encoder errors

This commit is contained in:
Adrien Marquès 2018-11-13 20:58:19 +01:00
parent 9d2219c3e4
commit 685da832df
1 changed files with 77 additions and 0 deletions

View File

@ -89,6 +89,83 @@ func TestDecodeEncode(t *testing.T) {
}
}
func TestErrors(t *testing.T) {
tests := []struct {
Receiver interface{}
Input string
Err error
}{
{new(Line), "", nil},
{nil, "", ErrInvalidReceiver},
{[]byte{}, "", ErrInvalidReceiver},
}
for i, test := range tests {
// create reader/writer
r, w := strings.NewReader(test.Input), &bytes.Buffer{}
// parse input
var receiver interface{} = new(Line)
decoder := NewDecoder(r)
if err := decoder.Decode(receiver); err != nil {
t.Errorf("[%d] unexpected error <%s>", i, err)
continue
}
// encode back to writer
receiver = test.Receiver
encoder := NewEncoder(w)
encoder.SetIndent("", "\t")
if err := encoder.Encode(receiver); err != test.Err {
t.Errorf("[%d] expected error <%s>, got <%s>", i, test.Err, err)
continue
}
}
}
func TestDefaultIndent(t *testing.T) {
tests := []struct {
Input string
SetIndent []string
Output string
}{
{"section {\nkey value;\n}\n", []string{"*prefix*", "*indent*"}, "*prefix*section {\n*prefix**indent*key\t\tvalue;\n*prefix*}\n\n"},
{"section {\nkey value;\n}\n", nil, "section {\n\tkey\t\tvalue;\n}\n\n"},
}
for i, test := range tests {
// create reader/writer
r, w := strings.NewReader(test.Input), &bytes.Buffer{}
// parse input
receiver := new(Line)
decoder := NewDecoder(r)
if err := decoder.Decode(receiver); err != nil {
t.Errorf("[%d] unexpected error <%s>", i, err)
continue
}
// encode back to writer
encoder := NewEncoder(w)
if test.SetIndent != nil && len(test.SetIndent) >= 2 {
encoder.SetIndent(test.SetIndent[0], test.SetIndent[1])
}
if err := encoder.Encode(receiver); err != nil {
t.Errorf("[%d] unexpected error <%s>", i, err)
continue
}
// check equality
if w.String() != test.Output {
t.Errorf("[%d] expected '%s', got '%s'", i, escape(test.Output), escape(w.String()))
}
}
}
func escape(raw string) string {
escaped := make([]rune, 0)