github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/transform/staticlark/call_graph_test.go (about) 1 package staticlark 2 3 import ( 4 "testing" 5 6 "github.com/google/go-cmp/cmp" 7 "github.com/google/go-cmp/cmp/cmpopts" 8 "go.starlark.net/starlark" 9 "go.starlark.net/syntax" 10 ) 11 12 func TestCallGraph(t *testing.T) { 13 filename := "testdata/some_funcs.star" 14 15 f, err := syntax.Parse(filename, nil, 0) 16 if err != nil { 17 t.Error(err) 18 } 19 funcs, topLevel, err := collectFuncDefsTopLevelCalls(f.Stmts) 20 if err != nil { 21 t.Error(err) 22 } 23 24 // Build a graph of all calls, Detect unused functions 25 callGraph := buildCallGraph(funcs, topLevel, newSymtable(starlark.Universe)) 26 27 actual := callGraph.String() 28 expect := `print 29 use_branch 30 print 31 branch_multiple 32 print 33 branch_no_else 34 print 35 branch_nested 36 print 37 len 38 another_function 39 branch_nested 40 print 41 branch_no_else 42 print 43 top_level_func 44 use_branch 45 print 46 len 47 branch_multiple 48 print 49 branch_no_else 50 print 51 another_function 52 branch_nested 53 print 54 branch_no_else 55 print 56 branch_elses 57 print 58 branch_elses_contained 59 print 60 ` 61 if diff := cmp.Diff(expect, actual); diff != "" { 62 t.Errorf("mismatch (-want +got):\n%s", diff) 63 } 64 } 65 66 func TestUnusedFunctions(t *testing.T) { 67 filename := "testdata/more_funcs.star" 68 69 f, err := syntax.Parse(filename, nil, 0) 70 if err != nil { 71 t.Error(err) 72 } 73 funcs, topLevel, err := collectFuncDefsTopLevelCalls(f.Stmts) 74 if err != nil { 75 t.Error(err) 76 } 77 78 // Build a graph of all calls, Detect unused functions 79 callGraph := buildCallGraph(funcs, topLevel, newSymtable(starlark.Universe)) 80 81 unused := callGraph.findUnusedFuncs() 82 expectUnused := []Diagnostic{ 83 {Category: "unused", Message: "func_c"}, 84 {Category: "unused", Message: "func_e"}, 85 {Category: "unused", Message: "func_f"}, 86 } 87 if diff := cmp.Diff(expectUnused, unused, cmpopts.IgnoreFields(Diagnostic{}, "Pos")); diff != "" { 88 t.Errorf("mismatch (-want +got):\n%s", diff) 89 } 90 }