gitee.com/wgliang/goreporter@v0.0.0-20180902115603-df1b20f7c5d0/linters/simplecode/lint/lint_test.go (about) 1 // Copyright (c) 2013 The Go Authors. All rights reserved. 2 // 3 // Use of this source code is governed by a BSD-style 4 // license that can be found in the LICENSE file or at 5 // https://developers.google.com/open-source/licenses/bsd. 6 7 package lint 8 9 import ( 10 "go/ast" 11 "go/parser" 12 "go/token" 13 "go/types" 14 "testing" 15 ) 16 17 func TestLine(t *testing.T) { 18 tests := []struct { 19 src string 20 offset int 21 want string 22 }{ 23 {"single line file", 5, "single line file"}, 24 {"single line file with newline\n", 5, "single line file with newline\n"}, 25 {"first\nsecond\nthird\n", 2, "first\n"}, 26 {"first\nsecond\nthird\n", 9, "second\n"}, 27 {"first\nsecond\nthird\n", 14, "third\n"}, 28 {"first\nsecond\nthird with no newline", 16, "third with no newline"}, 29 {"first byte\n", 0, "first byte\n"}, 30 } 31 for _, test := range tests { 32 got := SrcLine([]byte(test.src), token.Position{Offset: test.offset}) 33 if got != test.want { 34 t.Errorf("srcLine(%q, offset=%d) = %q, want %q", test.src, test.offset, got, test.want) 35 } 36 } 37 } 38 39 func TestExportedType(t *testing.T) { 40 tests := []struct { 41 typString string 42 exp bool 43 }{ 44 {"int", true}, 45 {"string", false}, // references the shadowed builtin "string" 46 {"T", true}, 47 {"t", false}, 48 {"*T", true}, 49 {"*t", false}, 50 {"map[int]complex128", true}, 51 } 52 for _, test := range tests { 53 src := `package foo; type T int; type t int; type string struct{}` 54 fset := token.NewFileSet() 55 file, err := parser.ParseFile(fset, "foo.go", src, 0) 56 if err != nil { 57 t.Fatalf("Parsing %q: %v", src, err) 58 } 59 // use the package name as package path 60 config := &types.Config{} 61 pkg, err := config.Check(file.Name.Name, fset, []*ast.File{file}, nil) 62 if err != nil { 63 t.Fatalf("Type checking %q: %v", src, err) 64 } 65 tv, err := types.Eval(fset, pkg, token.NoPos, test.typString) 66 if err != nil { 67 t.Errorf("types.Eval(%q): %v", test.typString, err) 68 continue 69 } 70 if got := ExportedType(tv.Type); got != test.exp { 71 t.Errorf("exportedType(%v) = %t, want %t", tv.Type, got, test.exp) 72 } 73 } 74 }