package parser import ( "fmt" "path/filepath" "reflect" "runtime" "testing" "github.com/fatih/hcl/ast" "github.com/fatih/hcl/token" ) func TestParseType(t *testing.T) { src := `foo = true` p := New([]byte(src)) p.enableTrace = true n, err := p.Parse() if err != nil { t.Fatal(err) } fmt.Printf("n = %+v\n", n) ast.Walk(n, func(node ast.Node) bool { fmt.Printf("node = %+v\n", node) return true }) } func TestObjectKey(t *testing.T) { keys := []struct { exp []token.TokenType src string }{ {[]token.TokenType{token.IDENT}, `foo {}`}, {[]token.TokenType{token.IDENT}, `foo = {}`}, {[]token.TokenType{token.IDENT}, `foo = bar`}, {[]token.TokenType{token.IDENT}, `foo = 123`}, {[]token.TokenType{token.IDENT}, `foo = "${var.bar}`}, {[]token.TokenType{token.STRING}, `"foo" {}`}, {[]token.TokenType{token.STRING}, `"foo" = {}`}, {[]token.TokenType{token.STRING}, `"foo" = "${var.bar}`}, {[]token.TokenType{token.IDENT, token.IDENT}, `foo bar {}`}, {[]token.TokenType{token.IDENT, token.STRING}, `foo "bar" {}`}, {[]token.TokenType{token.STRING, token.IDENT}, `"foo" bar {}`}, {[]token.TokenType{token.IDENT, token.IDENT, token.IDENT}, `foo bar baz {}`}, } for _, k := range keys { p := New([]byte(k.src)) keys, err := p.parseObjectKey() if err != nil { t.Fatal(err) } tokens := []token.TokenType{} for _, o := range keys { tokens = append(tokens, o.Token.Type) } equals(t, k.exp, tokens) } errKeys := []struct { src string }{ {`foo 12 {}`}, {`foo bar = {}`}, {`foo []`}, {`12 {}`}, } for _, k := range errKeys { p := New([]byte(k.src)) _, err := p.parseObjectKey() if err == nil { t.Errorf("case '%s' should give an error", k.src) } } } // equals fails the test if exp is not equal to act. func equals(tb testing.TB, exp, act interface{}) { if !reflect.DeepEqual(exp, act) { _, file, line, _ := runtime.Caller(1) fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act) tb.FailNow() } }