@@ -21,6 +21,7 @@ import (
2121 "go/token"
2222 "go/types"
2323 "slices"
24+ "sync"
2425 "testing"
2526
2627 "github.com/stretchr/testify/require"
@@ -195,3 +196,69 @@ var f func() (*http.Request, error)`,
195196 })
196197 }
197198}
199+
200+ func resetGlobals () {
201+ // 重置 GOROOT 的 sync.Once 和其缓存的变量
202+ gorootOnce = sync.Once {}
203+ detectedGoRoot = ""
204+ gorootErr = nil
205+
206+ // 重置包缓存
207+ stdlibCache = NewPackageCache ()
208+ }
209+
210+ func Test_isSysPkg (t * testing.T ) {
211+ // 测试在 `go env GOROOT` 可以成功执行时的行为
212+ t .Run ("Group: Happy Path - GOROOT is found" , func (t * testing.T ) {
213+ resetGlobals ()
214+
215+ testCases := []struct {
216+ name string
217+ importPath string
218+ want bool
219+ }{
220+ {"standard library package" , "fmt" , true },
221+ {"nested standard library package" , "net/http" , true },
222+ {"third-party package" , "github.com/google/uuid" , false },
223+ {"extended library package" , "golang.org/x/sync/errgroup" , false },
224+ {"local-like package name" , "myproject/utils" , false },
225+ {"non-existent package" , "non/existent/package" , false },
226+ {"root-level package with dot" , "gopkg.in/yaml.v2" , false },
227+ }
228+
229+ for _ , tc := range testCases {
230+ t .Run (tc .name , func (t * testing.T ) {
231+ if got := isSysPkg (tc .importPath ); got != tc .want {
232+ t .Errorf ("isSysPkg(%q) = %v, want %v" , tc .importPath , got , tc .want )
233+ }
234+ })
235+ }
236+ })
237+
238+ // 测试在 `go env GOROOT` 执行失败时的行为
239+ t .Run ("Group: Fallback Path - GOROOT is not found" , func (t * testing.T ) {
240+ resetGlobals ()
241+
242+ // 使用 t.Setenv 临时清空 PATH,使得 "go" 命令无法被找到
243+ t .Setenv ("PATH" , "" )
244+
245+ testCases := []struct {
246+ name string
247+ importPath string
248+ want bool
249+ }{
250+ {"standard library package (fallback)" , "fmt" , true },
251+ {"nested standard library package (fallback)" , "os/exec" , true },
252+ {"third-party package (fallback)" , "github.com/google/uuid" , false },
253+ {"local-like package name (fallback)" , "myproject/utils" , true }, // 在降级模式下,被错误地判断为 true
254+ }
255+
256+ for _ , tc := range testCases {
257+ t .Run (tc .name , func (t * testing.T ) {
258+ if got := isSysPkg (tc .importPath ); got != tc .want {
259+ t .Errorf ("isSysPkg(%q) in fallback mode = %v, want %v" , tc .importPath , got , tc .want )
260+ }
261+ })
262+ }
263+ })
264+ }
0 commit comments