github.com/maps90/godog@v0.7.5-0.20170923143419-0093943021d4/ast_test.go (about)

     1  package godog
     2  
     3  import (
     4  	"go/parser"
     5  	"go/token"
     6  	"testing"
     7  )
     8  
     9  var astContextSrc = `package main
    10  
    11  import (
    12  	"github.com/DATA-DOG/godog"
    13  )
    14  
    15  func MyContext(s *godog.Suite) {
    16  }`
    17  
    18  var astTwoContextSrc = `package lib
    19  
    20  import (
    21  	"github.com/DATA-DOG/godog"
    22  )
    23  
    24  func ApiContext(s *godog.Suite) {
    25  }
    26  
    27  func DBContext(s *godog.Suite) {
    28  }`
    29  
    30  func astContextParse(src string, t *testing.T) []string {
    31  	fset := token.NewFileSet()
    32  	f, err := parser.ParseFile(fset, "", []byte(src), 0)
    33  	if err != nil {
    34  		t.Fatalf("unexpected error while parsing ast: %v", err)
    35  	}
    36  
    37  	return astContexts(f)
    38  }
    39  
    40  func TestShouldGetSingleContextFromSource(t *testing.T) {
    41  	actual := astContextParse(astContextSrc, t)
    42  	expect := []string{"MyContext"}
    43  
    44  	if len(actual) != len(expect) {
    45  		t.Fatalf("number of found contexts do not match, expected %d, but got %d", len(expect), len(actual))
    46  	}
    47  
    48  	for i, c := range expect {
    49  		if c != actual[i] {
    50  			t.Fatalf("expected context '%s' at pos %d, but got: '%s'", c, i, actual[i])
    51  		}
    52  	}
    53  }
    54  
    55  func TestShouldGetTwoContextsFromSource(t *testing.T) {
    56  	actual := astContextParse(astTwoContextSrc, t)
    57  	expect := []string{"ApiContext", "DBContext"}
    58  
    59  	if len(actual) != len(expect) {
    60  		t.Fatalf("number of found contexts do not match, expected %d, but got %d", len(expect), len(actual))
    61  	}
    62  
    63  	for i, c := range expect {
    64  		if c != actual[i] {
    65  			t.Fatalf("expected context '%s' at pos %d, but got: '%s'", c, i, actual[i])
    66  		}
    67  	}
    68  }
    69  
    70  func TestShouldNotFindAnyContextsInEmptyFile(t *testing.T) {
    71  	actual := astContextParse(`package main`, t)
    72  
    73  	if len(actual) != 0 {
    74  		t.Fatalf("expected no contexts to be found, but there was some: %v", actual)
    75  	}
    76  }