blob: ed6f168a723de4c415ac8c37901d1935e01158c2 [file] [log] [blame]
Cosmos Nicolaou7c659ac2014-06-09 22:47:04 -07001package main
2
3import (
4 "fmt"
5 "reflect"
6 "testing"
7)
8
9func TestFields(t *testing.T) {
10 cases := []struct {
11 input string
12 output []string
13 }{
14 {"", []string{}},
15 {"a", []string{"a"}},
16 {" z", []string{"z"}},
17 {" zz zz", []string{"zz", "zz"}},
18 {"ab", []string{"ab"}},
19 {"a b", []string{"a", "b"}},
20 {`a " b"`, []string{"a", " b"}},
21 {`a " b zz"`, []string{"a", " b zz"}},
22 {`a " b zz"`, []string{"a", " b zz"}},
23 {`a " b" cc`, []string{"a", " b", "cc"}},
24 {`a "z b" cc`, []string{"a", "z b", "cc"}},
25 }
26 for i, c := range cases {
27 got, err := splitQuotedFields(c.input)
28 if err != nil {
29 t.Errorf("%d: %q: unexpected error: %v", i, c.input, err)
30 }
31 if !reflect.DeepEqual(got, c.output) {
32 t.Errorf("%d: %q: got %#v, want %#v", i, c.input, got, c.output)
33 }
34 }
35 if _, err := splitQuotedFields(`a b "c`); err == nil {
36 t.Errorf("expected error for unterminated quote")
37 }
38}
39
40func TestVariables(t *testing.T) {
41 globals["foo"] = "bar"
42 cases := []struct {
43 input string
44 output []string
45 }{
46 {"a b", []string{"a", "b"}},
47 {"a $foo", []string{"a", "bar"}},
48 {"$foo a", []string{"bar", "a"}},
49 {`a "$foo "`, []string{"a", "bar "}},
50 {"a xx$foo", []string{"a", "xxbar"}},
51 {"a xx${foo}yy", []string{"a", "xxbaryy"}},
52 {`a "foo"`, []string{"a", "foo"}},
53 }
54 for i, c := range cases {
55 fields, err := splitQuotedFields(c.input)
56 if err != nil {
57 t.Errorf("%d: %q: unexpected error: %v", i, c.input, err)
58 }
59 got, err := subVariables(fields, globals)
60 if err != nil {
61 t.Errorf("%d: %q: unexpected error: %v", i, c.input, err)
62 }
63 if !reflect.DeepEqual(got, c.output) {
64 t.Errorf("%d: %q: got %#v, want %#v", i, c.input, got, c.output)
65 }
66 }
67
68 errors := []struct {
69 input string
70 err error
71 }{
72 {"$foox", fmt.Errorf("unknown variable: %q", "foox")},
73 {"${fo", fmt.Errorf("unterminated variable: %q", "{fo")},
74 }
75 for i, c := range errors {
76 _, got := subVariables([]string{c.input}, globals)
77 if got.Error() != c.err.Error() {
78 t.Errorf("%d: %q: expected error: got %q, want %q", i, c.input, got, c.err)
79 }
80 }
81}