Skip to content

Commit f03577d

Browse files
authored
flakeguard: Fix codeowners (#1425)
1 parent 151614d commit f03577d

File tree

5 files changed

+51
-31
lines changed

5 files changed

+51
-31
lines changed

tools/flakeguard/cmd/aggregate_results.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ var AggregateResultsCmd = &cobra.Command{
5656

5757
// Output results to JSON files
5858
if len(resultsToSave) > 0 {
59-
return reports.SaveFilteredResultsAndLogs(outputResultsPath, outputLogsPath, allReport)
59+
return reports.SaveFilteredResultsAndLogs(outputResultsPath, outputLogsPath, allReport, codeOwnersPath != "")
6060
}
6161
return nil
6262
},
@@ -70,5 +70,4 @@ func init() {
7070
AggregateResultsCmd.Flags().BoolVarP(&filterFailed, "filter-failed", "f", false, "If true, filter and output only failed tests based on the max-pass-ratio threshold")
7171
AggregateResultsCmd.Flags().StringVarP(&codeOwnersPath, "codeowners-path", "c", "", "Path to the CODEOWNERS file")
7272
AggregateResultsCmd.Flags().StringVarP(&projectPath, "project-path", "r", ".", "The path to the Go project. Default is the current directory. Useful for subprojects")
73-
7473
}

tools/flakeguard/cmd/run.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ var RunTestsCmd = &cobra.Command{
7171
// Print all failed tests including flaky tests
7272
if printFailedTests {
7373
fmt.Printf("PassRatio threshold for flaky tests: %.2f\n", maxPassRatio)
74-
reports.PrintTests(os.Stdout, testReport.Results, maxPassRatio)
74+
reports.PrintTests(os.Stdout, testReport.Results, maxPassRatio, false)
7575
}
7676

7777
// Save the test results in JSON format

tools/flakeguard/reports/codebase_scanner.go

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package reports
22

33
import (
4+
"fmt"
45
"go/ast"
56
"go/parser"
67
"go/token"
@@ -16,33 +17,52 @@ type TestFileMap map[string]string
1617
func ScanTestFiles(rootDir string) (TestFileMap, error) {
1718
testFileMap := make(TestFileMap)
1819

19-
err := filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error {
20+
// Ensure rootDir is absolute
21+
rootDir, err := filepath.Abs(rootDir)
22+
if err != nil {
23+
return nil, fmt.Errorf("error normalizing rootDir: %v", err)
24+
}
25+
26+
// Walk through the root directory to find test files
27+
err = filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error {
2028
if err != nil {
2129
return err
2230
}
31+
32+
// Skip files that are not Go test files
2333
if !strings.HasSuffix(path, "_test.go") {
2434
return nil
2535
}
2636

27-
// Parse the file
37+
// Normalize path relative to rootDir
38+
relPath, err := filepath.Rel(rootDir, path)
39+
if err != nil {
40+
return fmt.Errorf("error getting relative path for %s: %v", path, err)
41+
}
42+
relPath = filepath.ToSlash(relPath) // Ensure Unix-style paths
43+
44+
// Parse the Go file
2845
fset := token.NewFileSet()
2946
node, err := parser.ParseFile(fset, path, nil, parser.AllErrors)
3047
if err != nil {
31-
return err
48+
return fmt.Errorf("error parsing file %s: %v", path, err)
3249
}
3350

34-
// Traverse the AST to find test functions
51+
// Traverse the AST to find test or fuzz functions
3552
ast.Inspect(node, func(n ast.Node) bool {
3653
funcDecl, ok := n.(*ast.FuncDecl)
3754
if !ok {
3855
return true
3956
}
40-
if strings.HasPrefix(funcDecl.Name.Name, "Test") {
41-
// Add both the package and test function to the map
42-
testFileMap[funcDecl.Name.Name] = path
57+
58+
// Match both "Test" and "Fuzz" prefixes
59+
if strings.HasPrefix(funcDecl.Name.Name, "Test") || strings.HasPrefix(funcDecl.Name.Name, "Fuzz") {
60+
// Add the function to the map with relative path
61+
testFileMap[funcDecl.Name.Name] = relPath
4362
}
4463
return true
4564
})
65+
4666
return nil
4767
})
4868

tools/flakeguard/reports/path_mapper.go

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
package reports
22

33
import (
4-
"fmt"
5-
"path/filepath"
64
"strings"
75
)
86

@@ -30,13 +28,8 @@ func MapTestResultsToPaths(report *TestReport, rootDir string) error {
3028
filePath = path
3129
}
3230

33-
// Normalize filePath to be relative to the project root
3431
if filePath != "" {
35-
relFilePath, err := filepath.Rel(rootDir, filePath)
36-
if err != nil {
37-
return fmt.Errorf("error getting relative path: %v", err)
38-
}
39-
report.Results[i].TestPath = relFilePath
32+
report.Results[i].TestPath = filePath
4033
} else {
4134
// Log or mark tests not found in the codebase
4235
report.Results[i].TestPath = "NOT FOUND"

tools/flakeguard/reports/reports.go

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@ func PrintTests(
193193
w io.Writer,
194194
tests []TestResult,
195195
maxPassRatio float64,
196+
includeCodeOwners bool, // Include code owners in the output. Set to true if test results have code owners
196197
) (runs, passes, fails, skips, panickedTests, racedTests, flakyTests int) {
197198
p := message.NewPrinter(language.English) // For formatting numbers
198199
sortTestResults(tests)
@@ -210,19 +211,17 @@ func PrintTests(
210211
"**Package**",
211212
"**Package Panicked?**",
212213
"**Avg Duration**",
213-
"**Code Owners**",
214+
}
215+
216+
if includeCodeOwners {
217+
headers = append(headers, "**Code Owners**")
214218
}
215219

216220
// Build test rows and summary data
217221
rows := [][]string{}
218222
for _, test := range tests {
219223
if test.PassRatio < maxPassRatio {
220-
owners := "Unknown"
221-
if len(test.CodeOwners) > 0 {
222-
owners = strings.Join(test.CodeOwners, ", ")
223-
}
224-
225-
rows = append(rows, []string{
224+
row := []string{
226225
test.TestName,
227226
fmt.Sprintf("%.2f%%", test.PassRatio*100),
228227
fmt.Sprintf("%t", test.Panic),
@@ -235,8 +234,17 @@ func PrintTests(
235234
test.TestPackage,
236235
fmt.Sprintf("%t", test.PackagePanic),
237236
avgDuration(test.Durations).String(),
238-
owners,
239-
})
237+
}
238+
239+
if includeCodeOwners {
240+
owners := "Unknown"
241+
if len(test.CodeOwners) > 0 {
242+
owners = strings.Join(test.CodeOwners, ", ")
243+
}
244+
row = append(row, owners)
245+
}
246+
247+
rows = append(rows, row)
240248
}
241249

242250
runs += test.Runs
@@ -350,7 +358,7 @@ func PrintTests(
350358
}
351359

352360
// MarkdownSummary builds a summary of test results in markdown format, handy for reporting in CI and Slack
353-
func MarkdownSummary(w io.Writer, testReport *TestReport, maxPassRatio float64) {
361+
func MarkdownSummary(w io.Writer, testReport *TestReport, maxPassRatio float64, includeCodeOwners bool) {
354362
var (
355363
avgPassRatio = 1.0
356364
testsData = bytes.NewBuffer(nil)
@@ -401,7 +409,7 @@ func MarkdownSummary(w io.Writer, testReport *TestReport, maxPassRatio float64)
401409
return
402410
}
403411

404-
allRuns, passes, _, _, _, _, _ := PrintTests(testsData, tests, maxPassRatio)
412+
allRuns, passes, _, _, _, _, _ := PrintTests(testsData, tests, maxPassRatio, includeCodeOwners)
405413
if allRuns > 0 {
406414
avgPassRatio = float64(passes) / float64(allRuns)
407415
}
@@ -414,7 +422,7 @@ func MarkdownSummary(w io.Writer, testReport *TestReport, maxPassRatio float64)
414422
}
415423

416424
// Helper function to save filtered results and logs to specified paths
417-
func SaveFilteredResultsAndLogs(outputResultsPath, outputLogsPath string, report *TestReport) error {
425+
func SaveFilteredResultsAndLogs(outputResultsPath, outputLogsPath string, report *TestReport, includeCodeOwners bool) error {
418426
if outputResultsPath != "" {
419427
if err := os.MkdirAll(filepath.Dir(outputResultsPath), 0755); err != nil { //nolint:gosec
420428
return fmt.Errorf("error creating output directory: %w", err)
@@ -430,7 +438,7 @@ func SaveFilteredResultsAndLogs(outputResultsPath, outputLogsPath string, report
430438
return fmt.Errorf("error creating markdown file: %w", err)
431439
}
432440
defer summaryFile.Close()
433-
MarkdownSummary(summaryFile, report, 1.0)
441+
MarkdownSummary(summaryFile, report, 1.0, includeCodeOwners)
434442
fmt.Printf("Test results saved to %s and summary to %s\n", jsonFileName, mdFileName)
435443
} else {
436444
fmt.Println("No failed tests found based on the specified threshold and min pass ratio.")

0 commit comments

Comments
 (0)