Debian Codegraph @

tools/celtest/test_coverage_reporter.go

raw symbols SCIP
1 // Copyright 2025 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package celtest provides functions for testing CEL policies and expressions.
16 package celtest
17
18 import (
19 "fmt"
20 "strings"
21 "testing"
22
23 "github.com/google/cel-go/common/ast"
24 "github.com/google/cel-go/common/types"
25 "github.com/google/cel-go/parser"
26 )
27
28 // reportCoverage reports the coverage information for the provided programs.
29 // - For the node coverage, the coverage is reported as a percentage of the number of nodes which
30 // were evaluated during the test execution and hence are present in the program Coverage report.
31 // - For the branch coverage, every node which has a boolean return type is considered as a branch.
32 // The number of branches which were evaluated during the test execution and hence are present in
33 // the program Coverage report are reported as the branch coverage percentage.
34 func reportCoverage(t *testing.T, programs []Program) {
35 t.Helper()
36 for _, p := range programs {
37 a := p.Ast.NativeRep()
38 exprString, err := parser.Unparse(a.Expr(), a.SourceInfo(), parser.WrapOnColumn(70))
39 if err != nil {
40 t.Logf("Error converting AST to string for a program: %v", err)
41 continue
42 }
43 rootNavigableExpr := ast.NavigateAST(p.Ast.NativeRep())
44 // Initialize coverage metrics
45 cr := &coverageReport{
46 nodes: 0,
47 coveredNodes: 0,
48 branches: 0,
49 coveredBooleanOutcomes: 0,
50 unencounteredNodes: []string{},
51 unencounteredBranches: []string{},
52 }
53 traverseAndCalculateCoverage(t, rootNavigableExpr, p, true, "", cr)
54 printCoverageReport(t, exprString, cr)
55 }
56 }
57
58 type coverageReport struct {
59 nodes int64
60 coveredNodes int64
61 branches int64
62 coveredBooleanOutcomes int64
63 unencounteredNodes []string
64 unencounteredBranches []string
65 }
66
67 func traverseAndCalculateCoverage(t *testing.T, expr ast.NavigableExpr, p Program, logUnencountered bool,
68 preceedingTabs string, cr *coverageReport) {
69 t.Helper()
70 if expr == nil || len(p.CoverageStats) == 0 {
71 return
72 }
73 nodeID := expr.ID()
74 exprText, err := parser.Unparse(expr, p.Ast.NativeRep().SourceInfo(), parser.WrapOnColumn(70))
75 if err != nil {
76 t.Logf("Error converting AST to string for an expression: %v", err)
77 return
78 }
79 cr.nodes++
80 // Check for nodes which need to be logged for missing coverage:
81 // * node should be of boolean type
82 // * node should not a literal
83 // * cel.@block type function nodes are bypassed as they are just the container for
84 // the underlying expressions and the node itself does not offer any significant coverage information
85 interestingBoolNode := expr.Type() == types.BoolType && expr.AsLiteral() == nil && expr.AsCall().FunctionName() != "cel.@block"
86 // Check for node coverage
87 if _, isCovered := p.CoverageStats[nodeID]; isCovered {
88 cr.coveredNodes++
89 } else if logUnencountered {
90 if interestingBoolNode {
91 cr.unencounteredNodes = append(cr.unencounteredNodes,
92 fmt.Sprintf("\nExpression ID %d ('%s')", nodeID, exprText))
93 }
94 logUnencountered = false
95 }
96 // Check for Branch Coverage if the node is a boolean type
97 if interestingBoolNode {
98 cr.branches += 2
99 if info, found := p.CoverageStats[nodeID]; found {
100 var trueFound, falseFound bool
101 if _, trueFound = info[types.True]; trueFound {
102 cr.coveredBooleanOutcomes++
103 }
104 if _, falseFound = info[types.False]; falseFound {
105 cr.coveredBooleanOutcomes++
106 }
107 if logUnencountered && !(trueFound && falseFound) {
108 if falseFound {
109 cr.unencounteredBranches = append(cr.unencounteredBranches,
110 "\n"+preceedingTabs+fmt.Sprintf("Expression ID %d ('%s'): lacks 'true' coverage", nodeID, exprText))
111 preceedingTabs = preceedingTabs + "\t\t"
112 } else if trueFound {
113 cr.unencounteredBranches = append(cr.unencounteredBranches,
114 "\n"+preceedingTabs+fmt.Sprintf("Expression ID %d ('%s'): lacks 'false' coverage", nodeID, exprText))
115 preceedingTabs = preceedingTabs + "\t\t"
116 } else {
117 cr.unencounteredBranches = append(cr.unencounteredBranches,
118 "\n"+preceedingTabs+fmt.Sprintf("Expression ID %d ('%s'): No coverage", nodeID, exprText))
119 preceedingTabs = preceedingTabs + "\t\t"
120 }
121 }
122 }
123 }
124 for _, child := range expr.Children() {
125 traverseAndCalculateCoverage(t, child.(ast.NavigableExpr), p, logUnencountered, preceedingTabs, cr)
126 }
127 }
128
129 func printCoverageReport(t *testing.T, exprString string, cr *coverageReport) {
130 t.Helper()
131 t.Logf("--- Start Coverage Report ---\nExpression: %s", exprString)
132 if cr.nodes == 0 {
133 t.Logf("No coverage stats found")
134 return
135 }
136 // Log Node Coverage results
137 nodeCoverage := float64(cr.coveredNodes) / float64(cr.nodes) * 100.0
138 t.Logf("AST Node Coverage: %.2f%% (%d out of %d nodes covered)", nodeCoverage, cr.coveredNodes, cr.nodes)
139 if len(cr.unencounteredNodes) > 0 {
140 t.Logf("Interesting Unencountered Nodes:\n%s", strings.Join(cr.unencounteredNodes, "\n"))
141 }
142 // Log Branch Coverage results
143 branchCoverage := 0.0
144 if cr.branches > 0 {
145 branchCoverage = float64(cr.coveredBooleanOutcomes) / float64(cr.branches) * 100.0
146 }
147 t.Logf("AST Branch Coverage: %.2f%% (%d out of %d branch outcomes covered)", branchCoverage,
148 cr.coveredBooleanOutcomes, cr.branches)
149 if len(cr.unencounteredBranches) > 0 {
150 t.Logf("Interesting Unencountered Branch Paths:\n%s", strings.Join(cr.unencounteredBranches, "\n"))
151 }
152 t.Logf("--- End Coverage Report ---\n")
153 }