github.com/masahide/goansible@v0.0.0-20160116054156-01eac649e9f2/lisp/tokens_test.go (about)

     1  package lisp
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  )
     7  
     8  func equalSlices(a, b Tokens) bool {
     9  	if len(a) != len(b) {
    10  		return false
    11  	}
    12  	for i, v := range a {
    13  		if v.val != b[i].val || v.typ != b[i].typ {
    14  			return false
    15  		}
    16  	}
    17  	return true
    18  }
    19  
    20  func TestNewTokens(t *testing.T) {
    21  	var tests = []struct {
    22  		in  string
    23  		out Tokens
    24  	}{
    25  		{"(define a 42)", Tokens{{openToken, "("}, {symbolToken, "define"}, {symbolToken, "a"}, {numberToken, "42"}, {closeToken, ")"}}},
    26  		{"\t(quote\n\t\t(a b c))  ", Tokens{{openToken, "("}, {symbolToken, "quote"}, {openToken, "("}, {symbolToken, "a"}, {symbolToken, "b"}, {symbolToken, "c"}, {closeToken, ")"}, {closeToken, ")"}}},
    27  		{"hello ; dude\n\tworld", Tokens{{symbolToken, "hello"}, {symbolToken, "world"}}},
    28  		{"test \"a string\"", Tokens{{symbolToken, "test"}, {stringToken, "\"a string\""}}},
    29  		{"\"only string\"", Tokens{{stringToken, "\"only string\""}}},
    30  		{"\"string\\nwith\\\"escape\\tcharacters\"", Tokens{{stringToken, "\"string\\nwith\\\"escape\\tcharacters\""}}},
    31  		{"\"hej\\\"hello\"", Tokens{{stringToken, "\"hej\\\"hello\""}}},
    32  	}
    33  
    34  	for _, test := range tests {
    35  		x := NewTokens(test.in)
    36  		if !equalSlices(x, test.out) {
    37  			t.Errorf("NewTokens \"%v\" gives \"%v\", expected \"%v\"", test.in, x, test.out)
    38  		}
    39  	}
    40  }
    41  
    42  func TestParse(t *testing.T) {
    43  	var tests = []struct {
    44  		in  string
    45  		out string
    46  	}{
    47  		{"42", "(42)"},
    48  		{"(+ (+ 1 2) 3)", "((+ (+ 1 2) 3))"},
    49  	}
    50  	for _, test := range tests {
    51  		if parsed, err := NewTokens(test.in).Parse(); err != nil {
    52  			t.Errorf("%v\n", err)
    53  		} else {
    54  			result := fmt.Sprintf("%v", parsed.String())
    55  			if result != test.out {
    56  				t.Errorf("Parse \"%v\" gives \"%v\", expected \"%v\"", test.in, result, test.out)
    57  			}
    58  		}
    59  	}
    60  }
    61  
    62  func TestParseFailures(t *testing.T) {
    63  	var tests = []string{
    64  		"(42",
    65  	}
    66  	for _, in := range tests {
    67  		if x, err := NewTokens(in).Parse(); err == nil {
    68  			t.Errorf("Parse('%v') = '%v', want error", in, x)
    69  		}
    70  	}
    71  }