From 11bb2922fbb8440e8d2f3e0284c7a327ec0234a5 Mon Sep 17 00:00:00 2001 From: Michael Matloob Date: Wed, 24 May 2023 14:59:01 -0400 Subject: [PATCH] cmd/go: fix reporting of test cycles to have proper order and begin and end with the same package to demonstrate the cyclical nature of the stack. Also fix the list_test_cycle script test which was testing for the wrong behavior. Fixes #59970 Change-Id: I3b3ee6762ee121fec19688ff1823cdfddae94f53 Reviewed-on: https://go-review.googlesource.com/c/go/+/498115 Reviewed-by: Michael Matloob Run-TryBot: Michael Matloob Reviewed-by: Bryan Mills TryBot-Result: Gopher Robot --- src/cmd/go/internal/load/test.go | 13 ++++++++++++- src/cmd/go/testdata/script/list_test_cycle.txt | 3 ++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/cmd/go/internal/load/test.go b/src/cmd/go/internal/load/test.go index ff3e17c90a..ceedb99e2f 100644 --- a/src/cmd/go/internal/load/test.go +++ b/src/cmd/go/internal/load/test.go @@ -16,6 +16,7 @@ import ( "go/token" "internal/lazytemplate" "path/filepath" + "slices" "sort" "strings" "unicode" @@ -23,7 +24,6 @@ import ( "cmd/go/internal/cfg" "cmd/go/internal/fsys" - "cmd/go/internal/slices" "cmd/go/internal/str" "cmd/go/internal/trace" ) @@ -520,11 +520,22 @@ func recompileForTest(pmain, preal, ptest, pxtest *Package) *PackageError { p := q[0] q = q[1:] if p == ptest { + // The stack is supposed to be in the order x imports y imports z. + // We collect in the reverse order: z is imported by y is imported + // by x, and then we reverse it. var stk []string for p != nil { stk = append(stk, p.ImportPath) p = importerOf[p] } + // complete the cycle: we set importer[p] = nil to break the cycle + // in importerOf, it's an implicit importerOf[p] == pTest. Add it + // back here since we reached nil in the loop above to demonstrate + // the cycle as (for example) package p imports package q imports package r + // imports package p. + stk = append(stk, ptest.ImportPath) + slices.Reverse(stk) + return &PackageError{ ImportStack: stk, Err: errors.New("import cycle not allowed in test"), diff --git a/src/cmd/go/testdata/script/list_test_cycle.txt b/src/cmd/go/testdata/script/list_test_cycle.txt index ea63792007..67edf18337 100644 --- a/src/cmd/go/testdata/script/list_test_cycle.txt +++ b/src/cmd/go/testdata/script/list_test_cycle.txt @@ -15,8 +15,9 @@ cmp stderr wanterr.txt -- wanterr.txt -- go: can't load test package: package example/p + imports example/q imports example/r - imports example/q: import cycle not allowed in test + imports example/p: import cycle not allowed in test -- go.mod -- module example go 1.20 -- 2.48.1