github.com/neugram/ng@v0.0.0-20180309130942-d472ff93d872/syntax/walk_test.go (about)

     1  // Copyright 2017 The Neugram Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package syntax_test
     6  
     7  import (
     8  	"io/ioutil"
     9  	"path/filepath"
    10  	"strings"
    11  	"testing"
    12  
    13  	"neugram.io/ng/parser"
    14  	"neugram.io/ng/syntax"
    15  )
    16  
    17  func TestWalk(t *testing.T) {
    18  	files, err := filepath.Glob("../eval/testdata/*.ng")
    19  	if err != nil {
    20  		t.Fatal(err)
    21  	}
    22  	if len(files) == 0 {
    23  		t.Fatal("cannot find testdata")
    24  	}
    25  
    26  	for _, file := range files {
    27  		file := file
    28  		test := file[len("testdata") : len(file)-3]
    29  		t.Run(test, func(t *testing.T) {
    30  			source, err := ioutil.ReadFile(file)
    31  			if err != nil {
    32  				t.Fatal(err)
    33  			}
    34  			p := parser.New(file)
    35  			f, err := p.Parse(source)
    36  			if err != nil {
    37  				if strings.HasSuffix(test, "_error") {
    38  					return // probably a parser test
    39  				}
    40  				t.Fatal(err)
    41  			}
    42  
    43  			preCount, postCount := 0, 0
    44  			preFn := func(c *syntax.Cursor) bool {
    45  				preCount++
    46  				if c.Name == "" {
    47  					t.Errorf("cursor has no name on %v", c.Node)
    48  				}
    49  				if c.Parent == nil {
    50  					t.Errorf("cursor has no parent on %v", c.Node)
    51  				}
    52  				return true
    53  			}
    54  			postFn := func(c *syntax.Cursor) bool {
    55  				postCount++
    56  				return true
    57  			}
    58  			if res := syntax.Walk(f, preFn, postFn); res != f {
    59  				t.Errorf("Walk returned %v, not original %v", res, f)
    60  			}
    61  			if preCount != postCount {
    62  				t.Errorf("Walk has imbalanced pre/post counts: %d/%d", preCount, postCount)
    63  			}
    64  			if preCount == 0 {
    65  				t.Errorf("Walk didn't visit anything")
    66  			}
    67  		})
    68  	}
    69  }