.gitignore added
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / honnef.co / go / tools@v0.1.1 / go / callgraph / static / static_test.go
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 //lint:file-ignore SA1019 go/callgraph's test suite is built around the deprecated go/loader. We'll leave fixing that to upstream.
6
7 package static_test
8
9 import (
10         "fmt"
11         "go/parser"
12         "reflect"
13         "sort"
14         "testing"
15
16         "honnef.co/go/tools/go/callgraph"
17         "honnef.co/go/tools/go/callgraph/static"
18         "honnef.co/go/tools/go/ir/irutil"
19
20         "golang.org/x/tools/go/loader"
21 )
22
23 const input = `package P
24
25 type C int
26 func (C) f()
27
28 type I interface{f()}
29
30 func f() {
31         p := func() {}
32         g()
33         p() // IR constant propagation => static
34
35         if unknown {
36                 p = h
37         }
38         p() // dynamic
39
40         C(0).f()
41 }
42
43 func g() {
44         var i I = C(0)
45         i.f()
46 }
47
48 func h()
49
50 var unknown bool
51 `
52
53 func TestStatic(t *testing.T) {
54         conf := loader.Config{ParserMode: parser.ParseComments}
55         f, err := conf.ParseFile("P.go", input)
56         if err != nil {
57                 t.Fatal(err)
58         }
59
60         conf.CreateFromFiles("P", f)
61         iprog, err := conf.Load()
62         if err != nil {
63                 t.Fatal(err)
64         }
65
66         P := iprog.Created[0].Pkg
67
68         prog := irutil.CreateProgram(iprog, 0)
69         prog.Build()
70
71         cg := static.CallGraph(prog)
72
73         var edges []string
74         callgraph.GraphVisitEdges(cg, func(e *callgraph.Edge) error {
75                 edges = append(edges, fmt.Sprintf("%s -> %s",
76                         e.Caller.Func.RelString(P),
77                         e.Callee.Func.RelString(P)))
78                 return nil
79         })
80         sort.Strings(edges)
81
82         want := []string{
83                 "(*C).f -> (C).f",
84                 "f -> (C).f",
85                 "f -> f$1",
86                 "f -> g",
87         }
88         if !reflect.DeepEqual(edges, want) {
89                 t.Errorf("Got edges %v, want %v", edges, want)
90         }
91 }