From 685da832df05065e85e27344c841eedbe59cb549 Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Tue, 13 Nov 2018 20:58:19 +0100 Subject: [PATCH] test default prefix/indent values + encoder errors --- internal/cnf/parser/nginx/encoder_test.go | 77 +++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/internal/cnf/parser/nginx/encoder_test.go b/internal/cnf/parser/nginx/encoder_test.go index c2a551d..3758c1d 100644 --- a/internal/cnf/parser/nginx/encoder_test.go +++ b/internal/cnf/parser/nginx/encoder_test.go @@ -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)