Debian Codegraph @

cmd/callgraph/main_test.go

raw symbols SCIP
1 // Copyright 2014 The Go 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 // No testdata on Android.
6
7 //go:build !android && go1.11
8
9 package main
10
11 import (
12 "bytes"
13 "fmt"
14 "log"
15 "os"
16 "path/filepath"
17 "strings"
18 "testing"
19
20 "golang.org/x/tools/internal/testenv"
21 )
22
23 func init() {
24 // This test currently requires GOPATH mode.
25 // Explicitly disabling module mode should suffix, but
26 // we'll also turn off GOPROXY just for good measure.
27 if err := os.Setenv("GO111MODULE", "off"); err != nil {
28 log.Fatal(err)
29 }
30 if err := os.Setenv("GOPROXY", "off"); err != nil {
31 log.Fatal(err)
32 }
33 }
34
35 func TestCallgraph(t *testing.T) {
36 testenv.NeedsTool(t, "go")
37
38 gopath, err := filepath.Abs("testdata")
39 if err != nil {
40 t.Fatal(err)
41 }
42
43 for _, test := range []struct {
44 algo string
45 tests bool
46 want []string
47 }{
48 {"rta", false, []string{
49 // rta imprecisely shows cross product of {main,main2} x {C,D}
50 `pkg.main --> (pkg.C).f`,
51 `pkg.main --> (pkg.D).f`,
52 `pkg.main --> pkg.main2`,
53 `pkg.main2 --> (pkg.C).f`,
54 `pkg.main2 --> (pkg.D).f`,
55 }},
56 {"vta", false, []string{
57 // vta distinguishes main->C, main2->D.
58 "pkg.main --> (pkg.C).f",
59 "pkg.main --> pkg.main2",
60 "pkg.main2 --> (pkg.D).f",
61 }},
62 // tests: both the package's main and the test's main are called.
63 // The callgraph includes all the guts of the "testing" package.
64 {"rta", true, []string{
65 `pkg.test.main --> testing.MainStart`,
66 `testing.runExample --> pkg.Example`,
67 `pkg.Example --> (pkg.C).f`,
68 `pkg.main --> (pkg.C).f`,
69 }},
70 {"vta", true, []string{
71 `pkg.test.main --> testing.MainStart`,
72 `testing.runExample --> pkg.Example`,
73 `pkg.Example --> (pkg.C).f`,
74 `pkg.main --> (pkg.C).f`,
75 }},
76 } {
77 const format = "{{.Caller}} --> {{.Callee}}"
78 stdout = new(bytes.Buffer)
79 if err := doCallgraph("testdata/src", gopath, test.algo, format, test.tests, []string{"pkg"}); err != nil {
80 t.Error(err)
81 continue
82 }
83
84 edges := make(map[string]bool)
85 for _, line := range strings.Split(fmt.Sprint(stdout), "\n") {
86 edges[line] = true
87 }
88 ok := true
89 for _, edge := range test.want {
90 if !edges[edge] {
91 ok = false
92 t.Errorf("callgraph(%q, %t): missing edge: %s",
93 test.algo, test.tests, edge)
94 }
95 }
96 if !ok {
97 t.Log("got:\n", stdout)
98 }
99 }
100 }