goenzyme_test.go raw

   1  package enzyme
   2  
   3  import (
   4  	"strings"
   5  	"testing"
   6  )
   7  
   8  func TestGoDigestSimple(t *testing.T) {
   9  	src := `package main
  10  
  11  import "fmt"
  12  
  13  type Foo struct {
  14  	Name string
  15  }
  16  
  17  func (f Foo) Hello() string {
  18  	return fmt.Sprintf("hello %s", f.Name)
  19  }
  20  
  21  func main() {
  22  	f := Foo{Name: "world"}
  23  	fmt.Println(f.Hello())
  24  }
  25  `
  26  	ge := GoSource{}
  27  	ch := ge.Digest(strings.NewReader(src))
  28  
  29  	types := make(map[string]int)
  30  	var elems []string
  31  	for e := range ch {
  32  		types[e.Type()]++
  33  		if e.Value() != nil && e.Value() != "" {
  34  			elems = append(elems, e.Type()+":"+e.Value().(string))
  35  		}
  36  	}
  37  
  38  	t.Logf("element types: %v", types)
  39  	t.Logf("named elements: %v", elems)
  40  
  41  	if types["package"] != 1 {
  42  		t.Error("expected exactly 1 package element")
  43  	}
  44  	if types["func"] < 1 {
  45  		t.Error("expected at least 1 func element")
  46  	}
  47  	if types["method"] < 1 {
  48  		t.Error("expected at least 1 method element")
  49  	}
  50  	if types["type"] < 1 {
  51  		t.Error("expected at least 1 type element")
  52  	}
  53  	if types["import"] < 1 {
  54  		t.Error("expected at least 1 import element")
  55  	}
  56  }
  57  
  58  func TestGoCanDigest(t *testing.T) {
  59  	goCode := []byte("package main\n\nfunc main() {}\n")
  60  	notGo := []byte("hello world this is not go")
  61  
  62  	e := GoSource{}
  63  	if !e.CanDigest(goCode) {
  64  		t.Error("should detect Go source")
  65  	}
  66  	if e.CanDigest(notGo) {
  67  		t.Error("should reject non-Go text")
  68  	}
  69  }
  70