| 1 |
// Copyright 2018 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package packages_test |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"encoding/json" |
| 10 |
"fmt" |
| 11 |
"go/ast" |
| 12 |
constantpkg "go/constant" |
| 13 |
"go/parser" |
| 14 |
"go/token" |
| 15 |
"go/types" |
| 16 |
"os" |
| 17 |
"os/exec" |
| 18 |
"path/filepath" |
| 19 |
"reflect" |
| 20 |
"runtime" |
| 21 |
"slices" |
| 22 |
"sort" |
| 23 |
"strings" |
| 24 |
"testing" |
| 25 |
"testing/fstest" |
| 26 |
|
| 27 |
"github.com/google/go-cmp/cmp" |
| 28 |
"golang.org/x/tools/go/packages" |
| 29 |
"golang.org/x/tools/internal/packagepath" |
| 30 |
"golang.org/x/tools/internal/packagesinternal" |
| 31 |
"golang.org/x/tools/internal/packagestest" |
| 32 |
"golang.org/x/tools/internal/testenv" |
| 33 |
"golang.org/x/tools/internal/testfiles" |
| 34 |
"golang.org/x/tools/txtar" |
| 35 |
) |
| 36 |
|
| 37 |
func TestMain(m *testing.M) { |
| 38 |
testenv.ExitIfSmallMachine() |
| 39 |
|
| 40 |
os.Exit(m.Run()) |
| 41 |
} |
| 42 |
|
| 43 |
func skipIfShort(t *testing.T, reason string) { |
| 44 |
if testing.Short() { |
| 45 |
t.Skipf("skipping slow test in short mode: %s", reason) |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
// testAllOrModulesParallel tests f, in parallel, against all packagestest |
| 50 |
// exporters in long mode, but only against the Modules exporter in short mode. |
| 51 |
func testAllOrModulesParallel(t *testing.T, f func(*testing.T, packagestest.Exporter)) { |
| 52 |
t.Parallel() |
| 53 |
packagestest.TestAll(t, func(t *testing.T, exporter packagestest.Exporter) { |
| 54 |
t.Helper() |
| 55 |
|
| 56 |
switch exporter.Name() { |
| 57 |
case "Modules": |
| 58 |
case "GOPATH": |
| 59 |
if testing.Short() { |
| 60 |
t.Skipf("skipping GOPATH test in short mode") |
| 61 |
} |
| 62 |
default: |
| 63 |
t.Fatalf("unexpected exporter %q", exporter.Name()) |
| 64 |
} |
| 65 |
|
| 66 |
t.Parallel() |
| 67 |
f(t, exporter) |
| 68 |
}) |
| 69 |
} |
| 70 |
|
| 71 |
// TODO(adonovan): more test cases to write: |
| 72 |
// |
| 73 |
// - When the tests fail, make them print a 'cd & load' command |
| 74 |
// that will allow the maintainer to interact with the failing scenario. |
| 75 |
// - errors in go-list metadata |
| 76 |
// - a foo.test package that cannot be built for some reason (e.g. |
| 77 |
// import error) will result in a JSON blob with no name and a |
| 78 |
// nonexistent testmain file in GoFiles. Test that we handle this |
| 79 |
// gracefully. |
| 80 |
// - test more Flags. |
| 81 |
// |
| 82 |
// LoadSyntax & LoadAllSyntax modes: |
| 83 |
// - Fset may be user-supplied or not. |
| 84 |
// - Packages.Info is correctly set. |
| 85 |
// - typechecker configuration is honored |
| 86 |
// - import cycles are gracefully handled in type checker. |
| 87 |
// - test typechecking of generated test main and cgo. |
| 88 |
|
| 89 |
// The zero-value of Config has LoadFiles mode. |
| 90 |
func TestLoadZeroConfig(t *testing.T) { |
| 91 |
testenv.NeedsGoPackages(t) |
| 92 |
t.Parallel() |
| 93 |
|
| 94 |
initial, err := packages.Load(nil, "hash") |
| 95 |
if err != nil { |
| 96 |
t.Fatal(err) |
| 97 |
} |
| 98 |
if len(initial) != 1 { |
| 99 |
t.Fatalf("got %s, want [hash]", initial) |
| 100 |
} |
| 101 |
hash := initial[0] |
| 102 |
// Even though the hash package has imports, |
| 103 |
// they are not reported. |
| 104 |
got := fmt.Sprintf("srcs=%v imports=%v", srcs(hash), hash.Imports) |
| 105 |
want := "srcs=[hash.go] imports=map[]" |
| 106 |
if got != want { |
| 107 |
t.Fatalf("got %s, want %s", got, want) |
| 108 |
} |
| 109 |
} |
| 110 |
|
| 111 |
func TestLoadImportsGraph(t *testing.T) { testAllOrModulesParallel(t, testLoadImportsGraph) } |
| 112 |
func testLoadImportsGraph(t *testing.T, exporter packagestest.Exporter) { |
| 113 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 114 |
Name: "golang.org/fake", |
| 115 |
Files: map[string]any{ |
| 116 |
"a/a.go": `package a; const A = 1`, |
| 117 |
"b/b.go": `package b; import ("golang.org/fake/a"; _ "container/list"); var B = a.A`, |
| 118 |
"c/c.go": `package c; import (_ "golang.org/fake/b"; _ "unsafe")`, |
| 119 |
"c/c2.go": "// +build ignore\n\n" + `package c; import _ "fmt"`, |
| 120 |
"subdir/d/d.go": `package d`, |
| 121 |
"subdir/d/d_test.go": `package d; import _ "math/bits"`, |
| 122 |
"subdir/d/x_test.go": `package d_test; import _ "golang.org/fake/subdir/d"`, // TODO(adonovan): test bad import here |
| 123 |
"subdir/e/d.go": `package e`, |
| 124 |
"e/e.go": `package main; import _ "golang.org/fake/b"`, |
| 125 |
"e/e2.go": `package main; import _ "golang.org/fake/c"`, |
| 126 |
"f/f.go": `package f`, |
| 127 |
}}}) |
| 128 |
defer exported.Cleanup() |
| 129 |
exported.Config.Mode = packages.LoadImports |
| 130 |
initial, err := packages.Load(exported.Config, "golang.org/fake/c", "golang.org/fake/subdir/d", "golang.org/fake/e") |
| 131 |
if err != nil { |
| 132 |
t.Fatal(err) |
| 133 |
} |
| 134 |
|
| 135 |
// Check graph topology. |
| 136 |
graph, _ := importGraph(initial) |
| 137 |
wantGraph := ` |
| 138 |
container/list |
| 139 |
golang.org/fake/a |
| 140 |
golang.org/fake/b |
| 141 |
* golang.org/fake/c |
| 142 |
* golang.org/fake/e |
| 143 |
* golang.org/fake/subdir/d |
| 144 |
* golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] |
| 145 |
* golang.org/fake/subdir/d.test |
| 146 |
* golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test] |
| 147 |
math/bits |
| 148 |
unsafe |
| 149 |
golang.org/fake/b -> container/list |
| 150 |
golang.org/fake/b -> golang.org/fake/a |
| 151 |
golang.org/fake/c -> golang.org/fake/b |
| 152 |
golang.org/fake/c -> unsafe |
| 153 |
golang.org/fake/e -> golang.org/fake/b |
| 154 |
golang.org/fake/e -> golang.org/fake/c |
| 155 |
golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] -> math/bits |
| 156 |
golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] |
| 157 |
golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test] |
| 158 |
golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test] -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] |
| 159 |
`[1:] |
| 160 |
|
| 161 |
if graph != wantGraph { |
| 162 |
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph) |
| 163 |
} |
| 164 |
|
| 165 |
exported.Config.Tests = true |
| 166 |
initial, err = packages.Load(exported.Config, "golang.org/fake/c", "golang.org/fake/subdir/d", "golang.org/fake/e") |
| 167 |
if err != nil { |
| 168 |
t.Fatal(err) |
| 169 |
} |
| 170 |
|
| 171 |
// Check graph topology. |
| 172 |
graph, all := importGraph(initial) |
| 173 |
wantGraph = ` |
| 174 |
container/list |
| 175 |
golang.org/fake/a |
| 176 |
golang.org/fake/b |
| 177 |
* golang.org/fake/c |
| 178 |
* golang.org/fake/e |
| 179 |
* golang.org/fake/subdir/d |
| 180 |
* golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] |
| 181 |
* golang.org/fake/subdir/d.test |
| 182 |
* golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test] |
| 183 |
math/bits |
| 184 |
unsafe |
| 185 |
golang.org/fake/b -> container/list |
| 186 |
golang.org/fake/b -> golang.org/fake/a |
| 187 |
golang.org/fake/c -> golang.org/fake/b |
| 188 |
golang.org/fake/c -> unsafe |
| 189 |
golang.org/fake/e -> golang.org/fake/b |
| 190 |
golang.org/fake/e -> golang.org/fake/c |
| 191 |
golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] -> math/bits |
| 192 |
golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] |
| 193 |
golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test] |
| 194 |
golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test] -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] |
| 195 |
`[1:] |
| 196 |
|
| 197 |
if graph != wantGraph { |
| 198 |
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph) |
| 199 |
} |
| 200 |
|
| 201 |
// Check node information: kind, name, srcs. |
| 202 |
for _, test := range []struct { |
| 203 |
id string |
| 204 |
wantName string |
| 205 |
wantKind string |
| 206 |
wantSrcs string // = {Go,Other,Embed}Files |
| 207 |
wantIgnored string |
| 208 |
}{ |
| 209 |
{"golang.org/fake/a", "a", "package", "a.go", ""}, |
| 210 |
{"golang.org/fake/b", "b", "package", "b.go", ""}, |
| 211 |
{"golang.org/fake/c", "c", "package", "c.go", "c2.go"}, // c2.go is ignored |
| 212 |
{"golang.org/fake/e", "main", "command", "e.go e2.go", ""}, |
| 213 |
{"container/list", "list", "package", "list.go", ""}, |
| 214 |
{"golang.org/fake/subdir/d", "d", "package", "d.go", ""}, |
| 215 |
{"golang.org/fake/subdir/d.test", "main", "command", "0.go", ""}, |
| 216 |
{"unsafe", "unsafe", "package", "unsafe.go", ""}, |
| 217 |
} { |
| 218 |
p, ok := all[test.id] |
| 219 |
if !ok { |
| 220 |
t.Errorf("no package %s", test.id) |
| 221 |
continue |
| 222 |
} |
| 223 |
if p.Name != test.wantName { |
| 224 |
t.Errorf("%s.Name = %q, want %q", test.id, p.Name, test.wantName) |
| 225 |
} |
| 226 |
|
| 227 |
// kind |
| 228 |
var kind string |
| 229 |
if p.Name == "main" { |
| 230 |
kind += "command" |
| 231 |
} else { |
| 232 |
kind += "package" |
| 233 |
} |
| 234 |
if kind != test.wantKind { |
| 235 |
t.Errorf("%s.Kind = %q, want %q", test.id, kind, test.wantKind) |
| 236 |
} |
| 237 |
|
| 238 |
if srcs := strings.Join(srcs(p), " "); srcs != test.wantSrcs { |
| 239 |
t.Errorf("%s.{Go,Other,Embed}Files = [%s], want [%s]", test.id, srcs, test.wantSrcs) |
| 240 |
} |
| 241 |
if ignored := strings.Join(cleanPaths(p.IgnoredFiles), " "); ignored != test.wantIgnored { |
| 242 |
t.Errorf("%s.IgnoredFiles = [%s], want [%s]", test.id, ignored, test.wantIgnored) |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
// Test an ad-hoc package, analogous to "go run hello.go". |
| 247 |
if initial, err := packages.Load(exported.Config, exported.File("golang.org/fake", "c/c.go")); len(initial) == 0 { |
| 248 |
t.Errorf("failed to obtain metadata for ad-hoc package: %s", err) |
| 249 |
} else { |
| 250 |
got := fmt.Sprintf("%s %s", initial[0].ID, srcs(initial[0])) |
| 251 |
if want := "command-line-arguments [c.go]"; got != want { |
| 252 |
t.Errorf("oops: got %s, want %s", got, want) |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
// Wildcards |
| 257 |
// See StdlibTest for effective test of "std" wildcard. |
| 258 |
// TODO(adonovan): test "all" returns everything in the current module. |
| 259 |
{ |
| 260 |
// "..." (subdirectory) |
| 261 |
initial, err = packages.Load(exported.Config, "golang.org/fake/subdir/...") |
| 262 |
if err != nil { |
| 263 |
t.Fatal(err) |
| 264 |
} |
| 265 |
graph, _ = importGraph(initial) |
| 266 |
wantGraph = ` |
| 267 |
* golang.org/fake/subdir/d |
| 268 |
* golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] |
| 269 |
* golang.org/fake/subdir/d.test |
| 270 |
* golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test] |
| 271 |
* golang.org/fake/subdir/e |
| 272 |
math/bits |
| 273 |
golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] -> math/bits |
| 274 |
golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] |
| 275 |
golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test] |
| 276 |
golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test] -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] |
| 277 |
`[1:] |
| 278 |
|
| 279 |
if graph != wantGraph { |
| 280 |
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph) |
| 281 |
} |
| 282 |
} |
| 283 |
} |
| 284 |
|
| 285 |
func TestLoadImportsTestVariants(t *testing.T) { |
| 286 |
testAllOrModulesParallel(t, testLoadImportsTestVariants) |
| 287 |
} |
| 288 |
func testLoadImportsTestVariants(t *testing.T, exporter packagestest.Exporter) { |
| 289 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 290 |
Name: "golang.org/fake", |
| 291 |
Files: map[string]any{ |
| 292 |
"a/a.go": `package a; import _ "golang.org/fake/b"`, |
| 293 |
"b/b.go": `package b`, |
| 294 |
"b/b_test.go": `package b`, |
| 295 |
"b/bx_test.go": `package b_test; import _ "golang.org/fake/a"`, |
| 296 |
}}}) |
| 297 |
defer exported.Cleanup() |
| 298 |
exported.Config.Mode = packages.LoadImports |
| 299 |
exported.Config.Tests = true |
| 300 |
|
| 301 |
initial, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/b") |
| 302 |
if err != nil { |
| 303 |
t.Fatal(err) |
| 304 |
} |
| 305 |
|
| 306 |
// Check graph topology. |
| 307 |
graph, _ := importGraph(initial) |
| 308 |
wantGraph := ` |
| 309 |
* golang.org/fake/a |
| 310 |
golang.org/fake/a [golang.org/fake/b.test] |
| 311 |
* golang.org/fake/b |
| 312 |
* golang.org/fake/b [golang.org/fake/b.test] |
| 313 |
* golang.org/fake/b.test |
| 314 |
* golang.org/fake/b_test [golang.org/fake/b.test] |
| 315 |
golang.org/fake/a -> golang.org/fake/b |
| 316 |
golang.org/fake/a [golang.org/fake/b.test] -> golang.org/fake/b [golang.org/fake/b.test] |
| 317 |
golang.org/fake/b.test -> golang.org/fake/b [golang.org/fake/b.test] |
| 318 |
golang.org/fake/b.test -> golang.org/fake/b_test [golang.org/fake/b.test] |
| 319 |
golang.org/fake/b_test [golang.org/fake/b.test] -> golang.org/fake/a [golang.org/fake/b.test] |
| 320 |
`[1:] |
| 321 |
|
| 322 |
if graph != wantGraph { |
| 323 |
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph) |
| 324 |
} |
| 325 |
} |
| 326 |
|
| 327 |
func TestLoadAbsolutePath(t *testing.T) { |
| 328 |
t.Parallel() |
| 329 |
|
| 330 |
exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{{ |
| 331 |
Name: "golang.org/gopatha", |
| 332 |
Files: map[string]any{ |
| 333 |
"a/a.go": `package a`, |
| 334 |
}}, { |
| 335 |
Name: "golang.org/gopathb", |
| 336 |
Files: map[string]any{ |
| 337 |
"b/b.go": `package b`, |
| 338 |
}}}) |
| 339 |
defer exported.Cleanup() |
| 340 |
|
| 341 |
initial, err := packages.Load(exported.Config, filepath.Dir(exported.File("golang.org/gopatha", "a/a.go")), filepath.Dir(exported.File("golang.org/gopathb", "b/b.go"))) |
| 342 |
if err != nil { |
| 343 |
t.Fatalf("failed to load imports: %v", err) |
| 344 |
} |
| 345 |
|
| 346 |
got := []string{} |
| 347 |
for _, p := range initial { |
| 348 |
got = append(got, p.ID) |
| 349 |
} |
| 350 |
sort.Strings(got) |
| 351 |
want := []string{"golang.org/gopatha/a", "golang.org/gopathb/b"} |
| 352 |
if !reflect.DeepEqual(got, want) { |
| 353 |
t.Fatalf("initial packages loaded: got [%s], want [%s]", got, want) |
| 354 |
} |
| 355 |
} |
| 356 |
|
| 357 |
func TestLoadArgumentListIsNotTooLong(t *testing.T) { |
| 358 |
// NOTE: this test adds about 2s to the test suite running time |
| 359 |
|
| 360 |
t.Parallel() |
| 361 |
|
| 362 |
// using the real ARG_MAX for some platforms increases the running time of this test by a lot, |
| 363 |
// 1_000_000 seems like enough to break Windows and macOS if Load doesn't split provided patterns |
| 364 |
argMax := 1_000_000 |
| 365 |
exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{{ |
| 366 |
Name: "golang.org/mod", |
| 367 |
Files: map[string]any{ |
| 368 |
"main.go": `package main"`, |
| 369 |
}}}) |
| 370 |
defer exported.Cleanup() |
| 371 |
numOfPatterns := argMax/16 + 1 // the pattern below is approx. 16 chars |
| 372 |
patterns := make([]string, numOfPatterns) |
| 373 |
for i := range numOfPatterns { |
| 374 |
patterns[i] = fmt.Sprintf("golang.org/mod/p%d", i) |
| 375 |
} // patterns have more than argMax number of chars combined with whitespaces b/w patterns |
| 376 |
|
| 377 |
_, err := packages.Load(exported.Config, patterns...) |
| 378 |
if err != nil { |
| 379 |
t.Fatalf("failed to load: %v", err) |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
func TestLoadSamePackageMultipleChunks(t *testing.T) { |
| 384 |
t.Parallel() |
| 385 |
|
| 386 |
exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{{ |
| 387 |
Name: "golang.org/fake", |
| 388 |
Files: map[string]any{ |
| 389 |
"a/def.go": `package a; const SharedConstant = 42`, |
| 390 |
}}}) |
| 391 |
defer exported.Cleanup() |
| 392 |
|
| 393 |
defFile := exported.File("golang.org/fake", "a/def.go") |
| 394 |
|
| 395 |
// Force chunking (exceed ~16KB arg limit) |
| 396 |
var files []string |
| 397 |
files = append(files, defFile) |
| 398 |
|
| 399 |
for i := range 200 { |
| 400 |
fillerPath := filepath.Join(filepath.Dir(defFile), fmt.Sprintf("filler_%03d.go", i)) |
| 401 |
if err := os.WriteFile(fillerPath, []byte("package a\n"), 0644); err != nil { |
| 402 |
t.Fatal(err) |
| 403 |
} |
| 404 |
files = append(files, fillerPath) |
| 405 |
} |
| 406 |
|
| 407 |
exported.Config.Mode = packages.NeedFiles |
| 408 |
pkgs, err := packages.Load(exported.Config, files...) |
| 409 |
if err != nil { |
| 410 |
t.Fatal(err) |
| 411 |
} |
| 412 |
|
| 413 |
if len(pkgs) == 0 { |
| 414 |
t.Fatal("package golang.org/fake/a not found") |
| 415 |
} |
| 416 |
|
| 417 |
if len(pkgs[0].GoFiles) != len(files) { |
| 418 |
t.Errorf("expected %d files, got %d", len(files), len(pkgs[0].GoFiles)) |
| 419 |
} |
| 420 |
} |
| 421 |
|
| 422 |
// TestLoadDoesNotInvokeGit ensures that the expensive and unnecessary VCS check is skipped; |
| 423 |
// see go.dev/issue/51999 and go.dev/issue/77419. |
| 424 |
func TestLoadDoesNotInvokeGit(t *testing.T) { |
| 425 |
testenv.NeedsGoPackages(t) |
| 426 |
t.Parallel() |
| 427 |
|
| 428 |
exported := packagestest.Export(t, packagestest.Modules, []packagestest.Module{{ |
| 429 |
Name: "golang.org/fake", |
| 430 |
Files: map[string]any{ |
| 431 |
"main.go": `package main; func main() {}`, |
| 432 |
}}}) |
| 433 |
defer exported.Cleanup() |
| 434 |
|
| 435 |
// mock a git repository by creating a .git directory |
| 436 |
modRoot := filepath.Dir(exported.File("golang.org/fake", "main.go")) |
| 437 |
if err := os.MkdirAll(filepath.Join(modRoot, ".git"), 0755); err != nil { |
| 438 |
t.Fatalf("creating .git: %v", err) |
| 439 |
} |
| 440 |
|
| 441 |
fakeGitDir := buildFakeGit(t, exported.Config.Env) |
| 442 |
|
| 443 |
pathVar := "PATH" |
| 444 |
if runtime.GOOS == "plan9" { |
| 445 |
pathVar = "path" |
| 446 |
} |
| 447 |
exported.Config.Env = prependPath(exported.Config.Env, pathVar, fakeGitDir) |
| 448 |
// NeedTypes triggers usesExportData, which sets -export=true on the go list invocation |
| 449 |
exported.Config.Mode = packages.NeedTypes |
| 450 |
|
| 451 |
pkgs, err := packages.Load(exported.Config, "golang.org/fake") |
| 452 |
if err != nil { |
| 453 |
t.Fatalf("packages.Load: %v", err) |
| 454 |
} |
| 455 |
if len(pkgs) != 1 { |
| 456 |
t.Fatalf("packages.Load: expected 1 package, got %d: %v", len(pkgs), pkgs) |
| 457 |
} |
| 458 |
if len(pkgs[0].Errors) > 0 { |
| 459 |
// Assume the failure was due to the fake git command being executed. |
| 460 |
t.Fatalf("packages.Load: unexpected errors (git should not have been called): %v", pkgs[0].Errors) |
| 461 |
} |
| 462 |
} |
| 463 |
|
| 464 |
// buildFakeGit returns a directory containing a "git" executable that exits 1. |
| 465 |
func buildFakeGit(t *testing.T, env []string) string { |
| 466 |
t.Helper() |
| 467 |
|
| 468 |
tmpdir := t.TempDir() |
| 469 |
gitName := "git" |
| 470 |
if runtime.GOOS == "windows" { |
| 471 |
gitName = "git.exe" |
| 472 |
} |
| 473 |
src := filepath.Join(tmpdir, "main.go") |
| 474 |
if err := os.WriteFile(src, []byte(`package main; func main() { panic("git executed") }`), 0644); err != nil { |
| 475 |
t.Fatal(err) |
| 476 |
} |
| 477 |
cmd := exec.Command("go", "build", "-o", gitName, "main.go") |
| 478 |
cmd.Dir = tmpdir |
| 479 |
cmd.Env = env |
| 480 |
if out, err := cmd.CombinedOutput(); err != nil { |
| 481 |
t.Fatalf("building fake git: %v\n%s", err, out) |
| 482 |
} |
| 483 |
return tmpdir |
| 484 |
} |
| 485 |
|
| 486 |
func prependPath(env []string, key, dir string) []string { |
| 487 |
result := make([]string, len(env)) |
| 488 |
copy(result, env) |
| 489 |
for i, v := range result { |
| 490 |
if val, ok := strings.CutPrefix(v, key+"="); ok { |
| 491 |
result[i] = key + "=" + dir + string(os.PathListSeparator) + val |
| 492 |
return result |
| 493 |
} |
| 494 |
} |
| 495 |
return append(result, key+"="+dir) |
| 496 |
} |
| 497 |
|
| 498 |
func TestVendorImports(t *testing.T) { |
| 499 |
t.Parallel() |
| 500 |
|
| 501 |
exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{{ |
| 502 |
Name: "golang.org/fake", |
| 503 |
Files: map[string]any{ |
| 504 |
"a/a.go": `package a; import _ "b"; import _ "golang.org/fake/c";`, |
| 505 |
"a/vendor/b/b.go": `package b; import _ "golang.org/fake/c"`, |
| 506 |
"c/c.go": `package c; import _ "b"`, |
| 507 |
"c/vendor/b/b.go": `package b`, |
| 508 |
}}}) |
| 509 |
defer exported.Cleanup() |
| 510 |
exported.Config.Mode = packages.LoadImports |
| 511 |
initial, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/c") |
| 512 |
if err != nil { |
| 513 |
t.Fatal(err) |
| 514 |
} |
| 515 |
|
| 516 |
graph, all := importGraph(initial) |
| 517 |
wantGraph := ` |
| 518 |
* golang.org/fake/a |
| 519 |
golang.org/fake/a/vendor/b |
| 520 |
* golang.org/fake/c |
| 521 |
golang.org/fake/c/vendor/b |
| 522 |
golang.org/fake/a -> golang.org/fake/a/vendor/b |
| 523 |
golang.org/fake/a -> golang.org/fake/c |
| 524 |
golang.org/fake/a/vendor/b -> golang.org/fake/c |
| 525 |
golang.org/fake/c -> golang.org/fake/c/vendor/b |
| 526 |
`[1:] |
| 527 |
if graph != wantGraph { |
| 528 |
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph) |
| 529 |
} |
| 530 |
|
| 531 |
for _, test := range []struct { |
| 532 |
pattern string |
| 533 |
wantImports string |
| 534 |
}{ |
| 535 |
{"golang.org/fake/a", "b:golang.org/fake/a/vendor/b golang.org/fake/c:golang.org/fake/c"}, |
| 536 |
{"golang.org/fake/c", "b:golang.org/fake/c/vendor/b"}, |
| 537 |
{"golang.org/fake/a/vendor/b", "golang.org/fake/c:golang.org/fake/c"}, |
| 538 |
{"golang.org/fake/c/vendor/b", ""}, |
| 539 |
} { |
| 540 |
// Test the import paths. |
| 541 |
pkg := all[test.pattern] |
| 542 |
if imports := strings.Join(imports(pkg), " "); imports != test.wantImports { |
| 543 |
t.Errorf("package %q: got %s, want %s", test.pattern, imports, test.wantImports) |
| 544 |
} |
| 545 |
} |
| 546 |
} |
| 547 |
|
| 548 |
func imports(p *packages.Package) []string { |
| 549 |
if p == nil { |
| 550 |
return nil |
| 551 |
} |
| 552 |
keys := make([]string, 0, len(p.Imports)) |
| 553 |
for k, v := range p.Imports { |
| 554 |
keys = append(keys, fmt.Sprintf("%s:%s", k, v.ID)) |
| 555 |
} |
| 556 |
sort.Strings(keys) |
| 557 |
return keys |
| 558 |
} |
| 559 |
|
| 560 |
func TestConfigDir(t *testing.T) { testAllOrModulesParallel(t, testConfigDir) } |
| 561 |
func testConfigDir(t *testing.T, exporter packagestest.Exporter) { |
| 562 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 563 |
Name: "golang.org/fake", |
| 564 |
Files: map[string]any{ |
| 565 |
"a/a.go": `package a; const Name = "a" `, |
| 566 |
"a/b/b.go": `package b; const Name = "a/b"`, |
| 567 |
"b/b.go": `package b; const Name = "b"`, |
| 568 |
}}}) |
| 569 |
defer exported.Cleanup() |
| 570 |
aDir := filepath.Dir(exported.File("golang.org/fake", "a/a.go")) |
| 571 |
bDir := filepath.Dir(exported.File("golang.org/fake", "b/b.go")) |
| 572 |
baseDir := filepath.Dir(aDir) |
| 573 |
|
| 574 |
for _, test := range []struct { |
| 575 |
dir string |
| 576 |
pattern string |
| 577 |
want string // value of Name constant |
| 578 |
fails bool |
| 579 |
}{ |
| 580 |
{dir: bDir, pattern: "golang.org/fake/a", want: `"a"`}, |
| 581 |
{dir: bDir, pattern: "golang.org/fake/b", want: `"b"`}, |
| 582 |
{dir: bDir, pattern: "./a", fails: true}, |
| 583 |
{dir: bDir, pattern: "./b", fails: true}, |
| 584 |
{dir: baseDir, pattern: "golang.org/fake/a", want: `"a"`}, |
| 585 |
{dir: baseDir, pattern: "golang.org/fake/b", want: `"b"`}, |
| 586 |
{dir: baseDir, pattern: "./a", want: `"a"`}, |
| 587 |
{dir: baseDir, pattern: "./b", want: `"b"`}, |
| 588 |
{dir: aDir, pattern: "golang.org/fake/a", want: `"a"`}, |
| 589 |
{dir: aDir, pattern: "golang.org/fake/b", want: `"b"`}, |
| 590 |
{dir: aDir, pattern: "./a", fails: true}, |
| 591 |
{dir: aDir, pattern: "./b", want: `"a/b"`}, |
| 592 |
} { |
| 593 |
exported.Config.Mode = packages.LoadSyntax // Use LoadSyntax to ensure that files can be opened. |
| 594 |
exported.Config.Dir = test.dir |
| 595 |
initial, err := packages.Load(exported.Config, test.pattern) |
| 596 |
var got string |
| 597 |
fails := false |
| 598 |
if err != nil { |
| 599 |
fails = true |
| 600 |
} else if len(initial) > 0 { |
| 601 |
if len(initial[0].Errors) > 0 { |
| 602 |
fails = true |
| 603 |
} else if c := constant(initial[0], "Name"); c != nil { |
| 604 |
got = c.Val().String() |
| 605 |
} |
| 606 |
} |
| 607 |
if got != test.want { |
| 608 |
t.Errorf("dir %q, pattern %q: got %s, want %s", |
| 609 |
test.dir, test.pattern, got, test.want) |
| 610 |
} |
| 611 |
if fails != test.fails { |
| 612 |
t.Errorf("dir %q, pattern %q: error %v, want %v", |
| 613 |
test.dir, test.pattern, fails, test.fails) |
| 614 |
} |
| 615 |
} |
| 616 |
} |
| 617 |
|
| 618 |
func TestConfigFlags(t *testing.T) { testAllOrModulesParallel(t, testConfigFlags) } |
| 619 |
func testConfigFlags(t *testing.T, exporter packagestest.Exporter) { |
| 620 |
// Test satisfying +build line tags, with -tags flag. |
| 621 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 622 |
Name: "golang.org/fake", |
| 623 |
Files: map[string]any{ |
| 624 |
// package a |
| 625 |
"a/a.go": `package a; import _ "golang.org/fake/a/b"`, |
| 626 |
"a/b.go": `// +build tag |
| 627 |
|
| 628 |
package a`, |
| 629 |
"a/c.go": `// +build tag tag2 |
| 630 |
|
| 631 |
package a`, |
| 632 |
"a/d.go": `// +build tag,tag2 |
| 633 |
|
| 634 |
package a`, |
| 635 |
// package a/b |
| 636 |
"a/b/a.go": `package b`, |
| 637 |
"a/b/b.go": `// +build tag |
| 638 |
|
| 639 |
package b`, |
| 640 |
}}}) |
| 641 |
defer exported.Cleanup() |
| 642 |
|
| 643 |
for _, test := range []struct { |
| 644 |
pattern string |
| 645 |
tags []string |
| 646 |
wantSrcs string |
| 647 |
wantImportSrcs string |
| 648 |
}{ |
| 649 |
{`golang.org/fake/a`, []string{}, "a.go", "a.go"}, |
| 650 |
{`golang.org/fake/a`, []string{`-tags=tag`}, "a.go b.go c.go", "a.go b.go"}, |
| 651 |
{`golang.org/fake/a`, []string{`-tags=tag2`}, "a.go c.go", "a.go"}, |
| 652 |
{`golang.org/fake/a`, []string{`-tags=tag tag2`}, "a.go b.go c.go d.go", "a.go b.go"}, |
| 653 |
} { |
| 654 |
exported.Config.Mode = packages.LoadImports |
| 655 |
exported.Config.BuildFlags = test.tags |
| 656 |
|
| 657 |
initial, err := packages.Load(exported.Config, test.pattern) |
| 658 |
if err != nil { |
| 659 |
t.Error(err) |
| 660 |
continue |
| 661 |
} |
| 662 |
if len(initial) != 1 { |
| 663 |
t.Errorf("test tags %v: pattern %s, expected 1 package, got %d packages.", test.tags, test.pattern, len(initial)) |
| 664 |
continue |
| 665 |
} |
| 666 |
pkg := initial[0] |
| 667 |
if srcs := strings.Join(srcs(pkg), " "); srcs != test.wantSrcs { |
| 668 |
t.Errorf("test tags %v: srcs of package %s = [%s], want [%s]", test.tags, test.pattern, srcs, test.wantSrcs) |
| 669 |
} |
| 670 |
for path, ipkg := range pkg.Imports { |
| 671 |
if srcs := strings.Join(srcs(ipkg), " "); srcs != test.wantImportSrcs { |
| 672 |
t.Errorf("build tags %v: srcs of imported package %s = [%s], want [%s]", test.tags, path, srcs, test.wantImportSrcs) |
| 673 |
} |
| 674 |
} |
| 675 |
|
| 676 |
} |
| 677 |
} |
| 678 |
|
| 679 |
func TestLoadTypes(t *testing.T) { testAllOrModulesParallel(t, testLoadTypes) } |
| 680 |
func testLoadTypes(t *testing.T, exporter packagestest.Exporter) { |
| 681 |
// In LoadTypes and LoadSyntax modes, the compiler will |
| 682 |
// fail to generate an export data file for c, because it has |
| 683 |
// a type error. The loader should fall back loading a and c |
| 684 |
// from source, but use the export data for b. |
| 685 |
|
| 686 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 687 |
Name: "golang.org/fake", |
| 688 |
Files: map[string]any{ |
| 689 |
"a/a.go": `package a; import "golang.org/fake/b"; import "golang.org/fake/c"; const A = "a" + b.B + c.C`, |
| 690 |
"b/b.go": `package b; const B = "b"`, |
| 691 |
"c/c.go": `package c; const C = "c" + 1`, |
| 692 |
}}}) |
| 693 |
defer exported.Cleanup() |
| 694 |
|
| 695 |
exported.Config.Mode = packages.LoadTypes |
| 696 |
initial, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 697 |
if err != nil { |
| 698 |
t.Fatal(err) |
| 699 |
} |
| 700 |
|
| 701 |
graph, all := importGraph(initial) |
| 702 |
wantGraph := ` |
| 703 |
* golang.org/fake/a |
| 704 |
golang.org/fake/b |
| 705 |
golang.org/fake/c |
| 706 |
golang.org/fake/a -> golang.org/fake/b |
| 707 |
golang.org/fake/a -> golang.org/fake/c |
| 708 |
`[1:] |
| 709 |
if graph != wantGraph { |
| 710 |
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph) |
| 711 |
} |
| 712 |
|
| 713 |
for _, id := range []string{ |
| 714 |
"golang.org/fake/a", |
| 715 |
"golang.org/fake/b", |
| 716 |
"golang.org/fake/c", |
| 717 |
} { |
| 718 |
p := all[id] |
| 719 |
if p == nil { |
| 720 |
t.Errorf("missing package: %s", id) |
| 721 |
continue |
| 722 |
} |
| 723 |
if p.Types == nil { |
| 724 |
t.Errorf("missing types.Package for %s", p) |
| 725 |
continue |
| 726 |
} else if !p.Types.Complete() { |
| 727 |
t.Errorf("incomplete types.Package for %s", p) |
| 728 |
} else if p.TypesSizes == nil { |
| 729 |
t.Errorf("TypesSizes is not filled in for %s", p) |
| 730 |
} |
| 731 |
|
| 732 |
} |
| 733 |
} |
| 734 |
|
| 735 |
// TestLoadTypesBits is equivalent to TestLoadTypes except that it only requests |
| 736 |
// the types using the NeedTypes bit. |
| 737 |
func TestLoadTypesBits(t *testing.T) { testAllOrModulesParallel(t, testLoadTypesBits) } |
| 738 |
func testLoadTypesBits(t *testing.T, exporter packagestest.Exporter) { |
| 739 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 740 |
Name: "golang.org/fake", |
| 741 |
Files: map[string]any{ |
| 742 |
"a/a.go": `package a; import "golang.org/fake/b"; const A = "a" + b.B`, |
| 743 |
"b/b.go": `package b; import "golang.org/fake/c"; const B = "b" + c.C`, |
| 744 |
"c/c.go": `package c; import "golang.org/fake/d"; const C = "c" + d.D`, |
| 745 |
"d/d.go": `package d; import "golang.org/fake/e"; const D = "d" + e.E`, |
| 746 |
"e/e.go": `package e; import "golang.org/fake/f"; const E = "e" + f.F`, |
| 747 |
"f/f.go": `package f; const F = "f"`, |
| 748 |
}}}) |
| 749 |
defer exported.Cleanup() |
| 750 |
|
| 751 |
exported.Config.Mode = packages.NeedTypes | packages.NeedImports |
| 752 |
initial, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/c") |
| 753 |
if err != nil { |
| 754 |
t.Fatal(err) |
| 755 |
} |
| 756 |
|
| 757 |
graph, all := importGraph(initial) |
| 758 |
wantGraph := ` |
| 759 |
* golang.org/fake/a |
| 760 |
golang.org/fake/b |
| 761 |
* golang.org/fake/c |
| 762 |
golang.org/fake/d |
| 763 |
golang.org/fake/e |
| 764 |
golang.org/fake/f |
| 765 |
golang.org/fake/a -> golang.org/fake/b |
| 766 |
golang.org/fake/b -> golang.org/fake/c |
| 767 |
golang.org/fake/c -> golang.org/fake/d |
| 768 |
golang.org/fake/d -> golang.org/fake/e |
| 769 |
golang.org/fake/e -> golang.org/fake/f |
| 770 |
`[1:] |
| 771 |
if graph != wantGraph { |
| 772 |
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph) |
| 773 |
} |
| 774 |
|
| 775 |
for _, test := range []struct { |
| 776 |
id string |
| 777 |
}{ |
| 778 |
{"golang.org/fake/a"}, |
| 779 |
{"golang.org/fake/b"}, |
| 780 |
{"golang.org/fake/c"}, |
| 781 |
{"golang.org/fake/d"}, |
| 782 |
{"golang.org/fake/e"}, |
| 783 |
{"golang.org/fake/f"}, |
| 784 |
} { |
| 785 |
p := all[test.id] |
| 786 |
if p == nil { |
| 787 |
t.Errorf("missing package: %s", test.id) |
| 788 |
continue |
| 789 |
} |
| 790 |
if p.Types == nil { |
| 791 |
t.Errorf("missing types.Package for %s", p) |
| 792 |
continue |
| 793 |
} |
| 794 |
// We don't request the syntax, so we shouldn't get it. |
| 795 |
if p.Syntax != nil { |
| 796 |
t.Errorf("Syntax unexpectedly provided for %s", p) |
| 797 |
} |
| 798 |
if p.Errors != nil { |
| 799 |
t.Errorf("errors in package: %s: %s", p, p.Errors) |
| 800 |
} |
| 801 |
} |
| 802 |
|
| 803 |
// Check value of constant. |
| 804 |
aA := constant(all["golang.org/fake/a"], "A") |
| 805 |
if aA == nil { |
| 806 |
t.Fatalf("a.A: got nil") |
| 807 |
} |
| 808 |
if got, want := fmt.Sprintf("%v %v", aA, aA.Val()), `const golang.org/fake/a.A untyped string "abcdef"`; got != want { |
| 809 |
t.Errorf("a.A: got %s, want %s", got, want) |
| 810 |
} |
| 811 |
} |
| 812 |
|
| 813 |
func TestLoadSyntaxOK(t *testing.T) { testAllOrModulesParallel(t, testLoadSyntaxOK) } |
| 814 |
func testLoadSyntaxOK(t *testing.T, exporter packagestest.Exporter) { |
| 815 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 816 |
Name: "golang.org/fake", |
| 817 |
Files: map[string]any{ |
| 818 |
"a/a.go": `package a; import "golang.org/fake/b"; const A = "a" + b.B`, |
| 819 |
"b/b.go": `package b; import "golang.org/fake/c"; const B = "b" + c.C`, |
| 820 |
"c/c.go": `package c; import "golang.org/fake/d"; const C = "c" + d.D`, |
| 821 |
"d/d.go": `package d; import "golang.org/fake/e"; const D = "d" + e.E`, |
| 822 |
"e/e.go": `package e; import "golang.org/fake/f"; const E = "e" + f.F`, |
| 823 |
"f/f.go": `package f; const F = "f"`, |
| 824 |
}}}) |
| 825 |
defer exported.Cleanup() |
| 826 |
|
| 827 |
exported.Config.Mode = packages.LoadSyntax |
| 828 |
initial, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/c") |
| 829 |
if err != nil { |
| 830 |
t.Fatal(err) |
| 831 |
} |
| 832 |
|
| 833 |
graph, all := importGraph(initial) |
| 834 |
wantGraph := ` |
| 835 |
* golang.org/fake/a |
| 836 |
golang.org/fake/b |
| 837 |
* golang.org/fake/c |
| 838 |
golang.org/fake/d |
| 839 |
golang.org/fake/e |
| 840 |
golang.org/fake/f |
| 841 |
golang.org/fake/a -> golang.org/fake/b |
| 842 |
golang.org/fake/b -> golang.org/fake/c |
| 843 |
golang.org/fake/c -> golang.org/fake/d |
| 844 |
golang.org/fake/d -> golang.org/fake/e |
| 845 |
golang.org/fake/e -> golang.org/fake/f |
| 846 |
`[1:] |
| 847 |
if graph != wantGraph { |
| 848 |
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph) |
| 849 |
} |
| 850 |
|
| 851 |
for _, test := range []struct { |
| 852 |
id string |
| 853 |
wantSyntax bool |
| 854 |
wantComplete bool |
| 855 |
}{ |
| 856 |
{"golang.org/fake/a", true, true}, // source package |
| 857 |
{"golang.org/fake/b", true, true}, // source package because depends on initial package |
| 858 |
{"golang.org/fake/c", true, true}, // source package |
| 859 |
{"golang.org/fake/d", false, true}, // export data package |
| 860 |
{"golang.org/fake/e", false, false}, // export data package |
| 861 |
{"golang.org/fake/f", false, false}, // export data package |
| 862 |
} { |
| 863 |
// TODO(matloob): LoadSyntax and LoadAllSyntax are now equivalent, wantSyntax and wantComplete |
| 864 |
// are true for all packages in the transitive dependency set. Add test cases on the individual |
| 865 |
// Need* fields to check the equivalents on the new API. |
| 866 |
p := all[test.id] |
| 867 |
if p == nil { |
| 868 |
t.Errorf("missing package: %s", test.id) |
| 869 |
continue |
| 870 |
} |
| 871 |
if p.Types == nil { |
| 872 |
t.Errorf("missing types.Package for %s", p) |
| 873 |
continue |
| 874 |
} else if p.Types.Complete() != test.wantComplete { |
| 875 |
if test.wantComplete { |
| 876 |
t.Errorf("incomplete types.Package for %s", p) |
| 877 |
} else { |
| 878 |
t.Errorf("unexpected complete types.Package for %s", p) |
| 879 |
} |
| 880 |
} |
| 881 |
if (p.Syntax != nil) != test.wantSyntax { |
| 882 |
if test.wantSyntax { |
| 883 |
t.Errorf("missing ast.Files for %s", p) |
| 884 |
} else { |
| 885 |
t.Errorf("unexpected ast.Files for for %s", p) |
| 886 |
} |
| 887 |
} |
| 888 |
if p.Errors != nil { |
| 889 |
t.Errorf("errors in package: %s: %s", p, p.Errors) |
| 890 |
} |
| 891 |
} |
| 892 |
|
| 893 |
// Check value of constant. |
| 894 |
aA := constant(all["golang.org/fake/a"], "A") |
| 895 |
if aA == nil { |
| 896 |
t.Fatalf("a.A: got nil") |
| 897 |
} |
| 898 |
if got, want := fmt.Sprintf("%v %v", aA, aA.Val()), `const golang.org/fake/a.A untyped string "abcdef"`; got != want { |
| 899 |
t.Errorf("a.A: got %s, want %s", got, want) |
| 900 |
} |
| 901 |
} |
| 902 |
|
| 903 |
func TestLoadDiamondTypes(t *testing.T) { testAllOrModulesParallel(t, testLoadDiamondTypes) } |
| 904 |
func testLoadDiamondTypes(t *testing.T, exporter packagestest.Exporter) { |
| 905 |
// We make a diamond dependency and check the type d.D is the same through both paths |
| 906 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 907 |
Name: "golang.org/fake", |
| 908 |
Files: map[string]any{ |
| 909 |
"a/a.go": `package a; import ("golang.org/fake/b"; "golang.org/fake/c"); var _ = b.B == c.C`, |
| 910 |
"b/b.go": `package b; import "golang.org/fake/d"; var B d.D`, |
| 911 |
"c/c.go": `package c; import "golang.org/fake/d"; var C d.D`, |
| 912 |
"d/d.go": `package d; type D int`, |
| 913 |
}}}) |
| 914 |
defer exported.Cleanup() |
| 915 |
|
| 916 |
exported.Config.Mode = packages.LoadSyntax |
| 917 |
initial, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 918 |
if err != nil { |
| 919 |
t.Fatal(err) |
| 920 |
} |
| 921 |
for pkg := range packages.Postorder(initial) { |
| 922 |
for _, err := range pkg.Errors { |
| 923 |
t.Errorf("package %s: %v", pkg.ID, err) |
| 924 |
} |
| 925 |
} |
| 926 |
|
| 927 |
graph, _ := importGraph(initial) |
| 928 |
wantGraph := ` |
| 929 |
* golang.org/fake/a |
| 930 |
golang.org/fake/b |
| 931 |
golang.org/fake/c |
| 932 |
golang.org/fake/d |
| 933 |
golang.org/fake/a -> golang.org/fake/b |
| 934 |
golang.org/fake/a -> golang.org/fake/c |
| 935 |
golang.org/fake/b -> golang.org/fake/d |
| 936 |
golang.org/fake/c -> golang.org/fake/d |
| 937 |
`[1:] |
| 938 |
if graph != wantGraph { |
| 939 |
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph) |
| 940 |
} |
| 941 |
} |
| 942 |
|
| 943 |
func TestLoadSyntaxError(t *testing.T) { testAllOrModulesParallel(t, testLoadSyntaxError) } |
| 944 |
func testLoadSyntaxError(t *testing.T, exporter packagestest.Exporter) { |
| 945 |
// A type error in a lower-level package (e) prevents go list |
| 946 |
// from producing export data for all packages that depend on it |
| 947 |
// [a-e]. Only f should be loaded from export data, and the rest |
| 948 |
// should be IllTyped. |
| 949 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 950 |
Name: "golang.org/fake", |
| 951 |
Files: map[string]any{ |
| 952 |
"a/a.go": `package a; import "golang.org/fake/b"; const A = "a" + b.B`, |
| 953 |
"b/b.go": `package b; import "golang.org/fake/c"; const B = "b" + c.C`, |
| 954 |
"c/c.go": `package c; import "golang.org/fake/d"; const C = "c" + d.D`, |
| 955 |
"d/d.go": `package d; import "golang.org/fake/e"; const D = "d" + e.E`, |
| 956 |
"e/e.go": `package e; import "golang.org/fake/f"; const E = "e" + f.F + 1`, // type error |
| 957 |
"f/f.go": `package f; const F = "f"`, |
| 958 |
}}}) |
| 959 |
defer exported.Cleanup() |
| 960 |
|
| 961 |
exported.Config.Mode = packages.LoadSyntax |
| 962 |
initial, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/c") |
| 963 |
if err != nil { |
| 964 |
t.Fatal(err) |
| 965 |
} |
| 966 |
|
| 967 |
all := make(map[string]*packages.Package) |
| 968 |
for p := range packages.Postorder(initial) { |
| 969 |
all[p.ID] = p |
| 970 |
} |
| 971 |
|
| 972 |
for _, test := range []struct { |
| 973 |
id string |
| 974 |
wantSyntax bool |
| 975 |
wantIllTyped bool |
| 976 |
}{ |
| 977 |
{"golang.org/fake/a", true, true}, |
| 978 |
{"golang.org/fake/b", true, true}, |
| 979 |
{"golang.org/fake/c", true, true}, |
| 980 |
{"golang.org/fake/d", true, true}, |
| 981 |
{"golang.org/fake/e", true, true}, |
| 982 |
{"golang.org/fake/f", false, false}, |
| 983 |
} { |
| 984 |
p := all[test.id] |
| 985 |
if p == nil { |
| 986 |
t.Errorf("missing package: %s", test.id) |
| 987 |
continue |
| 988 |
} |
| 989 |
if p.Types == nil { |
| 990 |
t.Errorf("missing types.Package for %s", p) |
| 991 |
continue |
| 992 |
} else if !p.Types.Complete() { |
| 993 |
t.Errorf("incomplete types.Package for %s", p) |
| 994 |
} |
| 995 |
if (p.Syntax != nil) != test.wantSyntax { |
| 996 |
if test.wantSyntax { |
| 997 |
t.Errorf("missing ast.Files for %s", test.id) |
| 998 |
} else { |
| 999 |
t.Errorf("unexpected ast.Files for for %s", test.id) |
| 1000 |
} |
| 1001 |
} |
| 1002 |
if p.IllTyped != test.wantIllTyped { |
| 1003 |
t.Errorf("IllTyped was %t for %s", p.IllTyped, test.id) |
| 1004 |
} |
| 1005 |
} |
| 1006 |
|
| 1007 |
// Check value of constant. |
| 1008 |
aA := constant(all["golang.org/fake/a"], "A") |
| 1009 |
if aA == nil { |
| 1010 |
t.Fatalf("a.A: got nil") |
| 1011 |
} |
| 1012 |
if got, want := aA.String(), `const golang.org/fake/a.A invalid type`; got != want { |
| 1013 |
t.Errorf("a.A: got %s, want %s", got, want) |
| 1014 |
} |
| 1015 |
} |
| 1016 |
|
| 1017 |
// This function tests use of the ParseFile hook to modify |
| 1018 |
// the AST after parsing. |
| 1019 |
func TestParseFileModifyAST(t *testing.T) { testAllOrModulesParallel(t, testParseFileModifyAST) } |
| 1020 |
func testParseFileModifyAST(t *testing.T, exporter packagestest.Exporter) { |
| 1021 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1022 |
Name: "golang.org/fake", |
| 1023 |
Files: map[string]any{ |
| 1024 |
"a/a.go": `package a; const A = "a" `, |
| 1025 |
}}}) |
| 1026 |
defer exported.Cleanup() |
| 1027 |
|
| 1028 |
exported.Config.Mode = packages.LoadAllSyntax |
| 1029 |
exported.Config.ParseFile = func(fset *token.FileSet, filename string, src []byte) (*ast.File, error) { |
| 1030 |
const mode = parser.AllErrors | parser.ParseComments |
| 1031 |
f, err := parser.ParseFile(fset, filename, src, mode) |
| 1032 |
// modify AST to change `const A = "a"` to `const A = "b"` |
| 1033 |
spec := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec) |
| 1034 |
spec.Values[0].(*ast.BasicLit).Value = `"b"` |
| 1035 |
return f, err |
| 1036 |
} |
| 1037 |
initial, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 1038 |
if err != nil { |
| 1039 |
t.Error(err) |
| 1040 |
} |
| 1041 |
|
| 1042 |
// Check value of a.A has been set to "b" |
| 1043 |
a := initial[0] |
| 1044 |
got := constant(a, "A").Val().String() |
| 1045 |
if got != `"b"` { |
| 1046 |
t.Errorf("a.A: got %s, want %s", got, `"b"`) |
| 1047 |
} |
| 1048 |
} |
| 1049 |
|
| 1050 |
func TestAdHocPackagesBadImport(t *testing.T) { |
| 1051 |
t.Parallel() |
| 1052 |
testenv.NeedsTool(t, "go") |
| 1053 |
|
| 1054 |
// This test doesn't use packagestest because we are testing ad-hoc packages, |
| 1055 |
// which are outside of $GOPATH and outside of a module. |
| 1056 |
tmp, err := os.MkdirTemp("", "a") |
| 1057 |
if err != nil { |
| 1058 |
t.Fatal(err) |
| 1059 |
} |
| 1060 |
defer os.RemoveAll(tmp) |
| 1061 |
|
| 1062 |
filename := filepath.Join(tmp, "a.go") |
| 1063 |
content := []byte(`package a |
| 1064 |
import _ "badimport" |
| 1065 |
const A = 1 |
| 1066 |
`) |
| 1067 |
if err := os.WriteFile(filename, content, 0775); err != nil { |
| 1068 |
t.Fatal(err) |
| 1069 |
} |
| 1070 |
|
| 1071 |
// Make sure that the user's value of GO111MODULE does not affect test results. |
| 1072 |
for _, go111module := range []string{"off", "auto", "on"} { |
| 1073 |
config := &packages.Config{ |
| 1074 |
Env: append(os.Environ(), "GOPACKAGESDRIVER=off", fmt.Sprintf("GO111MODULE=%s", go111module)), |
| 1075 |
Dir: tmp, |
| 1076 |
Mode: packages.LoadAllSyntax, |
| 1077 |
Logf: t.Logf, |
| 1078 |
} |
| 1079 |
initial, err := packages.Load(config, fmt.Sprintf("file=%s", filename)) |
| 1080 |
if err != nil { |
| 1081 |
t.Error(err) |
| 1082 |
} |
| 1083 |
if len(initial) == 0 { |
| 1084 |
t.Fatalf("no packages for %s with GO111MODULE=%s", filename, go111module) |
| 1085 |
} |
| 1086 |
// Check value of a.A. |
| 1087 |
a := initial[0] |
| 1088 |
// There's an error because there's a bad import. |
| 1089 |
aA := constant(a, "A") |
| 1090 |
if aA == nil { |
| 1091 |
t.Errorf("a.A: got nil") |
| 1092 |
return |
| 1093 |
} |
| 1094 |
got := aA.Val().String() |
| 1095 |
if want := "1"; got != want { |
| 1096 |
t.Errorf("a.A: got %s, want %s", got, want) |
| 1097 |
} |
| 1098 |
} |
| 1099 |
} |
| 1100 |
|
| 1101 |
func TestLoadAllSyntaxImportErrors(t *testing.T) { |
| 1102 |
testAllOrModulesParallel(t, testLoadAllSyntaxImportErrors) |
| 1103 |
} |
| 1104 |
func testLoadAllSyntaxImportErrors(t *testing.T, exporter packagestest.Exporter) { |
| 1105 |
// TODO(matloob): Remove this once go list -e -compiled is fixed. |
| 1106 |
// See https://golang.org/issue/26755 |
| 1107 |
t.Skip("go list -compiled -e fails with non-zero exit status for empty packages") |
| 1108 |
|
| 1109 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1110 |
Name: "golang.org/fake", |
| 1111 |
Files: map[string]any{ |
| 1112 |
"unicycle/unicycle.go": `package unicycle; import _ "unicycle"`, |
| 1113 |
"bicycle1/bicycle1.go": `package bicycle1; import _ "bicycle2"`, |
| 1114 |
"bicycle2/bicycle2.go": `package bicycle2; import _ "bicycle1"`, |
| 1115 |
"bad/bad.go": `not a package declaration`, |
| 1116 |
"empty/README.txt": `not a go file`, |
| 1117 |
"root/root.go": `package root |
| 1118 |
import ( |
| 1119 |
_ "bicycle1" |
| 1120 |
_ "unicycle" |
| 1121 |
_ "nonesuch" |
| 1122 |
_ "empty" |
| 1123 |
_ "bad" |
| 1124 |
)`, |
| 1125 |
}}}) |
| 1126 |
defer exported.Cleanup() |
| 1127 |
|
| 1128 |
exported.Config.Mode = packages.LoadAllSyntax |
| 1129 |
initial, err := packages.Load(exported.Config, "root") |
| 1130 |
if err != nil { |
| 1131 |
t.Fatal(err) |
| 1132 |
} |
| 1133 |
|
| 1134 |
// Cycle-forming edges are removed from the graph: |
| 1135 |
// bicycle2 -> bicycle1 |
| 1136 |
// unicycle -> unicycle |
| 1137 |
graph, all := importGraph(initial) |
| 1138 |
wantGraph := ` |
| 1139 |
bicycle1 |
| 1140 |
bicycle2 |
| 1141 |
* root |
| 1142 |
unicycle |
| 1143 |
bicycle1 -> bicycle2 |
| 1144 |
root -> bicycle1 |
| 1145 |
root -> unicycle |
| 1146 |
`[1:] |
| 1147 |
if graph != wantGraph { |
| 1148 |
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph) |
| 1149 |
} |
| 1150 |
for _, test := range []struct { |
| 1151 |
id string |
| 1152 |
wantErrs []string |
| 1153 |
}{ |
| 1154 |
{"bicycle1", nil}, |
| 1155 |
{"bicycle2", []string{ |
| 1156 |
"could not import bicycle1 (import cycle: [root bicycle1 bicycle2])", |
| 1157 |
}}, |
| 1158 |
{"unicycle", []string{ |
| 1159 |
"could not import unicycle (import cycle: [root unicycle])", |
| 1160 |
}}, |
| 1161 |
{"root", []string{ |
| 1162 |
`could not import bad (missing package: "bad")`, |
| 1163 |
`could not import empty (missing package: "empty")`, |
| 1164 |
`could not import nonesuch (missing package: "nonesuch")`, |
| 1165 |
}}, |
| 1166 |
} { |
| 1167 |
p := all[test.id] |
| 1168 |
if p == nil { |
| 1169 |
t.Errorf("missing package: %s", test.id) |
| 1170 |
continue |
| 1171 |
} |
| 1172 |
if p.Types == nil { |
| 1173 |
t.Errorf("missing types.Package for %s", test.id) |
| 1174 |
} |
| 1175 |
if p.Syntax == nil { |
| 1176 |
t.Errorf("missing ast.Files for %s", test.id) |
| 1177 |
} |
| 1178 |
if !p.IllTyped { |
| 1179 |
t.Errorf("IllTyped was false for %s", test.id) |
| 1180 |
} |
| 1181 |
if errs := errorMessages(p.Errors); !reflect.DeepEqual(errs, test.wantErrs) { |
| 1182 |
t.Errorf("in package %s, got errors %s, want %s", p, errs, test.wantErrs) |
| 1183 |
} |
| 1184 |
} |
| 1185 |
} |
| 1186 |
|
| 1187 |
func TestAbsoluteFilenames(t *testing.T) { testAllOrModulesParallel(t, testAbsoluteFilenames) } |
| 1188 |
func testAbsoluteFilenames(t *testing.T, exporter packagestest.Exporter) { |
| 1189 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1190 |
Name: "golang.org/fake", |
| 1191 |
Files: map[string]any{ |
| 1192 |
"a/a.go": `package a; const A = 1`, |
| 1193 |
"b/b.go": `package b; import ("golang.org/fake/a"; _ "errors"); var B = a.A`, |
| 1194 |
"b/vendor/a/a.go": `package a; const A = 1`, |
| 1195 |
"c/c.go": `package c; import (_ "golang.org/fake/b"; _ "unsafe")`, |
| 1196 |
"c/c2.go": "// +build ignore\n\n" + `package c; import _ "fmt"`, |
| 1197 |
"subdir/d/d.go": `package d`, |
| 1198 |
"subdir/e/d.go": `package e`, |
| 1199 |
"e/e.go": `package main; import _ "golang.org/fake/b"`, |
| 1200 |
"e/e2.go": `package main; import _ "golang.org/fake/c"`, |
| 1201 |
"f/f.go": `package f`, |
| 1202 |
"f/f.s": ``, |
| 1203 |
"g/g.go": `package g; import _ "embed";` + "\n//go:embed g2.txt\n" + `var s string`, |
| 1204 |
"g/g2.txt": "hello", |
| 1205 |
"h/h.go": `package g; import _ "embed";` + "\n//go:embed a*.txt\n" + `var s string`, |
| 1206 |
"h/aa.txt": "hello", |
| 1207 |
}}}) |
| 1208 |
defer exported.Cleanup() |
| 1209 |
exported.Config.Dir = filepath.Dir(filepath.Dir(exported.File("golang.org/fake", "a/a.go"))) |
| 1210 |
|
| 1211 |
checkFile := func(filename string) { |
| 1212 |
if !filepath.IsAbs(filename) { |
| 1213 |
t.Errorf("filename is not absolute: %s", filename) |
| 1214 |
} |
| 1215 |
if _, err := os.Stat(filename); err != nil { |
| 1216 |
t.Errorf("stat error, %s: %v", filename, err) |
| 1217 |
} |
| 1218 |
} |
| 1219 |
|
| 1220 |
for _, test := range []struct { |
| 1221 |
pattern string |
| 1222 |
want string |
| 1223 |
}{ |
| 1224 |
// Import paths |
| 1225 |
{"golang.org/fake/a", "a.go"}, |
| 1226 |
{"golang.org/fake/b/vendor/a", "a.go"}, |
| 1227 |
{"golang.org/fake/b", "b.go"}, |
| 1228 |
{"golang.org/fake/c", "c.go"}, |
| 1229 |
{"golang.org/fake/subdir/d", "d.go"}, |
| 1230 |
{"golang.org/fake/subdir/e", "d.go"}, |
| 1231 |
{"golang.org/fake/e", "e.go e2.go"}, |
| 1232 |
{"golang.org/fake/f", "f.go f.s"}, |
| 1233 |
{"golang.org/fake/g", "g.go g2.txt"}, |
| 1234 |
{"golang.org/fake/h", "h.go aa.txt"}, |
| 1235 |
// Relative paths |
| 1236 |
{"./a", "a.go"}, |
| 1237 |
{"./b/vendor/a", "a.go"}, |
| 1238 |
{"./b", "b.go"}, |
| 1239 |
{"./c", "c.go"}, |
| 1240 |
{"./subdir/d", "d.go"}, |
| 1241 |
{"./subdir/e", "d.go"}, |
| 1242 |
{"./e", "e.go e2.go"}, |
| 1243 |
{"./f", "f.go f.s"}, |
| 1244 |
{"./g", "g.go g2.txt"}, |
| 1245 |
{"./h", "h.go aa.txt"}, |
| 1246 |
} { |
| 1247 |
exported.Config.Mode = packages.LoadFiles | packages.NeedEmbedFiles |
| 1248 |
pkgs, err := packages.Load(exported.Config, test.pattern) |
| 1249 |
if err != nil { |
| 1250 |
t.Errorf("pattern %s: %v", test.pattern, err) |
| 1251 |
continue |
| 1252 |
} |
| 1253 |
|
| 1254 |
if got := strings.Join(srcs(pkgs[0]), " "); got != test.want { |
| 1255 |
t.Errorf("in package %s, got %s, want %s", test.pattern, got, test.want) |
| 1256 |
} |
| 1257 |
|
| 1258 |
// Test that files in all packages exist and are absolute paths. |
| 1259 |
_, all := importGraph(pkgs) |
| 1260 |
for _, pkg := range all { |
| 1261 |
for _, filename := range pkg.GoFiles { |
| 1262 |
checkFile(filename) |
| 1263 |
} |
| 1264 |
for _, filename := range pkg.OtherFiles { |
| 1265 |
checkFile(filename) |
| 1266 |
} |
| 1267 |
for _, filename := range pkg.EmbedFiles { |
| 1268 |
checkFile(filename) |
| 1269 |
} |
| 1270 |
for _, filename := range pkg.IgnoredFiles { |
| 1271 |
checkFile(filename) |
| 1272 |
} |
| 1273 |
} |
| 1274 |
} |
| 1275 |
} |
| 1276 |
|
| 1277 |
func TestContains(t *testing.T) { testAllOrModulesParallel(t, testContains) } |
| 1278 |
func testContains(t *testing.T, exporter packagestest.Exporter) { |
| 1279 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1280 |
Name: "golang.org/fake", |
| 1281 |
Files: map[string]any{ |
| 1282 |
"a/a.go": `package a; import "golang.org/fake/b"`, |
| 1283 |
"b/b.go": `package b; import "golang.org/fake/c"`, |
| 1284 |
"c/c.go": `package c`, |
| 1285 |
}}}) |
| 1286 |
defer exported.Cleanup() |
| 1287 |
bFile := exported.File("golang.org/fake", "b/b.go") |
| 1288 |
exported.Config.Mode = packages.LoadImports |
| 1289 |
initial, err := packages.Load(exported.Config, "file="+bFile) |
| 1290 |
if err != nil { |
| 1291 |
t.Fatal(err) |
| 1292 |
} |
| 1293 |
|
| 1294 |
graph, _ := importGraph(initial) |
| 1295 |
wantGraph := ` |
| 1296 |
* golang.org/fake/b |
| 1297 |
golang.org/fake/c |
| 1298 |
golang.org/fake/b -> golang.org/fake/c |
| 1299 |
`[1:] |
| 1300 |
if graph != wantGraph { |
| 1301 |
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph) |
| 1302 |
} |
| 1303 |
} |
| 1304 |
|
| 1305 |
// This test ensures that the effective GOARCH variable in the |
| 1306 |
// application determines the Sizes function used by the type checker. |
| 1307 |
// This behavior is a stop-gap until we make the build system's query |
| 1308 |
// tool report the correct sizes function for the actual configuration. |
| 1309 |
func TestSizes(t *testing.T) { testAllOrModulesParallel(t, testSizes) } |
| 1310 |
func testSizes(t *testing.T, exporter packagestest.Exporter) { |
| 1311 |
// Only run this test on operating systems that have both an amd64 and 386 port. |
| 1312 |
switch runtime.GOOS { |
| 1313 |
case "linux", "windows", "freebsd", "openbsd", "netbsd", "android": |
| 1314 |
default: |
| 1315 |
t.Skipf("skipping test on %s", runtime.GOOS) |
| 1316 |
} |
| 1317 |
|
| 1318 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1319 |
Name: "golang.org/fake", |
| 1320 |
Files: map[string]any{ |
| 1321 |
"a/a.go": `package a; import "unsafe"; const WordSize = 8*unsafe.Sizeof(int(0))`, |
| 1322 |
}}}) |
| 1323 |
defer exported.Cleanup() |
| 1324 |
|
| 1325 |
exported.Config.Mode = packages.LoadSyntax |
| 1326 |
savedEnv := exported.Config.Env |
| 1327 |
for arch, wantWordSize := range map[string]int64{"386": 32, "amd64": 64} { |
| 1328 |
exported.Config.Env = append(savedEnv, "GOARCH="+arch) |
| 1329 |
initial, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 1330 |
if err != nil { |
| 1331 |
t.Fatal(err) |
| 1332 |
} |
| 1333 |
if packages.PrintErrors(initial) > 0 { |
| 1334 |
t.Fatal("there were errors") |
| 1335 |
} |
| 1336 |
gotWordSize, _ := constantpkg.Int64Val(constant(initial[0], "WordSize").Val()) |
| 1337 |
if gotWordSize != wantWordSize { |
| 1338 |
t.Errorf("for GOARCH=%s, got word size %d, want %d", arch, gotWordSize, wantWordSize) |
| 1339 |
} |
| 1340 |
} |
| 1341 |
} |
| 1342 |
|
| 1343 |
// This is a regression test for a bug related to |
| 1344 |
// github.com/golang/vscode-go/issues/3021: if types are needed (any |
| 1345 |
// of NeedTypes{,Info,Sizes} and the types.Sizes cannot be obtained |
| 1346 |
// (e.g. due to a bad GOARCH) then the Load operation must fail. It |
| 1347 |
// must not return a nil TypesSizes, or use the default (wrong) size. |
| 1348 |
// (The root cause of that issue turned out to be due to skew in the |
| 1349 |
// Bazel GOPACKAGESDRIVER; see CL 537876.) |
| 1350 |
// |
| 1351 |
// We use a file=... query because it suppresses the bad-GOARCH check |
| 1352 |
// that the go command would otherwise perform eagerly. |
| 1353 |
// (Gopls relies on this as a fallback.) |
| 1354 |
func TestNeedTypeSizesWithBadGOARCH(t *testing.T) { |
| 1355 |
testAllOrModulesParallel(t, func(t *testing.T, exporter packagestest.Exporter) { |
| 1356 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1357 |
Name: "testdata", |
| 1358 |
Files: map[string]any{"a/a.go": `package a`}}}) |
| 1359 |
defer exported.Cleanup() |
| 1360 |
|
| 1361 |
exported.Config.Mode = packages.NeedTypesSizes // or {,Info,Sizes} |
| 1362 |
exported.Config.Env = append(exported.Config.Env, "GOARCH=286") |
| 1363 |
_, err := packages.Load(exported.Config, "file=./a/a.go") |
| 1364 |
got := fmt.Sprint(err) |
| 1365 |
want := "can't determine type sizes" |
| 1366 |
if !strings.Contains(got, want) { |
| 1367 |
t.Errorf("Load error %q does not contain substring %q", got, want) |
| 1368 |
} |
| 1369 |
}) |
| 1370 |
} |
| 1371 |
|
| 1372 |
// TestContainsFallbackSticks ensures that when there are both contains and non-contains queries |
| 1373 |
// the decision whether to fallback to the pre-1.11 go list sticks across both sets of calls to |
| 1374 |
// go list. |
| 1375 |
func TestContainsFallbackSticks(t *testing.T) { |
| 1376 |
testAllOrModulesParallel(t, testContainsFallbackSticks) |
| 1377 |
} |
| 1378 |
func testContainsFallbackSticks(t *testing.T, exporter packagestest.Exporter) { |
| 1379 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1380 |
Name: "golang.org/fake", |
| 1381 |
Files: map[string]any{ |
| 1382 |
"a/a.go": `package a; import "golang.org/fake/b"`, |
| 1383 |
"b/b.go": `package b; import "golang.org/fake/c"`, |
| 1384 |
"c/c.go": `package c`, |
| 1385 |
}}}) |
| 1386 |
defer exported.Cleanup() |
| 1387 |
|
| 1388 |
exported.Config.Mode = packages.LoadImports |
| 1389 |
bFile := exported.File("golang.org/fake", "b/b.go") |
| 1390 |
initial, err := packages.Load(exported.Config, "golang.org/fake/a", "file="+bFile) |
| 1391 |
if err != nil { |
| 1392 |
t.Fatal(err) |
| 1393 |
} |
| 1394 |
|
| 1395 |
graph, _ := importGraph(initial) |
| 1396 |
wantGraph := ` |
| 1397 |
* golang.org/fake/a |
| 1398 |
* golang.org/fake/b |
| 1399 |
golang.org/fake/c |
| 1400 |
golang.org/fake/a -> golang.org/fake/b |
| 1401 |
golang.org/fake/b -> golang.org/fake/c |
| 1402 |
`[1:] |
| 1403 |
if graph != wantGraph { |
| 1404 |
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph) |
| 1405 |
} |
| 1406 |
} |
| 1407 |
|
| 1408 |
// Test that Load with no patterns is equivalent to loading "." via the golist |
| 1409 |
// driver. |
| 1410 |
func TestNoPatterns(t *testing.T) { testAllOrModulesParallel(t, testNoPatterns) } |
| 1411 |
func testNoPatterns(t *testing.T, exporter packagestest.Exporter) { |
| 1412 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1413 |
Name: "golang.org/fake", |
| 1414 |
Files: map[string]any{ |
| 1415 |
"a/a.go": `package a;`, |
| 1416 |
"a/b/b.go": `package b;`, |
| 1417 |
}}}) |
| 1418 |
defer exported.Cleanup() |
| 1419 |
|
| 1420 |
aDir := filepath.Dir(exported.File("golang.org/fake", "a/a.go")) |
| 1421 |
exported.Config.Dir = aDir |
| 1422 |
|
| 1423 |
initial, err := packages.Load(exported.Config) |
| 1424 |
if err != nil { |
| 1425 |
t.Fatal(err) |
| 1426 |
} |
| 1427 |
if len(initial) != 1 || initial[0].Name != "a" { |
| 1428 |
t.Fatalf(`Load() = %v, wanted just the package in the current directory`, initial) |
| 1429 |
} |
| 1430 |
} |
| 1431 |
|
| 1432 |
func TestJSON(t *testing.T) { testAllOrModulesParallel(t, testJSON) } |
| 1433 |
func testJSON(t *testing.T, exporter packagestest.Exporter) { |
| 1434 |
// TODO: add in some errors |
| 1435 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1436 |
Name: "golang.org/fake", |
| 1437 |
Files: map[string]any{ |
| 1438 |
"a/a.go": `package a; const A = 1`, |
| 1439 |
"b/b.go": `package b; import "golang.org/fake/a"; var B = a.A`, |
| 1440 |
"c/c.go": `package c; import "golang.org/fake/b" ; var C = b.B`, |
| 1441 |
"d/d.go": `package d; import "golang.org/fake/b" ; var D = b.B`, |
| 1442 |
}}}) |
| 1443 |
defer exported.Cleanup() |
| 1444 |
|
| 1445 |
exported.Config.Mode = packages.LoadImports |
| 1446 |
initial, err := packages.Load(exported.Config, "golang.org/fake/c", "golang.org/fake/d") |
| 1447 |
if err != nil { |
| 1448 |
t.Fatal(err) |
| 1449 |
} |
| 1450 |
|
| 1451 |
// Visit and print all packages. |
| 1452 |
buf := &bytes.Buffer{} |
| 1453 |
enc := json.NewEncoder(buf) |
| 1454 |
enc.SetIndent("", "\t") |
| 1455 |
for pkg := range packages.Postorder(initial) { |
| 1456 |
// trim the source lists for stable results |
| 1457 |
pkg.GoFiles = cleanPaths(pkg.GoFiles) |
| 1458 |
pkg.CompiledGoFiles = cleanPaths(pkg.CompiledGoFiles) |
| 1459 |
pkg.OtherFiles = cleanPaths(pkg.OtherFiles) |
| 1460 |
pkg.IgnoredFiles = cleanPaths(pkg.IgnoredFiles) |
| 1461 |
if err := enc.Encode(pkg); err != nil { |
| 1462 |
t.Fatal(err) |
| 1463 |
} |
| 1464 |
} |
| 1465 |
|
| 1466 |
wantJSON := ` |
| 1467 |
{ |
| 1468 |
"ID": "golang.org/fake/a", |
| 1469 |
"Name": "a", |
| 1470 |
"PkgPath": "golang.org/fake/a", |
| 1471 |
"GoFiles": [ |
| 1472 |
"a.go" |
| 1473 |
], |
| 1474 |
"CompiledGoFiles": [ |
| 1475 |
"a.go" |
| 1476 |
] |
| 1477 |
} |
| 1478 |
{ |
| 1479 |
"ID": "golang.org/fake/b", |
| 1480 |
"Name": "b", |
| 1481 |
"PkgPath": "golang.org/fake/b", |
| 1482 |
"GoFiles": [ |
| 1483 |
"b.go" |
| 1484 |
], |
| 1485 |
"CompiledGoFiles": [ |
| 1486 |
"b.go" |
| 1487 |
], |
| 1488 |
"Imports": { |
| 1489 |
"golang.org/fake/a": "golang.org/fake/a" |
| 1490 |
} |
| 1491 |
} |
| 1492 |
{ |
| 1493 |
"ID": "golang.org/fake/c", |
| 1494 |
"Name": "c", |
| 1495 |
"PkgPath": "golang.org/fake/c", |
| 1496 |
"GoFiles": [ |
| 1497 |
"c.go" |
| 1498 |
], |
| 1499 |
"CompiledGoFiles": [ |
| 1500 |
"c.go" |
| 1501 |
], |
| 1502 |
"Imports": { |
| 1503 |
"golang.org/fake/b": "golang.org/fake/b" |
| 1504 |
} |
| 1505 |
} |
| 1506 |
{ |
| 1507 |
"ID": "golang.org/fake/d", |
| 1508 |
"Name": "d", |
| 1509 |
"PkgPath": "golang.org/fake/d", |
| 1510 |
"GoFiles": [ |
| 1511 |
"d.go" |
| 1512 |
], |
| 1513 |
"CompiledGoFiles": [ |
| 1514 |
"d.go" |
| 1515 |
], |
| 1516 |
"Imports": { |
| 1517 |
"golang.org/fake/b": "golang.org/fake/b" |
| 1518 |
} |
| 1519 |
} |
| 1520 |
`[1:] |
| 1521 |
|
| 1522 |
if buf.String() != wantJSON { |
| 1523 |
t.Errorf("wrong JSON: got <<%s>>, want <<%s>>", buf.String(), wantJSON) |
| 1524 |
} |
| 1525 |
// now decode it again |
| 1526 |
var decoded []*packages.Package |
| 1527 |
dec := json.NewDecoder(buf) |
| 1528 |
for dec.More() { |
| 1529 |
p := new(packages.Package) |
| 1530 |
if err := dec.Decode(p); err != nil { |
| 1531 |
t.Fatal(err) |
| 1532 |
} |
| 1533 |
decoded = append(decoded, p) |
| 1534 |
} |
| 1535 |
if len(decoded) != 4 { |
| 1536 |
t.Fatalf("got %d packages, want 4", len(decoded)) |
| 1537 |
} |
| 1538 |
for i, want := range []*packages.Package{{ |
| 1539 |
ID: "golang.org/fake/a", |
| 1540 |
Name: "a", |
| 1541 |
}, { |
| 1542 |
ID: "golang.org/fake/b", |
| 1543 |
Name: "b", |
| 1544 |
Imports: map[string]*packages.Package{ |
| 1545 |
"golang.org/fake/a": {ID: "golang.org/fake/a"}, |
| 1546 |
}, |
| 1547 |
}, { |
| 1548 |
ID: "golang.org/fake/c", |
| 1549 |
Name: "c", |
| 1550 |
Imports: map[string]*packages.Package{ |
| 1551 |
"golang.org/fake/b": {ID: "golang.org/fake/b"}, |
| 1552 |
}, |
| 1553 |
}, { |
| 1554 |
ID: "golang.org/fake/d", |
| 1555 |
Name: "d", |
| 1556 |
Imports: map[string]*packages.Package{ |
| 1557 |
"golang.org/fake/b": {ID: "golang.org/fake/b"}, |
| 1558 |
}, |
| 1559 |
}} { |
| 1560 |
got := decoded[i] |
| 1561 |
if got.ID != want.ID { |
| 1562 |
t.Errorf("Package %d has ID %q want %q", i, got.ID, want.ID) |
| 1563 |
} |
| 1564 |
if got.Name != want.Name { |
| 1565 |
t.Errorf("Package %q has Name %q want %q", got.ID, got.Name, want.Name) |
| 1566 |
} |
| 1567 |
if len(got.Imports) != len(want.Imports) { |
| 1568 |
t.Errorf("Package %q has %d imports want %d", got.ID, len(got.Imports), len(want.Imports)) |
| 1569 |
continue |
| 1570 |
} |
| 1571 |
for path, ipkg := range got.Imports { |
| 1572 |
if want.Imports[path] == nil { |
| 1573 |
t.Errorf("Package %q has unexpected import %q", got.ID, path) |
| 1574 |
continue |
| 1575 |
} |
| 1576 |
if want.Imports[path].ID != ipkg.ID { |
| 1577 |
t.Errorf("Package %q import %q is %q want %q", got.ID, path, ipkg.ID, want.Imports[path].ID) |
| 1578 |
} |
| 1579 |
} |
| 1580 |
} |
| 1581 |
} |
| 1582 |
|
| 1583 |
func TestRejectInvalidQueries(t *testing.T) { |
| 1584 |
t.Parallel() |
| 1585 |
|
| 1586 |
queries := []string{"key=", "key=value"} |
| 1587 |
cfg := &packages.Config{ |
| 1588 |
Mode: packages.LoadImports, |
| 1589 |
Env: append(os.Environ(), "GO111MODULE=off", "GOPACKAGESDRIVER=off"), |
| 1590 |
} |
| 1591 |
for _, q := range queries { |
| 1592 |
if _, err := packages.Load(cfg, q); err == nil { |
| 1593 |
t.Errorf("packages.Load(%q) succeeded. Expected \"invalid query type\" error", q) |
| 1594 |
} else if !strings.Contains(err.Error(), "invalid query type") { |
| 1595 |
t.Errorf("packages.Load(%q): got error %v, want \"invalid query type\" error", q, err) |
| 1596 |
} |
| 1597 |
} |
| 1598 |
} |
| 1599 |
|
| 1600 |
func TestPatternPassthrough(t *testing.T) { testAllOrModulesParallel(t, testPatternPassthrough) } |
| 1601 |
func testPatternPassthrough(t *testing.T, exporter packagestest.Exporter) { |
| 1602 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1603 |
Name: "golang.org/fake", |
| 1604 |
Files: map[string]any{ |
| 1605 |
"a/a.go": `package a;`, |
| 1606 |
}}}) |
| 1607 |
defer exported.Cleanup() |
| 1608 |
|
| 1609 |
initial, err := packages.Load(exported.Config, "pattern=a") |
| 1610 |
if err != nil { |
| 1611 |
t.Fatal(err) |
| 1612 |
} |
| 1613 |
|
| 1614 |
graph, _ := importGraph(initial) |
| 1615 |
wantGraph := ` |
| 1616 |
* a |
| 1617 |
`[1:] |
| 1618 |
if graph != wantGraph { |
| 1619 |
t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph) |
| 1620 |
} |
| 1621 |
|
| 1622 |
} |
| 1623 |
|
| 1624 |
func TestConfigDefaultEnv(t *testing.T) { |
| 1625 |
// packagestest.TestAll instead of testAllOrModulesParallel because this test |
| 1626 |
// can't be parallelized (it modifies the environment). |
| 1627 |
packagestest.TestAll(t, testConfigDefaultEnv) |
| 1628 |
} |
| 1629 |
func testConfigDefaultEnv(t *testing.T, exporter packagestest.Exporter) { |
| 1630 |
const driverJSON = `{ |
| 1631 |
"Roots": ["gopackagesdriver"], |
| 1632 |
"Packages": [{"ID": "gopackagesdriver", "Name": "gopackagesdriver"}] |
| 1633 |
}` |
| 1634 |
var ( |
| 1635 |
pathKey string |
| 1636 |
driverScript packagestest.Writer |
| 1637 |
) |
| 1638 |
switch runtime.GOOS { |
| 1639 |
case "android": |
| 1640 |
t.Skip("doesn't run on android") |
| 1641 |
case "windows": |
| 1642 |
// TODO(jayconrod): write an equivalent batch script for windows. |
| 1643 |
// Hint: "type" can be used to read a file to stdout. |
| 1644 |
t.Skip("test requires sh") |
| 1645 |
case "plan9": |
| 1646 |
pathKey = "path" |
| 1647 |
driverScript = packagestest.Script(`#!/bin/rc |
| 1648 |
|
| 1649 |
cat <<'EOF' |
| 1650 |
` + driverJSON + ` |
| 1651 |
EOF |
| 1652 |
`) |
| 1653 |
default: |
| 1654 |
pathKey = "PATH" |
| 1655 |
driverScript = packagestest.Script(`#!/bin/sh |
| 1656 |
|
| 1657 |
cat - <<'EOF' |
| 1658 |
` + driverJSON + ` |
| 1659 |
EOF |
| 1660 |
`) |
| 1661 |
} |
| 1662 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1663 |
Name: "golang.org/fake", |
| 1664 |
Files: map[string]any{ |
| 1665 |
"bin/gopackagesdriver": driverScript, |
| 1666 |
"golist/golist.go": "package golist", |
| 1667 |
}}}) |
| 1668 |
defer exported.Cleanup() |
| 1669 |
driver := exported.File("golang.org/fake", "bin/gopackagesdriver") |
| 1670 |
binDir := filepath.Dir(driver) |
| 1671 |
if err := os.Chmod(driver, 0755); err != nil { |
| 1672 |
t.Fatal(err) |
| 1673 |
} |
| 1674 |
|
| 1675 |
path, ok := os.LookupEnv(pathKey) |
| 1676 |
var pathWithDriver string |
| 1677 |
if ok { |
| 1678 |
pathWithDriver = binDir + string(os.PathListSeparator) + path |
| 1679 |
} else { |
| 1680 |
pathWithDriver = binDir |
| 1681 |
} |
| 1682 |
for _, test := range []struct { |
| 1683 |
desc string |
| 1684 |
path string |
| 1685 |
driver string |
| 1686 |
wantIDs string |
| 1687 |
}{ |
| 1688 |
{ |
| 1689 |
desc: "driver_off", |
| 1690 |
path: pathWithDriver, |
| 1691 |
driver: "off", |
| 1692 |
wantIDs: "[golist]", |
| 1693 |
}, { |
| 1694 |
desc: "driver_unset", |
| 1695 |
path: pathWithDriver, |
| 1696 |
driver: "", |
| 1697 |
wantIDs: "[gopackagesdriver]", |
| 1698 |
}, { |
| 1699 |
desc: "driver_set", |
| 1700 |
path: "", |
| 1701 |
driver: driver, |
| 1702 |
wantIDs: "[gopackagesdriver]", |
| 1703 |
}, |
| 1704 |
} { |
| 1705 |
t.Run(test.desc, func(t *testing.T) { |
| 1706 |
oldPath := os.Getenv(pathKey) |
| 1707 |
os.Setenv(pathKey, test.path) |
| 1708 |
defer os.Setenv(pathKey, oldPath) |
| 1709 |
// Clone exported.Config |
| 1710 |
config := exported.Config |
| 1711 |
config.Env = slices.Clone(exported.Config.Env) |
| 1712 |
config.Env = append(config.Env, "GOPACKAGESDRIVER="+test.driver) |
| 1713 |
pkgs, err := packages.Load(exported.Config, "golist") |
| 1714 |
if err != nil { |
| 1715 |
t.Fatal(err) |
| 1716 |
} |
| 1717 |
|
| 1718 |
gotIds := make([]string, len(pkgs)) |
| 1719 |
for i, pkg := range pkgs { |
| 1720 |
gotIds[i] = pkg.ID |
| 1721 |
} |
| 1722 |
if fmt.Sprint(pkgs) != test.wantIDs { |
| 1723 |
t.Errorf("got %v; want %v", gotIds, test.wantIDs) |
| 1724 |
} |
| 1725 |
}) |
| 1726 |
} |
| 1727 |
} |
| 1728 |
|
| 1729 |
// This test that a simple x test package layout loads correctly. |
| 1730 |
// There was a bug in go list where it returned multiple copies of the same |
| 1731 |
// package (specifically in this case of golang.org/fake/a), and this triggered |
| 1732 |
// a bug in go/packages where it would leave an empty entry in the root package |
| 1733 |
// list. This would then cause a nil pointer crash. |
| 1734 |
// This bug was triggered by the simple package layout below, and thus this |
| 1735 |
// test will make sure the bug remains fixed. |
| 1736 |
func TestBasicXTest(t *testing.T) { testAllOrModulesParallel(t, testBasicXTest) } |
| 1737 |
func testBasicXTest(t *testing.T, exporter packagestest.Exporter) { |
| 1738 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1739 |
Name: "golang.org/fake", |
| 1740 |
Files: map[string]any{ |
| 1741 |
"a/a.go": `package a;`, |
| 1742 |
"a/a_test.go": `package a_test;`, |
| 1743 |
}}}) |
| 1744 |
defer exported.Cleanup() |
| 1745 |
|
| 1746 |
exported.Config.Mode = packages.LoadFiles |
| 1747 |
exported.Config.Tests = true |
| 1748 |
_, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 1749 |
if err != nil { |
| 1750 |
t.Fatal(err) |
| 1751 |
} |
| 1752 |
} |
| 1753 |
|
| 1754 |
func TestErrorMissingFile(t *testing.T) { testAllOrModulesParallel(t, testErrorMissingFile) } |
| 1755 |
func testErrorMissingFile(t *testing.T, exporter packagestest.Exporter) { |
| 1756 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1757 |
Name: "golang.org/fake", |
| 1758 |
Files: map[string]any{ |
| 1759 |
"a/a_test.go": `package a;`, |
| 1760 |
}}}) |
| 1761 |
defer exported.Cleanup() |
| 1762 |
|
| 1763 |
exported.Config.Mode = packages.LoadSyntax |
| 1764 |
exported.Config.Tests = false |
| 1765 |
pkgs, err := packages.Load(exported.Config, "missing.go") |
| 1766 |
if err != nil { |
| 1767 |
t.Fatal(err) |
| 1768 |
} |
| 1769 |
if len(pkgs) == 0 && runtime.GOOS == "windows" { |
| 1770 |
t.Skip("Issue #31344: the ad-hoc command-line-arguments package isn't created on windows") |
| 1771 |
} |
| 1772 |
if len(pkgs) != 1 || (pkgs[0].PkgPath != "command-line-arguments" && pkgs[0].PkgPath != "missing.go") { |
| 1773 |
t.Fatalf("packages.Load: want [command-line-arguments] or [missing.go], got %v", pkgs) |
| 1774 |
} |
| 1775 |
if len(pkgs[0].Errors) == 0 { |
| 1776 |
t.Errorf("result of Load: want package with errors, got none: %+v", pkgs[0]) |
| 1777 |
} |
| 1778 |
} |
| 1779 |
|
| 1780 |
func TestReturnErrorWhenUsingNonGoFiles(t *testing.T) { |
| 1781 |
testAllOrModulesParallel(t, testReturnErrorWhenUsingNonGoFiles) |
| 1782 |
} |
| 1783 |
func testReturnErrorWhenUsingNonGoFiles(t *testing.T, exporter packagestest.Exporter) { |
| 1784 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1785 |
Name: "golang.org/gopatha", |
| 1786 |
Files: map[string]any{ |
| 1787 |
"a/a.go": `package a`, |
| 1788 |
}}, { |
| 1789 |
Name: "golang.org/gopathb", |
| 1790 |
Files: map[string]any{ |
| 1791 |
"b/b.c": `package b`, |
| 1792 |
}}}) |
| 1793 |
defer exported.Cleanup() |
| 1794 |
config := packages.Config{Env: append(os.Environ(), "GOPACKAGESDRIVER=off")} |
| 1795 |
pkgs, err := packages.Load(&config, "b/b.c") |
| 1796 |
if err != nil { |
| 1797 |
return |
| 1798 |
} |
| 1799 |
// Go <1.14 calls the package command-line-arguments while Go 1.14+ uses the file names. |
| 1800 |
if len(pkgs) != 1 || (pkgs[0].PkgPath != "command-line-arguments" && pkgs[0].PkgPath != "b/b.c") { |
| 1801 |
t.Fatalf("packages.Load: want [command-line-arguments] or [b/b.c], got %v", pkgs) |
| 1802 |
} |
| 1803 |
if len(pkgs[0].Errors) != 1 { |
| 1804 |
t.Fatalf("result of Load: want package with one error, got: %+v", pkgs[0]) |
| 1805 |
} |
| 1806 |
} |
| 1807 |
|
| 1808 |
func TestReturnErrorWhenUsingGoFilesInMultipleDirectories(t *testing.T) { |
| 1809 |
testAllOrModulesParallel(t, testReturnErrorWhenUsingGoFilesInMultipleDirectories) |
| 1810 |
} |
| 1811 |
func testReturnErrorWhenUsingGoFilesInMultipleDirectories(t *testing.T, exporter packagestest.Exporter) { |
| 1812 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1813 |
Name: "golang.org/gopatha", |
| 1814 |
Files: map[string]any{ |
| 1815 |
"a/a.go": `package a`, |
| 1816 |
"b/b.go": `package b`, |
| 1817 |
}}}) |
| 1818 |
defer exported.Cleanup() |
| 1819 |
want := "named files must all be in one directory" |
| 1820 |
pkgs, err := packages.Load(exported.Config, exported.File("golang.org/gopatha", "a/a.go"), exported.File("golang.org/gopatha", "b/b.go")) |
| 1821 |
if err != nil { |
| 1822 |
// Check if the error returned is the one we expected. |
| 1823 |
if !strings.Contains(err.Error(), want) { |
| 1824 |
t.Fatalf("want error message: %s, got: %s", want, err.Error()) |
| 1825 |
} |
| 1826 |
return |
| 1827 |
} |
| 1828 |
if len(pkgs) != 1 || pkgs[0].PkgPath != "command-line-arguments" { |
| 1829 |
t.Fatalf("packages.Load: want [command-line-arguments], got %v", pkgs) |
| 1830 |
} |
| 1831 |
if len(pkgs[0].Errors) != 1 { |
| 1832 |
t.Fatalf("result of Load: want package with one error, got: %+v", pkgs[0]) |
| 1833 |
} |
| 1834 |
got := pkgs[0].Errors[0].Error() |
| 1835 |
if !strings.Contains(got, want) { |
| 1836 |
t.Fatalf("want error message: %s, got: %s", want, got) |
| 1837 |
} |
| 1838 |
} |
| 1839 |
|
| 1840 |
func TestReturnErrorForUnexpectedDirectoryLayout(t *testing.T) { |
| 1841 |
testAllOrModulesParallel(t, testReturnErrorForUnexpectedDirectoryLayout) |
| 1842 |
} |
| 1843 |
func testReturnErrorForUnexpectedDirectoryLayout(t *testing.T, exporter packagestest.Exporter) { |
| 1844 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1845 |
Name: "golang.org/gopatha", |
| 1846 |
Files: map[string]any{ |
| 1847 |
"a/testdata/a.go": `package a; import _ "b"`, |
| 1848 |
"a/vendor/b/b.go": `package b; import _ "fmt"`, |
| 1849 |
}}}) |
| 1850 |
defer exported.Cleanup() |
| 1851 |
want := "unexpected directory layout" |
| 1852 |
// triggering this error requires a relative package path |
| 1853 |
exported.Config.Dir = filepath.Dir(exported.File("golang.org/gopatha", "a/testdata/a.go")) |
| 1854 |
pkgs, err := packages.Load(exported.Config, ".") |
| 1855 |
|
| 1856 |
// This error doesn't seem to occur in module mode; so only |
| 1857 |
// complain if we get zero packages while also getting no error. |
| 1858 |
if err == nil { |
| 1859 |
if len(pkgs) == 0 { |
| 1860 |
// TODO(dh): we'll need to expand on the error check if/when Go stops emitting this error |
| 1861 |
t.Fatalf("want error, got nil") |
| 1862 |
} |
| 1863 |
return |
| 1864 |
} |
| 1865 |
// Check if the error returned is the one we expected. |
| 1866 |
if !strings.Contains(err.Error(), want) { |
| 1867 |
t.Fatalf("want error message: %s, got: %s", want, err.Error()) |
| 1868 |
} |
| 1869 |
} |
| 1870 |
|
| 1871 |
func TestMissingDependency(t *testing.T) { testAllOrModulesParallel(t, testMissingDependency) } |
| 1872 |
func testMissingDependency(t *testing.T, exporter packagestest.Exporter) { |
| 1873 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1874 |
Name: "golang.org/fake", |
| 1875 |
Files: map[string]any{ |
| 1876 |
"a/a.go": `package a; import _ "this/package/doesnt/exist"`, |
| 1877 |
}}}) |
| 1878 |
defer exported.Cleanup() |
| 1879 |
|
| 1880 |
exported.Config.Mode = packages.LoadAllSyntax |
| 1881 |
pkgs, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 1882 |
if err != nil { |
| 1883 |
t.Fatal(err) |
| 1884 |
} |
| 1885 |
if len(pkgs) != 1 && pkgs[0].PkgPath != "golang.org/fake/a" { |
| 1886 |
t.Fatalf("packages.Load: want [golang.org/fake/a], got %v", pkgs) |
| 1887 |
} |
| 1888 |
if len(pkgs[0].Errors) == 0 { |
| 1889 |
t.Errorf("result of Load: want package with errors, got none: %+v", pkgs[0]) |
| 1890 |
} |
| 1891 |
} |
| 1892 |
|
| 1893 |
func TestAdHocContains(t *testing.T) { testAllOrModulesParallel(t, testAdHocContains) } |
| 1894 |
func testAdHocContains(t *testing.T, exporter packagestest.Exporter) { |
| 1895 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1896 |
Name: "golang.org/fake", |
| 1897 |
Files: map[string]any{ |
| 1898 |
"a/a.go": `package a;`, |
| 1899 |
}}}) |
| 1900 |
defer exported.Cleanup() |
| 1901 |
|
| 1902 |
tmpfile, err := os.CreateTemp("", "adhoc*.go") |
| 1903 |
filename := tmpfile.Name() |
| 1904 |
if err != nil { |
| 1905 |
t.Fatal(err) |
| 1906 |
} |
| 1907 |
fmt.Fprint(tmpfile, `package main; import "fmt"; func main() { fmt.Println("time for coffee") }`) |
| 1908 |
if err := tmpfile.Close(); err != nil { |
| 1909 |
t.Fatal(err) |
| 1910 |
} |
| 1911 |
|
| 1912 |
defer func() { |
| 1913 |
if err := os.Remove(filename); err != nil { |
| 1914 |
t.Fatal(err) |
| 1915 |
} |
| 1916 |
}() |
| 1917 |
|
| 1918 |
exported.Config.Mode = packages.NeedImports | packages.NeedFiles |
| 1919 |
pkgs, err := packages.Load(exported.Config, "file="+filename) |
| 1920 |
if err != nil { |
| 1921 |
t.Fatal(err) |
| 1922 |
} |
| 1923 |
if len(pkgs) != 1 && pkgs[0].PkgPath != "command-line-arguments" { |
| 1924 |
t.Fatalf("packages.Load: want [command-line-arguments], got %v", pkgs) |
| 1925 |
} |
| 1926 |
pkg := pkgs[0] |
| 1927 |
if _, ok := pkg.Imports["fmt"]; !ok || len(pkg.Imports) != 1 { |
| 1928 |
t.Fatalf("Imports of loaded package: want [fmt], got %v", pkg.Imports) |
| 1929 |
} |
| 1930 |
if len(pkg.GoFiles) != 1 || pkg.GoFiles[0] != filename { |
| 1931 |
t.Fatalf("GoFiles of loaded package: want [%s], got %v", filename, pkg.GoFiles) |
| 1932 |
} |
| 1933 |
} |
| 1934 |
|
| 1935 |
func TestCgoNoCcompiler(t *testing.T) { testAllOrModulesParallel(t, testCgoNoCcompiler) } |
| 1936 |
func testCgoNoCcompiler(t *testing.T, exporter packagestest.Exporter) { |
| 1937 |
testenv.NeedsTool(t, "cgo") |
| 1938 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1939 |
Name: "golang.org/fake", |
| 1940 |
Files: map[string]any{ |
| 1941 |
"a/a.go": `package a |
| 1942 |
import "net/http" |
| 1943 |
const A = http.MethodGet |
| 1944 |
`, |
| 1945 |
}}}) |
| 1946 |
defer exported.Cleanup() |
| 1947 |
|
| 1948 |
// Explicitly enable cgo but configure a nonexistent C compiler. |
| 1949 |
exported.Config.Env = append(exported.Config.Env, "CGO_ENABLED=1", "CC=doesnotexist") |
| 1950 |
exported.Config.Mode = packages.LoadAllSyntax |
| 1951 |
initial, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 1952 |
|
| 1953 |
if err != nil { |
| 1954 |
t.Fatal(err) |
| 1955 |
} |
| 1956 |
|
| 1957 |
// Check value of a.A. |
| 1958 |
a := initial[0] |
| 1959 |
aA := constant(a, "A") |
| 1960 |
if aA == nil { |
| 1961 |
t.Fatalf("a.A: got nil") |
| 1962 |
} |
| 1963 |
got := aA.Val().String() |
| 1964 |
if got != "\"GET\"" { |
| 1965 |
t.Errorf("a.A: got %s, want %s", got, "\"GET\"") |
| 1966 |
} |
| 1967 |
} |
| 1968 |
|
| 1969 |
func TestCgoMissingFile(t *testing.T) { testAllOrModulesParallel(t, testCgoMissingFile) } |
| 1970 |
func testCgoMissingFile(t *testing.T, exporter packagestest.Exporter) { |
| 1971 |
testenv.NeedsTool(t, "cgo") |
| 1972 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 1973 |
Name: "golang.org/fake", |
| 1974 |
Files: map[string]any{ |
| 1975 |
"a/a.go": `package a |
| 1976 |
|
| 1977 |
// #include "foo.h" |
| 1978 |
import "C" |
| 1979 |
|
| 1980 |
const A = 4 |
| 1981 |
`, |
| 1982 |
}}}) |
| 1983 |
defer exported.Cleanup() |
| 1984 |
|
| 1985 |
// Explicitly enable cgo. |
| 1986 |
exported.Config.Env = append(exported.Config.Env, "CGO_ENABLED=1") |
| 1987 |
exported.Config.Mode = packages.LoadAllSyntax |
| 1988 |
initial, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 1989 |
|
| 1990 |
if err != nil { |
| 1991 |
t.Fatal(err) |
| 1992 |
} |
| 1993 |
|
| 1994 |
// Check value of a.A. |
| 1995 |
a := initial[0] |
| 1996 |
aA := constant(a, "A") |
| 1997 |
if aA == nil { |
| 1998 |
t.Fatalf("a.A: got nil") |
| 1999 |
} |
| 2000 |
got := aA.Val().String() |
| 2001 |
if got != "4" { |
| 2002 |
t.Errorf("a.A: got %s, want %s", got, "4") |
| 2003 |
} |
| 2004 |
} |
| 2005 |
|
| 2006 |
func TestLoadImportsC(t *testing.T) { |
| 2007 |
// This test checks that when a package depends on the |
| 2008 |
// test variant of "syscall", "unsafe", or "runtime/cgo", that dependency |
| 2009 |
// is not removed when those packages are added when it imports "C". |
| 2010 |
// |
| 2011 |
// For this test to work, the external test of syscall must have a dependency |
| 2012 |
// on net, and net must import "syscall" and "C". |
| 2013 |
if runtime.GOOS == "windows" { |
| 2014 |
t.Skipf("skipping on windows; packages on windows do not satisfy conditions for test.") |
| 2015 |
} |
| 2016 |
if runtime.GOOS == "plan9" { |
| 2017 |
// See https://golang.org/issue/27100. |
| 2018 |
t.Skip(`skipping on plan9; for some reason "net [syscall.test]" is not loaded`) |
| 2019 |
} |
| 2020 |
t.Parallel() |
| 2021 |
testenv.NeedsGoPackages(t) |
| 2022 |
|
| 2023 |
cfg := &packages.Config{ |
| 2024 |
Context: t.Context(), |
| 2025 |
Mode: packages.LoadImports, |
| 2026 |
Tests: true, |
| 2027 |
} |
| 2028 |
initial, err := packages.Load(cfg, "syscall", "net") |
| 2029 |
if err != nil { |
| 2030 |
t.Fatalf("failed to load imports: %v", err) |
| 2031 |
} |
| 2032 |
|
| 2033 |
_, all := importGraph(initial) |
| 2034 |
|
| 2035 |
for _, test := range []struct { |
| 2036 |
pattern string |
| 2037 |
wantImport string // an import to check for |
| 2038 |
}{ |
| 2039 |
{"net", "syscall:syscall"}, |
| 2040 |
{"net [syscall.test]", "syscall:syscall [syscall.test]"}, |
| 2041 |
{"syscall_test [syscall.test]", "net:net [syscall.test]"}, |
| 2042 |
} { |
| 2043 |
// Test the import paths. |
| 2044 |
pkg := all[test.pattern] |
| 2045 |
if pkg == nil { |
| 2046 |
t.Errorf("package %q not loaded", test.pattern) |
| 2047 |
continue |
| 2048 |
} |
| 2049 |
if imports := strings.Join(imports(pkg), " "); !strings.Contains(imports, test.wantImport) { |
| 2050 |
t.Errorf("package %q: got \n%s, \nwant to have %s", test.pattern, imports, test.wantImport) |
| 2051 |
} |
| 2052 |
} |
| 2053 |
} |
| 2054 |
|
| 2055 |
func TestCgoNoSyntax(t *testing.T) { |
| 2056 |
testAllOrModulesParallel(t, testCgoNoSyntax) |
| 2057 |
} |
| 2058 |
func testCgoNoSyntax(t *testing.T, exporter packagestest.Exporter) { |
| 2059 |
testenv.NeedsTool(t, "cgo") |
| 2060 |
|
| 2061 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 2062 |
Name: "golang.org/fake", |
| 2063 |
Files: map[string]any{ |
| 2064 |
"c/c.go": `package c; import "C"`, |
| 2065 |
}, |
| 2066 |
}}) |
| 2067 |
|
| 2068 |
// Explicitly enable cgo. |
| 2069 |
exported.Config.Env = append(exported.Config.Env, "CGO_ENABLED=1") |
| 2070 |
|
| 2071 |
modes := []packages.LoadMode{ |
| 2072 |
packages.NeedTypes, |
| 2073 |
packages.NeedName | packages.NeedTypes, |
| 2074 |
packages.NeedName | packages.NeedTypes | packages.NeedImports, |
| 2075 |
packages.NeedName | packages.NeedTypes | packages.NeedImports | packages.NeedDeps, |
| 2076 |
packages.NeedName | packages.NeedImports, |
| 2077 |
} |
| 2078 |
for _, mode := range modes { |
| 2079 |
t.Run(fmt.Sprint(mode), func(t *testing.T) { |
| 2080 |
exported.Config.Mode = mode |
| 2081 |
pkgs, err := packages.Load(exported.Config, "golang.org/fake/c") |
| 2082 |
if err != nil { |
| 2083 |
t.Fatal(err) |
| 2084 |
} |
| 2085 |
if len(pkgs) != 1 { |
| 2086 |
t.Fatalf("Expected 1 package, got %v", pkgs) |
| 2087 |
} |
| 2088 |
pkg := pkgs[0] |
| 2089 |
if len(pkg.Errors) != 0 { |
| 2090 |
t.Fatalf("Expected no errors in package, got %v", pkg.Errors) |
| 2091 |
} |
| 2092 |
}) |
| 2093 |
} |
| 2094 |
} |
| 2095 |
|
| 2096 |
func TestCgoBadPkgConfig(t *testing.T) { |
| 2097 |
testAllOrModulesParallel(t, testCgoBadPkgConfig) |
| 2098 |
} |
| 2099 |
func testCgoBadPkgConfig(t *testing.T, exporter packagestest.Exporter) { |
| 2100 |
skipIfShort(t, "builds and links a fake pkgconfig binary") |
| 2101 |
testenv.NeedsTool(t, "cgo") |
| 2102 |
|
| 2103 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 2104 |
Name: "golang.org/fake", |
| 2105 |
Files: map[string]any{ |
| 2106 |
"c/c.go": `package c |
| 2107 |
|
| 2108 |
// #cgo pkg-config: --cflags -- foo |
| 2109 |
import "C"`, |
| 2110 |
}, |
| 2111 |
}}) |
| 2112 |
|
| 2113 |
dir := buildFakePkgconfig(t, exported.Config.Env) |
| 2114 |
defer os.RemoveAll(dir) |
| 2115 |
env := exported.Config.Env |
| 2116 |
for i, v := range env { |
| 2117 |
if strings.HasPrefix(v, "PATH=") { |
| 2118 |
env[i] = "PATH=" + dir + string(os.PathListSeparator) + v[len("PATH="):] |
| 2119 |
} |
| 2120 |
} |
| 2121 |
|
| 2122 |
exported.Config.Env = append(exported.Config.Env, "CGO_ENABLED=1") |
| 2123 |
|
| 2124 |
exported.Config.Mode = packages.NeedName | packages.NeedCompiledGoFiles |
| 2125 |
pkgs, err := packages.Load(exported.Config, "golang.org/fake/c") |
| 2126 |
if err != nil { |
| 2127 |
t.Fatal(err) |
| 2128 |
} |
| 2129 |
if len(pkgs) != 1 { |
| 2130 |
t.Fatalf("Expected 1 package, got %v", pkgs) |
| 2131 |
} |
| 2132 |
if pkgs[0].Name != "c" { |
| 2133 |
t.Fatalf("Expected package to have name \"c\", got %q", pkgs[0].Name) |
| 2134 |
} |
| 2135 |
} |
| 2136 |
|
| 2137 |
func buildFakePkgconfig(t *testing.T, env []string) string { |
| 2138 |
tmpdir, err := os.MkdirTemp("", "fakepkgconfig") |
| 2139 |
if err != nil { |
| 2140 |
t.Fatal(err) |
| 2141 |
} |
| 2142 |
err = os.WriteFile(filepath.Join(tmpdir, "pkg-config.go"), []byte(` |
| 2143 |
package main |
| 2144 |
|
| 2145 |
import "fmt" |
| 2146 |
import "os" |
| 2147 |
|
| 2148 |
func main() { |
| 2149 |
fmt.Fprintln(os.Stderr, "bad") |
| 2150 |
os.Exit(2) |
| 2151 |
} |
| 2152 |
`), 0644) |
| 2153 |
if err != nil { |
| 2154 |
os.RemoveAll(tmpdir) |
| 2155 |
t.Fatal(err) |
| 2156 |
} |
| 2157 |
cmd := exec.Command("go", "build", "-o", "pkg-config", "pkg-config.go") |
| 2158 |
cmd.Dir = tmpdir |
| 2159 |
cmd.Env = env |
| 2160 |
|
| 2161 |
if b, err := cmd.CombinedOutput(); err != nil { |
| 2162 |
os.RemoveAll(tmpdir) |
| 2163 |
fmt.Println(os.Environ()) |
| 2164 |
t.Log(string(b)) |
| 2165 |
t.Fatal(err) |
| 2166 |
} |
| 2167 |
return tmpdir |
| 2168 |
} |
| 2169 |
|
| 2170 |
func TestIssue32814(t *testing.T) { testAllOrModulesParallel(t, testIssue32814) } |
| 2171 |
func testIssue32814(t *testing.T, exporter packagestest.Exporter) { |
| 2172 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 2173 |
Name: "golang.org/fake", |
| 2174 |
Files: map[string]any{}}}) |
| 2175 |
defer exported.Cleanup() |
| 2176 |
|
| 2177 |
exported.Config.Mode = packages.NeedName | packages.NeedTypes | packages.NeedSyntax | packages.NeedTypesInfo | packages.NeedTypesSizes |
| 2178 |
pkgs, err := packages.Load(exported.Config, "fmt") |
| 2179 |
|
| 2180 |
if err != nil { |
| 2181 |
t.Fatal(err) |
| 2182 |
} |
| 2183 |
|
| 2184 |
if len(pkgs) != 1 && pkgs[0].PkgPath != "fmt" { |
| 2185 |
t.Fatalf("packages.Load: want [fmt], got %v", pkgs) |
| 2186 |
} |
| 2187 |
pkg := pkgs[0] |
| 2188 |
if len(pkg.Errors) != 0 { |
| 2189 |
t.Fatalf("Errors for fmt pkg: got %v, want none", pkg.Errors) |
| 2190 |
} |
| 2191 |
if !pkg.Types.Complete() { |
| 2192 |
t.Fatalf("Types.Complete() for fmt pkg: got %v, want true", pkgs[0].Types.Complete()) |
| 2193 |
|
| 2194 |
} |
| 2195 |
} |
| 2196 |
|
| 2197 |
func TestLoadTypesInfoWithoutNeedDeps(t *testing.T) { |
| 2198 |
testAllOrModulesParallel(t, testLoadTypesInfoWithoutNeedDeps) |
| 2199 |
} |
| 2200 |
func testLoadTypesInfoWithoutNeedDeps(t *testing.T, exporter packagestest.Exporter) { |
| 2201 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 2202 |
Name: "golang.org/fake", |
| 2203 |
Files: map[string]any{ |
| 2204 |
"a/a.go": `package a; import _ "golang.org/fake/b"`, |
| 2205 |
"b/b.go": `package b`, |
| 2206 |
}}}) |
| 2207 |
defer exported.Cleanup() |
| 2208 |
|
| 2209 |
exported.Config.Mode = packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports |
| 2210 |
pkgs, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 2211 |
if err != nil { |
| 2212 |
t.Fatal(err) |
| 2213 |
} |
| 2214 |
pkg := pkgs[0] |
| 2215 |
if pkg.IllTyped { |
| 2216 |
t.Fatal("Loaded package is ill typed") |
| 2217 |
} |
| 2218 |
const expectedImport = "golang.org/fake/b" |
| 2219 |
if _, ok := pkg.Imports[expectedImport]; !ok || len(pkg.Imports) != 1 { |
| 2220 |
t.Fatalf("Imports of loaded package: want [%s], got %v", expectedImport, pkg.Imports) |
| 2221 |
} |
| 2222 |
} |
| 2223 |
|
| 2224 |
func TestLoadWithNeedDeps(t *testing.T) { |
| 2225 |
testAllOrModulesParallel(t, testLoadWithNeedDeps) |
| 2226 |
} |
| 2227 |
func testLoadWithNeedDeps(t *testing.T, exporter packagestest.Exporter) { |
| 2228 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 2229 |
Name: "golang.org/fake", |
| 2230 |
Files: map[string]any{ |
| 2231 |
"a/a.go": `package a; import _ "golang.org/fake/b"`, |
| 2232 |
"b/b.go": `package b; import _ "golang.org/fake/c"`, |
| 2233 |
"c/c.go": `package c`, |
| 2234 |
}}}) |
| 2235 |
defer exported.Cleanup() |
| 2236 |
|
| 2237 |
exported.Config.Mode = packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports | packages.NeedDeps |
| 2238 |
pkgs, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 2239 |
if err != nil { |
| 2240 |
t.Fatal(err) |
| 2241 |
} |
| 2242 |
if len(pkgs) != 1 { |
| 2243 |
t.Fatalf("Expected 1 package, got %d", len(pkgs)) |
| 2244 |
} |
| 2245 |
|
| 2246 |
pkgA := pkgs[0] |
| 2247 |
if pkgA.IllTyped { |
| 2248 |
t.Fatal("Loaded package is ill typed") |
| 2249 |
} |
| 2250 |
|
| 2251 |
pkgB := pkgA.Imports["golang.org/fake/b"] |
| 2252 |
if pkgB == nil || len(pkgA.Imports) != 1 { |
| 2253 |
t.Fatalf("Imports of loaded package 'a' are invalid: %v", pkgA.Imports) |
| 2254 |
} |
| 2255 |
if pkgB.Types == nil || !pkgB.Types.Complete() || pkgB.TypesInfo == nil { |
| 2256 |
t.Fatalf("Types of package 'b' are nil or incomplete: %v, %v", pkgB.Types, pkgB.TypesInfo) |
| 2257 |
} |
| 2258 |
|
| 2259 |
pkgC := pkgB.Imports["golang.org/fake/c"] |
| 2260 |
if pkgC == nil || len(pkgB.Imports) != 1 { |
| 2261 |
t.Fatalf("Imports of loaded package 'c' are invalid: %v", pkgB.Imports) |
| 2262 |
} |
| 2263 |
if pkgC.Types == nil || !pkgC.Types.Complete() || pkgC.TypesInfo == nil { |
| 2264 |
t.Fatalf("Types of package 'b' are nil or incomplete: %v, %v", pkgC.Types, pkgC.TypesInfo) |
| 2265 |
} |
| 2266 |
} |
| 2267 |
|
| 2268 |
func TestImpliedLoadMode(t *testing.T) { |
| 2269 |
testAllOrModulesParallel(t, testImpliedLoadMode) |
| 2270 |
} |
| 2271 |
func testImpliedLoadMode(t *testing.T, exporter packagestest.Exporter) { |
| 2272 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 2273 |
Name: "golang.org/fake", |
| 2274 |
Files: map[string]any{ |
| 2275 |
"a/a.go": `package a; import _ "golang.org/fake/b"`, |
| 2276 |
"b/b.go": `package b`, |
| 2277 |
}}}) |
| 2278 |
defer exported.Cleanup() |
| 2279 |
|
| 2280 |
exported.Config.Mode = packages.NeedTypes | packages.NeedTypesInfo |
| 2281 |
pkgs, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 2282 |
if err != nil { |
| 2283 |
t.Fatal(err) |
| 2284 |
} |
| 2285 |
if len(pkgs) != 1 { |
| 2286 |
t.Fatalf("Expected 1 package, got %d", len(pkgs)) |
| 2287 |
} |
| 2288 |
|
| 2289 |
pkg := pkgs[0] |
| 2290 |
if pkg.IllTyped { |
| 2291 |
t.Fatalf("Loaded package is ill typed: %v", pkg.Errors) |
| 2292 |
} |
| 2293 |
|
| 2294 |
// Check that packages.NeedTypesInfo worked well. |
| 2295 |
if !pkg.Types.Complete() { |
| 2296 |
t.Fatalf("Loaded package types are incomplete") |
| 2297 |
} |
| 2298 |
|
| 2299 |
// Check that implied packages.NeedImports by packages.NeedTypesInfo |
| 2300 |
// didn't add Imports. |
| 2301 |
if len(pkg.Imports) != 0 { |
| 2302 |
t.Fatalf("Package imports weren't requested but were returned: %v", pkg.Imports) |
| 2303 |
} |
| 2304 |
} |
| 2305 |
|
| 2306 |
func TestIssue35331(t *testing.T) { |
| 2307 |
testAllOrModulesParallel(t, testIssue35331) |
| 2308 |
} |
| 2309 |
func testIssue35331(t *testing.T, exporter packagestest.Exporter) { |
| 2310 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 2311 |
Name: "golang.org/fake", |
| 2312 |
}}) |
| 2313 |
defer exported.Cleanup() |
| 2314 |
|
| 2315 |
exported.Config.Mode = packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | |
| 2316 |
packages.NeedImports | packages.NeedDeps | packages.NeedSyntax |
| 2317 |
exported.Config.Tests = false |
| 2318 |
pkgs, err := packages.Load(exported.Config, "strconv") |
| 2319 |
if err != nil { |
| 2320 |
t.Fatal(err) |
| 2321 |
} |
| 2322 |
if len(pkgs) != 1 { |
| 2323 |
t.Fatalf("Expected 1 package, got %v", pkgs) |
| 2324 |
} |
| 2325 |
for pkg := range packages.Postorder(pkgs) { |
| 2326 |
if len(pkg.Errors) > 0 { |
| 2327 |
t.Errorf("Expected no errors in package %q, got %v", pkg.ID, pkg.Errors) |
| 2328 |
} |
| 2329 |
if len(pkg.Syntax) == 0 && pkg.ID != "unsafe" { |
| 2330 |
t.Errorf("Expected syntax on package %q, got none.", pkg.ID) |
| 2331 |
} |
| 2332 |
} |
| 2333 |
} |
| 2334 |
|
| 2335 |
func TestMultiplePackageVersionsIssue36188(t *testing.T) { |
| 2336 |
testAllOrModulesParallel(t, testMultiplePackageVersionsIssue36188) |
| 2337 |
} |
| 2338 |
|
| 2339 |
func testMultiplePackageVersionsIssue36188(t *testing.T, exporter packagestest.Exporter) { |
| 2340 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 2341 |
Name: "golang.org/fake", |
| 2342 |
Files: map[string]any{ |
| 2343 |
"a/a.go": `package a; import _ "golang.org/fake/b"`, |
| 2344 |
"b/b.go": `package main`, |
| 2345 |
}}}) |
| 2346 |
pkgs, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/b") |
| 2347 |
if err != nil { |
| 2348 |
t.Fatal(err) |
| 2349 |
} |
| 2350 |
sort.Slice(pkgs, func(i, j int) bool { return pkgs[i].ID < pkgs[j].ID }) |
| 2351 |
if len(pkgs) != 2 { |
| 2352 |
t.Fatalf("expected two packages, got %v", pkgs) |
| 2353 |
} |
| 2354 |
if pkgs[0].ID != "golang.org/fake/a" && pkgs[1].ID != "golang.org/fake/b" { |
| 2355 |
t.Fatalf(`expected (sorted) IDs "golang.org/fake/a" and "golang.org/fake/b", got %q and %q`, |
| 2356 |
pkgs[0].ID, pkgs[1].ID) |
| 2357 |
} |
| 2358 |
if pkgs[0].Errors == nil { |
| 2359 |
t.Errorf(`expected error on package "golang.org/fake/a", got none`) |
| 2360 |
} |
| 2361 |
if pkgs[1].Errors != nil { |
| 2362 |
t.Errorf(`expected no errors on package "golang.org/fake/b", got %v`, pkgs[1].Errors) |
| 2363 |
} |
| 2364 |
defer exported.Cleanup() |
| 2365 |
} |
| 2366 |
|
| 2367 |
func TestLoadModeStrings(t *testing.T) { |
| 2368 |
testcases := []struct { |
| 2369 |
mode packages.LoadMode |
| 2370 |
expected string |
| 2371 |
}{ |
| 2372 |
{ |
| 2373 |
packages.LoadMode(0), |
| 2374 |
"LoadMode(0)", |
| 2375 |
}, |
| 2376 |
{ |
| 2377 |
packages.NeedName, |
| 2378 |
"NeedName", |
| 2379 |
}, |
| 2380 |
{ |
| 2381 |
packages.NeedFiles, |
| 2382 |
"NeedFiles", |
| 2383 |
}, |
| 2384 |
{ |
| 2385 |
packages.NeedCompiledGoFiles, |
| 2386 |
"NeedCompiledGoFiles", |
| 2387 |
}, |
| 2388 |
{ |
| 2389 |
packages.NeedImports, |
| 2390 |
"NeedImports", |
| 2391 |
}, |
| 2392 |
{ |
| 2393 |
packages.NeedDeps, |
| 2394 |
"NeedDeps", |
| 2395 |
}, |
| 2396 |
{ |
| 2397 |
packages.NeedExportFile, |
| 2398 |
"NeedExportFile", |
| 2399 |
}, |
| 2400 |
{ |
| 2401 |
packages.NeedTypes, |
| 2402 |
"NeedTypes", |
| 2403 |
}, |
| 2404 |
{ |
| 2405 |
packages.NeedSyntax, |
| 2406 |
"NeedSyntax", |
| 2407 |
}, |
| 2408 |
{ |
| 2409 |
packages.NeedTypesInfo, |
| 2410 |
"NeedTypesInfo", |
| 2411 |
}, |
| 2412 |
{ |
| 2413 |
packages.NeedTypesSizes, |
| 2414 |
"NeedTypesSizes", |
| 2415 |
}, |
| 2416 |
{ |
| 2417 |
packages.NeedName | packages.NeedExportFile, |
| 2418 |
"(NeedName|NeedExportFile)", |
| 2419 |
}, |
| 2420 |
{ |
| 2421 |
packages.NeedForTest | packages.NeedTarget | packages.NeedEmbedFiles | packages.NeedEmbedPatterns, |
| 2422 |
"(NeedForTest|NeedEmbedFiles|NeedEmbedPatterns|NeedTarget)", |
| 2423 |
}, |
| 2424 |
{ |
| 2425 |
packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedImports | packages.NeedDeps | packages.NeedExportFile | packages.NeedTypes | packages.NeedSyntax | packages.NeedTypesInfo | packages.NeedTypesSizes, |
| 2426 |
"(NeedName|NeedFiles|NeedCompiledGoFiles|NeedImports|NeedDeps|NeedExportFile|NeedTypes|NeedSyntax|NeedTypesInfo|NeedTypesSizes)", |
| 2427 |
}, |
| 2428 |
{ |
| 2429 |
packages.NeedName | packages.NeedModule, |
| 2430 |
"(NeedName|NeedModule)", |
| 2431 |
}, |
| 2432 |
{ |
| 2433 |
packages.NeedName | 0x100000, // off the end (future use) |
| 2434 |
"(NeedName|0x100000)", |
| 2435 |
}, |
| 2436 |
{ |
| 2437 |
packages.NeedName | 0x400, // needInternalDepsErrors |
| 2438 |
"(NeedName|0x400)", |
| 2439 |
}, |
| 2440 |
{ |
| 2441 |
0x1000, |
| 2442 |
"LoadMode(0x1000)", |
| 2443 |
}, |
| 2444 |
} |
| 2445 |
|
| 2446 |
for tcInd, tc := range testcases { |
| 2447 |
t.Run(fmt.Sprintf("test-%d", tcInd), func(t *testing.T) { |
| 2448 |
actual := tc.mode.String() |
| 2449 |
if tc.expected != actual { |
| 2450 |
t.Errorf("want %#v, got %#v", tc.expected, actual) |
| 2451 |
} |
| 2452 |
}) |
| 2453 |
} |
| 2454 |
} |
| 2455 |
|
| 2456 |
func TestCycleImportStack(t *testing.T) { |
| 2457 |
testAllOrModulesParallel(t, testCycleImportStack) |
| 2458 |
} |
| 2459 |
func testCycleImportStack(t *testing.T, exporter packagestest.Exporter) { |
| 2460 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 2461 |
Name: "golang.org/fake", |
| 2462 |
Files: map[string]any{ |
| 2463 |
"a/a.go": `package a; import _ "golang.org/fake/b"`, |
| 2464 |
"b/b.go": `package b; import _ "golang.org/fake/a"`, |
| 2465 |
}}}) |
| 2466 |
defer exported.Cleanup() |
| 2467 |
|
| 2468 |
exported.Config.Mode = packages.NeedName | packages.NeedImports |
| 2469 |
pkgs, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 2470 |
if err != nil { |
| 2471 |
t.Fatal(err) |
| 2472 |
} |
| 2473 |
if len(pkgs) != 1 { |
| 2474 |
t.Fatalf("Expected 1 package, got %v", pkgs) |
| 2475 |
} |
| 2476 |
pkg := pkgs[0] |
| 2477 |
if len(pkg.Errors) != 1 { |
| 2478 |
t.Fatalf("Expected one error in package, got %v", pkg.Errors) |
| 2479 |
} |
| 2480 |
expected := "import cycle not allowed: import stack: [golang.org/fake/a golang.org/fake/b golang.org/fake/a]" |
| 2481 |
if pkg.Errors[0].Msg != expected { |
| 2482 |
t.Fatalf("Expected error %q, got %q", expected, pkg.Errors[0].Msg) |
| 2483 |
} |
| 2484 |
} |
| 2485 |
|
| 2486 |
func TestForTestField(t *testing.T) { |
| 2487 |
testAllOrModulesParallel(t, testForTestField) |
| 2488 |
} |
| 2489 |
func testForTestField(t *testing.T, exporter packagestest.Exporter) { |
| 2490 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 2491 |
Name: "golang.org/fake", |
| 2492 |
Files: map[string]any{ |
| 2493 |
"a/a.go": `package a; func hello() {};`, |
| 2494 |
"a/a_test.go": `package a; import "testing"; func TestA1(t *testing.T) {};`, |
| 2495 |
"a/x_test.go": `package a_test; import "testing"; func TestA2(t *testing.T) {};`, |
| 2496 |
}}}) |
| 2497 |
defer exported.Cleanup() |
| 2498 |
|
| 2499 |
// Add overlays to make sure they don't affect anything. |
| 2500 |
exported.Config.Overlay = map[string][]byte{ |
| 2501 |
"a/a_test.go": []byte(`package a; import "testing"; func TestA1(t *testing.T) { hello(); };`), |
| 2502 |
"a/x_test.go": []byte(`package a_test; import "testing"; func TestA2(t *testing.T) { hello(); };`), |
| 2503 |
} |
| 2504 |
exported.Config.Tests = true |
| 2505 |
exported.Config.Mode = packages.NeedName | packages.NeedImports |
| 2506 |
forTest := "golang.org/fake/a" |
| 2507 |
pkgs, err := packages.Load(exported.Config, forTest) |
| 2508 |
if err != nil { |
| 2509 |
t.Fatal(err) |
| 2510 |
} |
| 2511 |
if len(pkgs) != 4 { |
| 2512 |
t.Errorf("expected 4 packages, got %v", len(pkgs)) |
| 2513 |
} |
| 2514 |
for _, pkg := range pkgs { |
| 2515 |
var hasTestFile bool |
| 2516 |
for _, f := range pkg.CompiledGoFiles { |
| 2517 |
if strings.Contains(f, "a_test.go") || strings.Contains(f, "x_test.go") { |
| 2518 |
hasTestFile = true |
| 2519 |
break |
| 2520 |
} |
| 2521 |
} |
| 2522 |
if !hasTestFile { |
| 2523 |
continue |
| 2524 |
} |
| 2525 |
if got := pkg.ForTest; got != forTest { |
| 2526 |
t.Errorf("expected %q, got %q", forTest, got) |
| 2527 |
} |
| 2528 |
} |
| 2529 |
} |
| 2530 |
|
| 2531 |
func TestIssue37629(t *testing.T) { |
| 2532 |
testAllOrModulesParallel(t, testIssue37629) |
| 2533 |
} |
| 2534 |
func testIssue37629(t *testing.T, exporter packagestest.Exporter) { |
| 2535 |
// Tests #37629. When automatic vendoring is triggered, and we try to determine |
| 2536 |
// the module root dir for a new overlay package, we previously would do a go list -m all, |
| 2537 |
// which is incompatible with automatic vendoring. |
| 2538 |
|
| 2539 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 2540 |
Name: "golang.org/fake", |
| 2541 |
Files: map[string]any{ |
| 2542 |
"c/c2.go": `package c`, |
| 2543 |
"a/a.go": `package a; import "b.com/b"; const A = b.B`, |
| 2544 |
"vendor/b.com/b/b.go": `package b; const B = 4`, |
| 2545 |
"vendor/modules.txt": `# b.com/b v1.0.0 |
| 2546 |
## explicit |
| 2547 |
b.com/b`, |
| 2548 |
}}, { |
| 2549 |
Name: "b.com/[email protected]", |
| 2550 |
Files: map[string]any{ |
| 2551 |
"arbitrary.txt": "", |
| 2552 |
}}, |
| 2553 |
}) |
| 2554 |
rootDir := filepath.Dir(filepath.Dir(exported.File("golang.org/fake", "a/a.go"))) |
| 2555 |
exported.Config.Overlay = map[string][]byte{ |
| 2556 |
filepath.Join(rootDir, "c/c.go"): []byte(`package c; import "golang.org/fake/a"; const C = a.A`), |
| 2557 |
} |
| 2558 |
exported.Config.Env = append(exported.Config.Env, "GOFLAGS=-mod=vendor") |
| 2559 |
exported.Config.Mode = packages.LoadAllSyntax |
| 2560 |
|
| 2561 |
defer exported.Cleanup() |
| 2562 |
|
| 2563 |
initial, err := packages.Load(exported.Config, "golang.org/fake/c") |
| 2564 |
if err != nil { |
| 2565 |
t.Fatal(err) |
| 2566 |
} |
| 2567 |
|
| 2568 |
// Check value of a.A. |
| 2569 |
a := initial[0] |
| 2570 |
aA := constant(a, "C") |
| 2571 |
if aA == nil { |
| 2572 |
t.Fatalf("a.A: got nil") |
| 2573 |
} |
| 2574 |
got := aA.Val().String() |
| 2575 |
if got != "4" { |
| 2576 |
t.Errorf("a.A: got %s, want %s", got, "4") |
| 2577 |
} |
| 2578 |
} |
| 2579 |
|
| 2580 |
func TestIssue37098(t *testing.T) { testAllOrModulesParallel(t, testIssue37098) } |
| 2581 |
func testIssue37098(t *testing.T, exporter packagestest.Exporter) { |
| 2582 |
// packages.Load should only return Go sources in |
| 2583 |
// (*Package).CompiledGoFiles. This tests #37098, where using SWIG to |
| 2584 |
// causes C++ sources to be inadvertently included in |
| 2585 |
// (*Package).CompiledGoFiles. |
| 2586 |
|
| 2587 |
if _, err := exec.LookPath("swig"); err != nil { |
| 2588 |
t.Skip("skipping test: swig not available") |
| 2589 |
} |
| 2590 |
if _, err := exec.LookPath("g++"); err != nil { |
| 2591 |
t.Skip("skipping test: g++ not available") |
| 2592 |
} |
| 2593 |
|
| 2594 |
// Create a fake package with an empty Go source, and a SWIG interface |
| 2595 |
// file. |
| 2596 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 2597 |
Name: "golang.org/fake", |
| 2598 |
Files: map[string]any{ |
| 2599 |
// The "package" statement must be included for SWIG sources to |
| 2600 |
// be generated. |
| 2601 |
"a/a.go": "package a", |
| 2602 |
"a/a.swigcxx": "", |
| 2603 |
}}}) |
| 2604 |
defer exported.Cleanup() |
| 2605 |
|
| 2606 |
initial, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 2607 |
if err != nil { |
| 2608 |
t.Fatalf("failed to load the package: %v", err) |
| 2609 |
} |
| 2610 |
// Try and parse each of the files |
| 2611 |
for _, pkg := range initial { |
| 2612 |
for _, file := range pkg.CompiledGoFiles { |
| 2613 |
|
| 2614 |
// Validate that each file can be parsed as a Go source. |
| 2615 |
fset := token.NewFileSet() |
| 2616 |
_, err := parser.ParseFile(fset, file, nil, parser.ImportsOnly) |
| 2617 |
if err != nil { |
| 2618 |
t.Errorf("Failed to parse file '%s' as a Go source: %v", file, err) |
| 2619 |
|
| 2620 |
contents, err := os.ReadFile(file) |
| 2621 |
if err != nil { |
| 2622 |
t.Fatalf("Failed to read the un-parsable file '%s': %v", file, err) |
| 2623 |
} |
| 2624 |
|
| 2625 |
// Print out some of the un-parsable file to aid in debugging. |
| 2626 |
n := len(contents) |
| 2627 |
|
| 2628 |
// Don't print the whole file if it is too large. |
| 2629 |
const maxBytes = 1000 |
| 2630 |
if n > maxBytes { |
| 2631 |
n = maxBytes |
| 2632 |
} |
| 2633 |
|
| 2634 |
t.Logf("First %d bytes of un-parsable file: %s", n, contents[:n]) |
| 2635 |
} |
| 2636 |
} |
| 2637 |
} |
| 2638 |
} |
| 2639 |
|
| 2640 |
// TestIssue56632 checks that CompiledGoFiles does not contain non-go files regardless of |
| 2641 |
// whether the NeedFiles mode bit is set. |
| 2642 |
func TestIssue56632(t *testing.T) { |
| 2643 |
t.Parallel() |
| 2644 |
testenv.NeedsGoBuild(t) |
| 2645 |
testenv.NeedsTool(t, "cgo") |
| 2646 |
|
| 2647 |
exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{{ |
| 2648 |
Name: "golang.org/issue56632", |
| 2649 |
Files: map[string]any{ |
| 2650 |
"a/a.go": `package a`, |
| 2651 |
"a/a_cgo.go": `package a |
| 2652 |
|
| 2653 |
import "C"`, |
| 2654 |
"a/a.s": ``, |
| 2655 |
"a/a.c": ``, |
| 2656 |
}}}) |
| 2657 |
defer exported.Cleanup() |
| 2658 |
|
| 2659 |
modes := []packages.LoadMode{packages.NeedCompiledGoFiles, packages.NeedCompiledGoFiles | packages.NeedFiles, packages.NeedImports | packages.NeedCompiledGoFiles, packages.NeedImports | packages.NeedFiles | packages.NeedCompiledGoFiles} |
| 2660 |
for _, mode := range modes { |
| 2661 |
exported.Config.Mode = mode |
| 2662 |
|
| 2663 |
initial, err := packages.Load(exported.Config, "golang.org/issue56632/a") |
| 2664 |
if err != nil { |
| 2665 |
t.Fatalf("failed to load package: %v", err) |
| 2666 |
} |
| 2667 |
|
| 2668 |
if len(initial) != 1 { |
| 2669 |
t.Errorf("expected 3 packages, got %d", len(initial)) |
| 2670 |
} |
| 2671 |
|
| 2672 |
p := initial[0] |
| 2673 |
|
| 2674 |
if len(p.Errors) != 0 { |
| 2675 |
t.Errorf("expected no errors, got %v", p.Errors) |
| 2676 |
} |
| 2677 |
|
| 2678 |
for _, f := range p.CompiledGoFiles { |
| 2679 |
if strings.HasSuffix(f, ".s") || strings.HasSuffix(f, ".c") { |
| 2680 |
t.Errorf("expected no non-Go CompiledGoFiles, got file %q in CompiledGoFiles", f) |
| 2681 |
} |
| 2682 |
} |
| 2683 |
} |
| 2684 |
} |
| 2685 |
|
| 2686 |
// TestInvalidFilesInXTest checks the fix for golang/go#37971 in Go 1.15. |
| 2687 |
func TestInvalidFilesInXTest(t *testing.T) { testAllOrModulesParallel(t, testInvalidFilesInXTest) } |
| 2688 |
func testInvalidFilesInXTest(t *testing.T, exporter packagestest.Exporter) { |
| 2689 |
exported := packagestest.Export(t, exporter, []packagestest.Module{ |
| 2690 |
{ |
| 2691 |
Name: "golang.org/fake", |
| 2692 |
Files: map[string]any{ |
| 2693 |
"d/d.go": `package d; import "net/http"; const d = http.MethodGet; func Get() string { return d; }`, |
| 2694 |
"d/d2.go": ``, // invalid file |
| 2695 |
"d/d_test.go": `package d_test; import "testing"; import "golang.org/fake/d"; func TestD(t *testing.T) { d.Get(); }`, |
| 2696 |
}, |
| 2697 |
}, |
| 2698 |
}) |
| 2699 |
defer exported.Cleanup() |
| 2700 |
|
| 2701 |
exported.Config.Mode = packages.NeedName | packages.NeedFiles |
| 2702 |
exported.Config.Tests = true |
| 2703 |
|
| 2704 |
initial, err := packages.Load(exported.Config, "golang.org/fake/d") |
| 2705 |
if err != nil { |
| 2706 |
t.Fatal(err) |
| 2707 |
} |
| 2708 |
if len(initial) != 3 { |
| 2709 |
t.Errorf("expected 3 packages, got %d", len(initial)) |
| 2710 |
} |
| 2711 |
} |
| 2712 |
|
| 2713 |
func TestTypecheckCgo(t *testing.T) { testAllOrModulesParallel(t, testTypecheckCgo) } |
| 2714 |
func testTypecheckCgo(t *testing.T, exporter packagestest.Exporter) { |
| 2715 |
testenv.NeedsTool(t, "cgo") |
| 2716 |
|
| 2717 |
const cgo = `package cgo |
| 2718 |
import "C" |
| 2719 |
|
| 2720 |
func Example() { |
| 2721 |
C.CString("hi") |
| 2722 |
} |
| 2723 |
` |
| 2724 |
exported := packagestest.Export(t, exporter, []packagestest.Module{ |
| 2725 |
{ |
| 2726 |
Name: "golang.org/fake", |
| 2727 |
Files: map[string]any{ |
| 2728 |
"cgo/cgo.go": cgo, |
| 2729 |
}, |
| 2730 |
}, |
| 2731 |
}) |
| 2732 |
defer exported.Cleanup() |
| 2733 |
|
| 2734 |
exported.Config.Mode = packages.NeedFiles | packages.NeedCompiledGoFiles | |
| 2735 |
packages.NeedSyntax | packages.NeedDeps | packages.NeedTypes | |
| 2736 |
packages.LoadMode(packagesinternal.TypecheckCgo) |
| 2737 |
|
| 2738 |
initial, err := packages.Load(exported.Config, "golang.org/fake/cgo") |
| 2739 |
if err != nil { |
| 2740 |
t.Fatal(err) |
| 2741 |
} |
| 2742 |
pkg := initial[0] |
| 2743 |
if len(pkg.Errors) != 0 { |
| 2744 |
t.Fatalf("package has errors: %v", pkg.Errors) |
| 2745 |
} |
| 2746 |
|
| 2747 |
expos := pkg.Types.Scope().Lookup("Example").Pos() |
| 2748 |
fname := pkg.Fset.File(expos).Name() |
| 2749 |
if !strings.HasSuffix(fname, "cgo.go") { |
| 2750 |
t.Errorf("position for cgo package was loaded from %v, wanted cgo.go", fname) |
| 2751 |
} |
| 2752 |
} |
| 2753 |
|
| 2754 |
// TestIssue48226 ensures that when NeedSyntax is provided we do not nullify the |
| 2755 |
// Fset, which is needed to resolve the syntax tree element positions to files. |
| 2756 |
func TestIssue48226(t *testing.T) { testAllOrModulesParallel(t, testIssue48226) } |
| 2757 |
func testIssue48226(t *testing.T, exporter packagestest.Exporter) { |
| 2758 |
exported := packagestest.Export(t, exporter, []packagestest.Module{ |
| 2759 |
{ |
| 2760 |
Name: "golang.org/fake/syntax", |
| 2761 |
Files: map[string]any{ |
| 2762 |
"syntax.go": `package test`, |
| 2763 |
}, |
| 2764 |
}, |
| 2765 |
}) |
| 2766 |
defer exported.Cleanup() |
| 2767 |
|
| 2768 |
exported.Config.Mode = packages.NeedFiles | packages.NeedSyntax |
| 2769 |
|
| 2770 |
initial, err := packages.Load(exported.Config, "golang.org/fake/syntax") |
| 2771 |
if err != nil { |
| 2772 |
t.Fatal(err) |
| 2773 |
} |
| 2774 |
if len(initial) != 1 { |
| 2775 |
t.Fatalf("expected 1 package, got %d", len(initial)) |
| 2776 |
} |
| 2777 |
pkg := initial[0] |
| 2778 |
|
| 2779 |
if len(pkg.Errors) != 0 { |
| 2780 |
t.Fatalf("package has errors: %v", pkg.Errors) |
| 2781 |
} |
| 2782 |
|
| 2783 |
fname := pkg.Fset.File(pkg.Syntax[0].FileStart).Name() |
| 2784 |
if filepath.Base(fname) != "syntax.go" { |
| 2785 |
t.Errorf("expected the package declaration position "+ |
| 2786 |
"to resolve to \"syntax.go\", got %q instead", fname) |
| 2787 |
} |
| 2788 |
} |
| 2789 |
|
| 2790 |
func TestModule(t *testing.T) { |
| 2791 |
testAllOrModulesParallel(t, testModule) |
| 2792 |
} |
| 2793 |
func testModule(t *testing.T, exporter packagestest.Exporter) { |
| 2794 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 2795 |
Name: "golang.org/fake", |
| 2796 |
Files: map[string]any{"a/a.go": `package a`}}}) |
| 2797 |
exported.Config.Mode = packages.NeedModule |
| 2798 |
rootDir := filepath.Dir(filepath.Dir(exported.File("golang.org/fake", "a/a.go"))) |
| 2799 |
|
| 2800 |
initial, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 2801 |
if err != nil { |
| 2802 |
t.Fatal(err) |
| 2803 |
} |
| 2804 |
|
| 2805 |
if len(initial) != 1 { |
| 2806 |
t.Fatal("want exactly one package, got ", initial) |
| 2807 |
} |
| 2808 |
a := initial[0] |
| 2809 |
switch exported.Exporter.Name() { |
| 2810 |
case "GOPATH": |
| 2811 |
if a.Module != nil { |
| 2812 |
t.Fatal("package.Module: want nil, got ", a.Module) |
| 2813 |
} |
| 2814 |
case "Modules": |
| 2815 |
// Make sure Modules field is set, and spot check a few of its fields. |
| 2816 |
if a.Module == nil { |
| 2817 |
t.Fatal("package.Module: want non-nil, got nil") |
| 2818 |
} |
| 2819 |
if a.Module.Path != "golang.org/fake" { |
| 2820 |
t.Fatalf("package.Module.Path: want \"golang.org/fake\", got %q", a.Module.Path) |
| 2821 |
} |
| 2822 |
if a.Module.GoMod != filepath.Join(rootDir, "go.mod") { |
| 2823 |
t.Fatalf("package.Module.GoMod: want %q, got %q", filepath.Join(rootDir, "go.mod"), a.Module.GoMod) |
| 2824 |
} |
| 2825 |
default: |
| 2826 |
t.Fatalf("Expected exporter to be GOPATH or Modules, got %v", exported.Exporter.Name()) |
| 2827 |
} |
| 2828 |
} |
| 2829 |
|
| 2830 |
func TestExternal_NotHandled(t *testing.T) { |
| 2831 |
testAllOrModulesParallel(t, testExternal_NotHandled) |
| 2832 |
} |
| 2833 |
func testExternal_NotHandled(t *testing.T, exporter packagestest.Exporter) { |
| 2834 |
skipIfShort(t, "builds and links fake driver binaries") |
| 2835 |
testenv.NeedsGoBuild(t) |
| 2836 |
|
| 2837 |
tempdir, err := os.MkdirTemp("", "testexternal") |
| 2838 |
if err != nil { |
| 2839 |
t.Fatal(err) |
| 2840 |
} |
| 2841 |
defer os.RemoveAll(tempdir) |
| 2842 |
|
| 2843 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 2844 |
Name: "golang.org/fake", |
| 2845 |
Files: map[string]any{ |
| 2846 |
"a/a.go": `package a`, |
| 2847 |
"empty_driver/main.go": `package main |
| 2848 |
|
| 2849 |
import ( |
| 2850 |
"fmt" |
| 2851 |
"io" |
| 2852 |
"os" |
| 2853 |
) |
| 2854 |
|
| 2855 |
func main() { |
| 2856 |
io.ReadAll(os.Stdin) |
| 2857 |
fmt.Println("{}") |
| 2858 |
} |
| 2859 |
`, |
| 2860 |
"nothandled_driver/main.go": `package main |
| 2861 |
|
| 2862 |
import ( |
| 2863 |
"fmt" |
| 2864 |
"io" |
| 2865 |
"os" |
| 2866 |
) |
| 2867 |
|
| 2868 |
func main() { |
| 2869 |
io.ReadAll(os.Stdin) |
| 2870 |
fmt.Println("{\"NotHandled\": true}") |
| 2871 |
} |
| 2872 |
`, |
| 2873 |
}}}) |
| 2874 |
baseEnv := exported.Config.Env |
| 2875 |
|
| 2876 |
// As a control, create a fake driver that always returns an empty response. |
| 2877 |
emptyDriverPath := filepath.Join(tempdir, "empty_driver.exe") // Add .exe because Windows expects it. |
| 2878 |
cmd := exec.Command("go", "build", "-o", emptyDriverPath, "golang.org/fake/empty_driver") |
| 2879 |
cmd.Env = baseEnv |
| 2880 |
cmd.Dir = exported.Config.Dir |
| 2881 |
if b, err := cmd.CombinedOutput(); err != nil { |
| 2882 |
t.Log(string(b)) |
| 2883 |
t.Fatal(err) |
| 2884 |
} |
| 2885 |
|
| 2886 |
exported.Config.Env = append(slices.Clone(baseEnv), "GOPACKAGESDRIVER="+emptyDriverPath) |
| 2887 |
initial, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 2888 |
if err != nil { |
| 2889 |
t.Fatal(err) |
| 2890 |
} |
| 2891 |
|
| 2892 |
if len(initial) != 0 { |
| 2893 |
t.Errorf("package.Load with empty driver: want [], got %v", initial) |
| 2894 |
} |
| 2895 |
|
| 2896 |
// Create a fake driver that always returns a NotHandled response. |
| 2897 |
notHandledDriverPath := filepath.Join(tempdir, "nothandled_driver.exe") |
| 2898 |
cmd = exec.Command("go", "build", "-o", notHandledDriverPath, "golang.org/fake/nothandled_driver") |
| 2899 |
cmd.Env = baseEnv |
| 2900 |
cmd.Dir = exported.Config.Dir |
| 2901 |
if b, err := cmd.CombinedOutput(); err != nil { |
| 2902 |
t.Log(string(b)) |
| 2903 |
t.Fatal(err) |
| 2904 |
} |
| 2905 |
|
| 2906 |
exported.Config.Env = append(slices.Clone(baseEnv), "GOPACKAGESDRIVER="+notHandledDriverPath) |
| 2907 |
initial, err = packages.Load(exported.Config, "golang.org/fake/a") |
| 2908 |
if err != nil { |
| 2909 |
t.Fatal(err) |
| 2910 |
} |
| 2911 |
|
| 2912 |
if len(initial) != 1 || initial[0].PkgPath != "golang.org/fake/a" { |
| 2913 |
t.Errorf("package.Load: want [golang.org/fake/a], got %v", initial) |
| 2914 |
} |
| 2915 |
} |
| 2916 |
|
| 2917 |
func TestInvalidPackageName(t *testing.T) { |
| 2918 |
testAllOrModulesParallel(t, testInvalidPackageName) |
| 2919 |
} |
| 2920 |
|
| 2921 |
func testInvalidPackageName(t *testing.T, exporter packagestest.Exporter) { |
| 2922 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 2923 |
Name: "golang.org/fake", |
| 2924 |
Files: map[string]any{ |
| 2925 |
"main.go": `package default |
| 2926 |
|
| 2927 |
func main() { |
| 2928 |
} |
| 2929 |
`, |
| 2930 |
}, |
| 2931 |
}}) |
| 2932 |
defer exported.Cleanup() |
| 2933 |
|
| 2934 |
initial, err := packages.Load(exported.Config, "golang.org/fake") |
| 2935 |
if err != nil { |
| 2936 |
t.Fatal(err) |
| 2937 |
} |
| 2938 |
pkg := initial[0] |
| 2939 |
if len(pkg.CompiledGoFiles) != 1 { |
| 2940 |
t.Fatalf("expected 1 Go file in package %s, got %v", pkg.ID, len(pkg.CompiledGoFiles)) |
| 2941 |
} |
| 2942 |
} |
| 2943 |
|
| 2944 |
func TestEmptyEnvironment(t *testing.T) { |
| 2945 |
t.Parallel() |
| 2946 |
|
| 2947 |
cfg := &packages.Config{ |
| 2948 |
Env: []string{"FOO=BAR"}, |
| 2949 |
} |
| 2950 |
_, err := packages.Load(cfg, "fmt") |
| 2951 |
if err == nil { |
| 2952 |
t.Fatal("Load with explicitly empty environment should fail") |
| 2953 |
} |
| 2954 |
} |
| 2955 |
|
| 2956 |
func TestPackageLoadSingleFile(t *testing.T) { |
| 2957 |
testenv.NeedsTool(t, "go") |
| 2958 |
|
| 2959 |
tmp, err := os.MkdirTemp("", "a") |
| 2960 |
if err != nil { |
| 2961 |
t.Fatal(err) |
| 2962 |
} |
| 2963 |
defer os.RemoveAll(tmp) |
| 2964 |
|
| 2965 |
filename := filepath.Join(tmp, "a.go") |
| 2966 |
|
| 2967 |
if err := os.WriteFile(filename, []byte(`package main; func main() { println("hello world") }`), 0775); err != nil { |
| 2968 |
t.Fatal(err) |
| 2969 |
} |
| 2970 |
|
| 2971 |
pkgs, err := packages.Load(&packages.Config{Mode: packages.LoadSyntax, Dir: tmp}, "file="+filename) |
| 2972 |
if err != nil { |
| 2973 |
t.Fatalf("could not load package: %v", err) |
| 2974 |
} |
| 2975 |
if len(pkgs) != 1 { |
| 2976 |
t.Fatalf("expected one package to be loaded, got %d", len(pkgs)) |
| 2977 |
} |
| 2978 |
if len(pkgs[0].CompiledGoFiles) != 1 || pkgs[0].CompiledGoFiles[0] != filename { |
| 2979 |
t.Fatalf("expected one compiled go file (%q), got %v", filename, pkgs[0].CompiledGoFiles) |
| 2980 |
} |
| 2981 |
} |
| 2982 |
|
| 2983 |
func errorMessages(errors []packages.Error) []string { |
| 2984 |
var msgs []string |
| 2985 |
for _, err := range errors { |
| 2986 |
msgs = append(msgs, err.Msg) |
| 2987 |
} |
| 2988 |
return msgs |
| 2989 |
} |
| 2990 |
|
| 2991 |
func srcs(p *packages.Package) []string { |
| 2992 |
var files []string |
| 2993 |
files = append(files, p.GoFiles...) |
| 2994 |
files = append(files, p.OtherFiles...) |
| 2995 |
files = append(files, p.EmbedFiles...) |
| 2996 |
return cleanPaths(files) |
| 2997 |
} |
| 2998 |
|
| 2999 |
// cleanPaths attempts to reduce path names to stable forms |
| 3000 |
func cleanPaths(paths []string) []string { |
| 3001 |
result := make([]string, len(paths)) |
| 3002 |
for i, src := range paths { |
| 3003 |
// If the source file doesn't have an extension like .go or .s, |
| 3004 |
// it comes from GOCACHE. The names there aren't predictable. |
| 3005 |
name := filepath.Base(src) |
| 3006 |
if !strings.Contains(name, ".") { |
| 3007 |
result[i] = fmt.Sprintf("%d.go", i) // make cache names predictable |
| 3008 |
} else { |
| 3009 |
result[i] = name |
| 3010 |
} |
| 3011 |
} |
| 3012 |
return result |
| 3013 |
} |
| 3014 |
|
| 3015 |
// importGraph returns the import graph as a user-friendly string, |
| 3016 |
// and a map containing all packages keyed by ID. |
| 3017 |
func importGraph(initial []*packages.Package) (string, map[string]*packages.Package) { |
| 3018 |
out := new(bytes.Buffer) |
| 3019 |
|
| 3020 |
initialSet := make(map[*packages.Package]bool) |
| 3021 |
for _, p := range initial { |
| 3022 |
initialSet[p] = true |
| 3023 |
} |
| 3024 |
|
| 3025 |
// We can't use Visit or Postorder because we need to prune |
| 3026 |
// the traversal of specific edges, not just nodes. |
| 3027 |
var nodes, edges []string |
| 3028 |
res := make(map[string]*packages.Package) |
| 3029 |
seen := make(map[*packages.Package]bool) |
| 3030 |
var visit func(p *packages.Package) |
| 3031 |
visit = func(p *packages.Package) { |
| 3032 |
if !seen[p] { |
| 3033 |
seen[p] = true |
| 3034 |
if res[p.ID] != nil { |
| 3035 |
panic("duplicate ID: " + p.ID) |
| 3036 |
} |
| 3037 |
res[p.ID] = p |
| 3038 |
|
| 3039 |
star := ' ' // mark initial packages with a star |
| 3040 |
if initialSet[p] { |
| 3041 |
star = '*' |
| 3042 |
} |
| 3043 |
nodes = append(nodes, fmt.Sprintf("%c %s", star, p.ID)) |
| 3044 |
|
| 3045 |
// To avoid a lot of noise, |
| 3046 |
// we prune uninteresting dependencies of testmain packages, |
| 3047 |
// which we identify by this import: |
| 3048 |
isTestMain := p.Imports["testing/internal/testdeps"] != nil |
| 3049 |
|
| 3050 |
for _, imp := range p.Imports { |
| 3051 |
if isTestMain { |
| 3052 |
switch imp.ID { |
| 3053 |
case "os", "reflect", "testing", "testing/internal/testdeps": |
| 3054 |
continue |
| 3055 |
} |
| 3056 |
} |
| 3057 |
// math/bits took on a dependency on unsafe in 1.12, which breaks some |
| 3058 |
// tests. As a short term hack, prune that edge. |
| 3059 |
// ditto for ("errors", "internal/reflectlite") in 1.13. |
| 3060 |
// TODO(matloob): think of a cleaner solution, or remove math/bits from the test. |
| 3061 |
if p.ID == "math/bits" && imp.ID == "unsafe" { |
| 3062 |
continue |
| 3063 |
} |
| 3064 |
edges = append(edges, fmt.Sprintf("%s -> %s", p, imp)) |
| 3065 |
visit(imp) |
| 3066 |
} |
| 3067 |
} |
| 3068 |
} |
| 3069 |
for _, p := range initial { |
| 3070 |
visit(p) |
| 3071 |
} |
| 3072 |
|
| 3073 |
// Sort, ignoring leading optional star prefix. |
| 3074 |
sort.Slice(nodes, func(i, j int) bool { return nodes[i][2:] < nodes[j][2:] }) |
| 3075 |
for _, node := range nodes { |
| 3076 |
fmt.Fprintf(out, "%s\n", node) |
| 3077 |
} |
| 3078 |
|
| 3079 |
sort.Strings(edges) |
| 3080 |
for _, edge := range edges { |
| 3081 |
fmt.Fprintf(out, " %s\n", edge) |
| 3082 |
} |
| 3083 |
|
| 3084 |
return out.String(), res |
| 3085 |
} |
| 3086 |
|
| 3087 |
func constant(p *packages.Package, name string) *types.Const { |
| 3088 |
if p == nil || p.Types == nil { |
| 3089 |
return nil |
| 3090 |
} |
| 3091 |
c := p.Types.Scope().Lookup(name) |
| 3092 |
if c == nil { |
| 3093 |
return nil |
| 3094 |
} |
| 3095 |
return c.(*types.Const) |
| 3096 |
} |
| 3097 |
|
| 3098 |
func TestExportFile(t *testing.T) { |
| 3099 |
// This used to trigger the log.Fatal in loadFromExportData. |
| 3100 |
// See go.dev/issue/45584. |
| 3101 |
cfg := new(packages.Config) |
| 3102 |
cfg.Mode = packages.NeedTypes |
| 3103 |
packages.Load(cfg, "fmt") |
| 3104 |
} |
| 3105 |
|
| 3106 |
// TestLoadEitherSucceedsOrFails is an attempt to reproduce a sporadic |
| 3107 |
// failure observed on the Android emu builders in which Load would |
| 3108 |
// return an empty list of packages but no error. We don't expect |
| 3109 |
// packages.Load to succeed on that platform, and testenv.NeedsGoBuild |
| 3110 |
// would ordinarily suppress the attempt if called early. But |
| 3111 |
// regardless of whether the 'go' command is functional, Load should |
| 3112 |
// never return an empty set of packages but no error. |
| 3113 |
func TestLoadEitherSucceedsOrFails(t *testing.T) { |
| 3114 |
const src = `package p` |
| 3115 |
dir := t.TempDir() |
| 3116 |
cfg := &packages.Config{ |
| 3117 |
Dir: dir, |
| 3118 |
Mode: packages.LoadSyntax, |
| 3119 |
Overlay: map[string][]byte{ |
| 3120 |
filepath.Join(dir, "p.go"): []byte(src), |
| 3121 |
}, |
| 3122 |
} |
| 3123 |
initial, err := packages.Load(cfg, "./p.go") |
| 3124 |
if err != nil { |
| 3125 |
// If Load failed because it needed 'go' and the |
| 3126 |
// platform doesn't have it, silently skip the test. |
| 3127 |
testenv.NeedsGoBuild(t) |
| 3128 |
|
| 3129 |
// Otherwise, it's a real failure. |
| 3130 |
t.Fatal(err) |
| 3131 |
} |
| 3132 |
|
| 3133 |
// If Load returned without error, |
| 3134 |
// it had better give us error-free packages. |
| 3135 |
if packages.PrintErrors(initial) > 0 { |
| 3136 |
t.Errorf("packages contain errors") |
| 3137 |
} |
| 3138 |
|
| 3139 |
// If Load returned without error, |
| 3140 |
// it had better give us the correct number packages. |
| 3141 |
if len(initial) != 1 { |
| 3142 |
t.Errorf("Load returned %d packages (want 1) and no error", len(initial)) |
| 3143 |
} |
| 3144 |
} |
| 3145 |
|
| 3146 |
// TestLoadOverlayGoMod ensures that overlays containing go.mod files |
| 3147 |
// are effective for all 'go list' calls made by go/packages (#67644). |
| 3148 |
func TestLoadOverlayGoMod(t *testing.T) { |
| •3149 |
t.Skip("needs Go mod") |
| 3150 |
testenv.NeedsGoBuild(t) |
| 3151 |
|
| 3152 |
cwd, _ := os.Getwd() |
| 3153 |
|
| 3154 |
// This test ensures that the overlaid go.mod file is seen by |
| 3155 |
// all runs of 'go list', in particular the early run that |
| 3156 |
// enumerates the modules: if the go.mod file were absent, |
| 3157 |
// it would ascend to the parent directory (x/tools) and |
| 3158 |
// then (falsely) report inconsistent vendoring. |
| 3159 |
// |
| 3160 |
// (Ideally the testdata would be constructed from nothing |
| 3161 |
// rather than rely on the go/packages source tree, but it is |
| 3162 |
// turned out to a bigger project than bargained for.) |
| 3163 |
cfg := &packages.Config{ |
| 3164 |
Mode: packages.LoadSyntax, |
| 3165 |
Overlay: map[string][]byte{ |
| 3166 |
filepath.Join(cwd, "go.mod"): []byte("module example.com\ngo 1.0"), |
| 3167 |
}, |
| 3168 |
Env: append(os.Environ(), "GOFLAGS=-mod=vendor", "GOWORK=off"), |
| 3169 |
} |
| 3170 |
|
| 3171 |
pkgs, err := packages.Load(cfg, "./testdata") |
| 3172 |
if err != nil { |
| 3173 |
t.Fatal(err) // (would previously fail here with "inconsistent vendoring") |
| 3174 |
} |
| 3175 |
got := fmt.Sprint(pkgs) |
| 3176 |
want := `[./testdata]` |
| 3177 |
if got != want { |
| 3178 |
t.Errorf("Load: got %s, want %v", got, want) |
| 3179 |
} |
| 3180 |
} |
| 3181 |
|
| 3182 |
func overlayFS(overlay map[string][]byte) fstest.MapFS { |
| 3183 |
fs := make(fstest.MapFS) |
| 3184 |
for name, data := range overlay { |
| 3185 |
fs[name] = &fstest.MapFile{Data: data} |
| 3186 |
} |
| 3187 |
return fs |
| 3188 |
} |
| 3189 |
|
| 3190 |
// TestIssue69606a tests when tools in $GOROOT/pkg/tool/$GOOS_$GOARCH are missing, |
| 3191 |
// Load should return an error. |
| 3192 |
func TestIssue69606a(t *testing.T) { |
| 3193 |
testenv.NeedsTool(t, "go") |
| 3194 |
overlay := overlayFS(map[string][]byte{ |
| 3195 |
"io/io.go": []byte("package io"), |
| 3196 |
"unsafe/unsafe.go": []byte("package unsafe"), |
| 3197 |
}) |
| 3198 |
goroot := testfiles.CopyToTmp(t, overlay) |
| 3199 |
|
| 3200 |
t.Logf("custom GOROOT: %s", goroot) |
| 3201 |
|
| 3202 |
// load the std packages under a custom GOROOT |
| 3203 |
_, err := packages.Load(&packages.Config{ |
| 3204 |
Mode: packages.NeedName | |
| 3205 |
packages.NeedFiles | |
| 3206 |
packages.NeedImports | |
| 3207 |
packages.NeedTypes, |
| 3208 |
Env: append( |
| 3209 |
os.Environ(), |
| 3210 |
"GO111MODULES=on", |
| 3211 |
"GOPATH=", |
| 3212 |
"GOWORK=off", |
| 3213 |
"GOPROXY=off", |
| 3214 |
fmt.Sprintf("GOROOT=%s", goroot)), |
| 3215 |
}, "std") |
| 3216 |
|
| 3217 |
if err == nil { |
| 3218 |
t.Fatal("Expected to get an error because missing tool 'compile' but got a nil error") |
| 3219 |
} |
| 3220 |
} |
| 3221 |
|
| 3222 |
// TestIssue69606b tests when loading std from a fake goroot without a unsafe package, |
| 3223 |
// Load should return an error. |
| 3224 |
func TestIssue69606b(t *testing.T) { |
| 3225 |
testenv.NeedsTool(t, "go") |
| 3226 |
overlay := overlayFS(map[string][]byte{ |
| 3227 |
"io/io.go": []byte("package io"), |
| 3228 |
}) |
| 3229 |
goroot := testfiles.CopyToTmp(t, overlay) |
| 3230 |
|
| 3231 |
t.Logf("custom GOROOT: %s", goroot) |
| 3232 |
|
| 3233 |
// load the std packages under a custom GOROOT |
| 3234 |
_, err := packages.Load(&packages.Config{ |
| 3235 |
Mode: packages.NeedName | |
| 3236 |
packages.NeedFiles | |
| 3237 |
packages.NeedImports | |
| 3238 |
packages.NeedTypes, |
| 3239 |
Env: append( |
| 3240 |
os.Environ(), |
| 3241 |
"GO111MODULES=on", |
| 3242 |
"GOPATH=", |
| 3243 |
"GOWORK=off", |
| 3244 |
"GOPROXY=off", |
| 3245 |
fmt.Sprintf("GOROOT=%s", goroot)), |
| 3246 |
}, "std") |
| 3247 |
|
| 3248 |
if err == nil { |
| 3249 |
t.Fatal("Expected to get an error because missing unsafe package but got a nil error") |
| 3250 |
} |
| 3251 |
} |
| 3252 |
|
| 3253 |
// TestIssue70394 tests materializing an alias type defined in a package (m/a) |
| 3254 |
// in another package (m/b) where the types for m/b are coming from the compiler, |
| 3255 |
// e.g. `go list -compiled=true ... m/b`. |
| 3256 |
func TestIssue70394(t *testing.T) { |
| 3257 |
testenv.NeedsGo1Point(t, 23) |
| 3258 |
testenv.NeedsTool(t, "go") // requires go list. |
| 3259 |
testenv.NeedsGoBuild(t) // requires the compiler for export data. |
| 3260 |
|
| 3261 |
dir := t.TempDir() |
| 3262 |
overlay := map[string][]byte{ |
| 3263 |
filepath.Join(dir, "go.mod"): []byte("module m"), // go version of the module does not matter. |
| 3264 |
filepath.Join(dir, "a/a.go"): []byte(`package a; type A = int32`), |
| 3265 |
filepath.Join(dir, "b/b.go"): []byte(`package b; import "m/a"; var V a.A`), |
| 3266 |
} |
| 3267 |
cfg := &packages.Config{ |
| 3268 |
Dir: dir, |
| 3269 |
Mode: packages.NeedTypes, // just NeedsTypes allows for loading export data. |
| 3270 |
Overlay: overlay, |
| 3271 |
Env: append(os.Environ(), "GOFLAGS=-mod=vendor", "GOWORK=off"), |
| 3272 |
} |
| 3273 |
pkgs, err := packages.Load(cfg, "m/b") |
| 3274 |
if err != nil { |
| 3275 |
t.Fatal(err) |
| 3276 |
} |
| 3277 |
if errs := packages.PrintErrors(pkgs); errs > 0 { |
| 3278 |
t.Fatalf("Got %d errors while loading packages.", errs) |
| 3279 |
} |
| 3280 |
if len(pkgs) != 1 { |
| 3281 |
t.Fatalf("Loaded %d packages. expected 1", len(pkgs)) |
| 3282 |
} |
| 3283 |
|
| 3284 |
pkg := pkgs[0] |
| 3285 |
scope := pkg.Types.Scope() |
| 3286 |
obj := scope.Lookup("V") |
| 3287 |
if obj == nil { |
| 3288 |
t.Fatalf("Failed to find object %q in package %q", "V", pkg) |
| 3289 |
} |
| 3290 |
if _, ok := obj.Type().(*types.Alias); !ok { |
| 3291 |
t.Errorf("Object %q has type %q. expected an alias", obj, obj.Type()) |
| 3292 |
} |
| 3293 |
} |
| 3294 |
|
| 3295 |
// TestLoadTypesInfoWithoutSyntaxOrTypes tests when NeedTypesInfo was set and NeedSyntax & NeedTypes were not, |
| 3296 |
// Load should include the TypesInfo of packages properly |
| 3297 |
func TestLoadTypesInfoWithoutSyntaxOrTypes(t *testing.T) { |
| 3298 |
testAllOrModulesParallel(t, testLoadTypesInfoWithoutSyntaxOrTypes) |
| 3299 |
} |
| 3300 |
|
| 3301 |
func testLoadTypesInfoWithoutSyntaxOrTypes(t *testing.T, exporter packagestest.Exporter) { |
| 3302 |
exported := packagestest.Export(t, exporter, []packagestest.Module{{ |
| 3303 |
Name: "golang.org/fake", |
| 3304 |
Files: map[string]any{ |
| 3305 |
"a/a.go": `package a; |
| 3306 |
|
| 3307 |
func foo() int { |
| 3308 |
i := 0 |
| 3309 |
s := "abc" |
| 3310 |
return i + len(s) |
| 3311 |
} |
| 3312 |
`, |
| 3313 |
}}}) |
| 3314 |
defer exported.Cleanup() |
| 3315 |
exported.Config.Mode = packages.NeedTypesInfo |
| 3316 |
|
| 3317 |
pkgs, err := packages.Load(exported.Config, "golang.org/fake/a") |
| 3318 |
if err != nil { |
| 3319 |
t.Fatal(err) |
| 3320 |
} |
| 3321 |
|
| 3322 |
// check if types info is present |
| 3323 |
if pkgs[0].TypesInfo == nil { |
| 3324 |
t.Errorf("expected types info to be present but got nil") |
| 3325 |
} |
| 3326 |
} |
| 3327 |
|
| 3328 |
// TestDirAndForTest tests the new fields added as part of golang/go#38445. |
| 3329 |
func TestDirAndForTest(t *testing.T) { |
| 3330 |
testenv.NeedsGoPackages(t) |
| 3331 |
|
| 3332 |
dir := writeTree(t, ` |
| 3333 |
-- go.mod -- |
| 3334 |
module example.com |
| 3335 |
|
| 3336 |
go 1.18 |
| 3337 |
|
| 3338 |
-- a/a.go -- |
| 3339 |
package a |
| 3340 |
|
| 3341 |
func Foo() int { return 1 } |
| 3342 |
|
| 3343 |
-- a/a_test.go -- |
| 3344 |
package a |
| 3345 |
|
| 3346 |
func Bar() int { return 2 } |
| 3347 |
|
| 3348 |
-- a/a_x_test.go -- |
| 3349 |
package a_test |
| 3350 |
|
| 3351 |
import ( |
| 3352 |
"example.com/a" |
| 3353 |
"example.com/b" |
| 3354 |
) |
| 3355 |
|
| 3356 |
func _() { |
| 3357 |
if got := a.Foo() + a.Bar() + b.Baz(); got != 6 { |
| 3358 |
panic("whoops") |
| 3359 |
} |
| 3360 |
} |
| 3361 |
|
| 3362 |
-- b/b.go -- |
| 3363 |
package b |
| 3364 |
|
| 3365 |
import "example.com/a" |
| 3366 |
|
| 3367 |
func Baz() int { return 3 } |
| 3368 |
|
| 3369 |
func Foo() int { return a.Foo() } |
| 3370 |
`) |
| 3371 |
|
| 3372 |
pkgs, err := packages.Load(&packages.Config{ |
| 3373 |
Mode: packages.NeedName | |
| 3374 |
packages.NeedFiles | |
| 3375 |
packages.NeedForTest | |
| 3376 |
packages.NeedImports, |
| 3377 |
Dir: dir, |
| 3378 |
Tests: true, |
| 3379 |
}, "./...") |
| 3380 |
if err != nil { |
| 3381 |
t.Fatal(err) |
| 3382 |
} |
| 3383 |
type result struct{ Dir, ForTest string } |
| 3384 |
got := make(map[string]result) |
| 3385 |
for pkg := range packages.Postorder(pkgs) { |
| 3386 |
if !packagepath.IsStdPackage(pkg.PkgPath) { |
| 3387 |
rel, err := filepath.Rel(dir, pkg.Dir) |
| 3388 |
if err != nil { |
| 3389 |
t.Errorf("Rel(%q, %q) failed: %v", dir, pkg.Dir, err) |
| 3390 |
continue |
| 3391 |
} |
| 3392 |
got[pkg.ID] = result{ |
| 3393 |
Dir: rel, |
| 3394 |
ForTest: pkg.ForTest, |
| 3395 |
} |
| 3396 |
} |
| 3397 |
} |
| 3398 |
want := map[string]result{ |
| 3399 |
"example.com/a": {"a", ""}, |
| 3400 |
"example.com/a.test": {"a", ""}, |
| 3401 |
"example.com/a [example.com/a.test]": {"a", "example.com/a"}, // test variant |
| 3402 |
"example.com/a_test [example.com/a.test]": {"a", "example.com/a"}, // x_test |
| 3403 |
"example.com/b [example.com/a.test]": {"b", "example.com/a"}, // intermediate test variant |
| 3404 |
"example.com/b": {"b", ""}, |
| 3405 |
} |
| 3406 |
if diff := cmp.Diff(want, got); diff != "" { |
| 3407 |
t.Errorf("Load returned mismatching ForTest fields (ID->result -want +got):\n%s", diff) |
| 3408 |
} |
| 3409 |
t.Logf("Packages: %+v", pkgs) |
| 3410 |
} |
| 3411 |
|
| 3412 |
// TestTarget tests the new field added as part of golang/go#38445. |
| 3413 |
// The test uses GOPATH mode because non-main packages don't usually |
| 3414 |
// have install targets in module mode. |
| 3415 |
func TestTarget(t *testing.T) { |
| 3416 |
testenv.NeedsGoPackages(t) |
| 3417 |
|
| 3418 |
dir := writeTree(t, ` |
| 3419 |
-- gopath/src/a/a.go -- |
| 3420 |
package a |
| 3421 |
|
| 3422 |
func Foo() {} |
| 3423 |
-- gopath/src/b/b.go -- |
| 3424 |
package main |
| 3425 |
|
| 3426 |
import "a" |
| 3427 |
|
| 3428 |
func main() { |
| 3429 |
a.Foo() |
| 3430 |
} |
| 3431 |
`) |
| 3432 |
gopath := filepath.Join(dir, "gopath") |
| 3433 |
|
| 3434 |
pkgs, err := packages.Load(&packages.Config{ |
| 3435 |
Mode: packages.NeedName | packages.NeedTarget, |
| 3436 |
Env: append(os.Environ(), "GOPATH="+gopath, "GO111MODULE=off"), |
| 3437 |
}, filepath.Join(gopath, "src", "...")) |
| 3438 |
if err != nil { |
| 3439 |
t.Fatal(err) |
| 3440 |
} |
| 3441 |
var goexe string |
| 3442 |
if runtime.GOOS == "windows" { |
| 3443 |
goexe = ".exe" |
| 3444 |
} |
| 3445 |
want := map[string]string{ |
| 3446 |
"a": filepath.Join(gopath, "pkg", runtime.GOOS+"_"+runtime.GOARCH, "a.a"), |
| 3447 |
"b": filepath.Join(gopath, "bin", "b"+goexe), |
| 3448 |
} |
| 3449 |
got := make(map[string]string) |
| 3450 |
for pkg := range packages.Postorder(pkgs) { |
| 3451 |
got[pkg.PkgPath] = pkg.Target |
| 3452 |
} |
| 3453 |
if diff := cmp.Diff(want, got); diff != "" { |
| 3454 |
t.Errorf("Load returned mismatching Target fields (pkgpath->target -want +got):\n%s", diff) |
| 3455 |
} |
| 3456 |
t.Logf("Packages: %+v", pkgs) |
| 3457 |
} |
| 3458 |
|
| 3459 |
// TestCompiledGoFilesIncludesDepsErrors ensures that when CompiledGoFiles |
| 3460 |
// is missing, errors reported by go/packages include underlying dependency |
| 3461 |
// errors from go list, rather than only a generic message. |
| 3462 |
// |
| 3463 |
// See golang/go#78083. |
| 3464 |
func TestCompiledGoFilesIncludesDepsErrors(t *testing.T) { |
| 3465 |
testenv.NeedsGoPackages(t) |
| 3466 |
|
| 3467 |
dir := writeTree(t, ` |
| 3468 |
-- go.mod -- |
| 3469 |
module example.com |
| 3470 |
go 1.18 |
| 3471 |
|
| 3472 |
-- a/a.go -- |
| 3473 |
package a |
| 3474 |
|
| 3475 |
/* |
| 3476 |
#cgo CFLAGS: -I/nonexistent |
| 3477 |
#include <missing.h> |
| 3478 |
*/ |
| 3479 |
import "C" |
| 3480 |
|
| 3481 |
func Foo() {} |
| 3482 |
`) |
| 3483 |
pkgs, err := packages.Load(&packages.Config{ |
| 3484 |
Dir: dir, |
| 3485 |
Mode: packages.LoadAllSyntax, |
| 3486 |
Env: append(os.Environ(), |
| 3487 |
"CGO_ENABLED=1", |
| 3488 |
), |
| 3489 |
}, "example.com/a") |
| 3490 |
if err != nil { |
| 3491 |
t.Fatal(err) |
| 3492 |
} |
| 3493 |
if len(pkgs) == 0 { |
| 3494 |
t.Fatal("no packages loaded") |
| 3495 |
} |
| 3496 |
found := false |
| 3497 |
// Expected error should include something like: |
| 3498 |
// fatal error: missing.h: No such file or directory |
| 3499 |
// We assert only "missing.h" for portability across systems. |
| 3500 |
for _, err := range pkgs[0].Errors { |
| 3501 |
if strings.Contains(err.Msg, "missing.h") { |
| 3502 |
found = true |
| 3503 |
} |
| 3504 |
} |
| 3505 |
if !found { |
| 3506 |
t.Errorf("expected error message to include underlying dependency errors, got: %+v", pkgs[0].Errors) |
| 3507 |
} |
| 3508 |
} |
| 3509 |
|
| 3510 |
// TestMainPackagePathInModeTypes tests (*types.Package).Path() for |
| 3511 |
// main packages in mode NeedTypes, a regression test for #70742, a |
| 3512 |
// bug in cmd/compile's export data that caused them to appear as |
| 3513 |
// "main". (The PkgPath field was always correct.) |
| 3514 |
func TestMainPackagePathInModeTypes(t *testing.T) { |
| 3515 |
testenv.NeedsGoPackages(t) |
| 3516 |
|
| 3517 |
cfg := &packages.Config{Mode: packages.NeedName | packages.NeedTypes} |
| 3518 |
pkgs, err := packages.Load(cfg, "cmd/go") |
| 3519 |
if err != nil { |
| 3520 |
t.Fatal(err) |
| 3521 |
} |
| 3522 |
p := pkgs[0] |
| 3523 |
if p.PkgPath != "cmd/go" || |
| 3524 |
p.Name != "main" || |
| 3525 |
p.Types.Path() != "cmd/go" || |
| 3526 |
p.Types.Name() != "main" { |
| 3527 |
t.Errorf("PkgPath=%q Name=%q Types.Path=%q Types.Name=%q; want (cmd/go, main) both times)", |
| 3528 |
p.PkgPath, |
| 3529 |
p.Name, |
| 3530 |
p.Types.Name(), |
| 3531 |
p.Types.Path()) |
| 3532 |
} |
| 3533 |
} |
| 3534 |
|
| 3535 |
func writeTree(t *testing.T, archive string) string { |
| 3536 |
root := t.TempDir() |
| 3537 |
|
| 3538 |
for _, f := range txtar.Parse([]byte(archive)).Files { |
| 3539 |
filename := filepath.Join(root, f.Name) |
| 3540 |
if err := os.MkdirAll(filepath.Dir(filename), 0777); err != nil { |
| 3541 |
t.Fatal(err) |
| 3542 |
} |
| 3543 |
if err := os.WriteFile(filename, f.Data, 0666); err != nil { |
| 3544 |
t.Fatal(err) |
| 3545 |
} |
| 3546 |
} |
| 3547 |
return root |
| 3548 |
} |
| 3549 |
|
| 3550 |
func TestLoadFileRelativePath(t *testing.T) { |
| 3551 |
exported := packagestest.Export(t, packagestest.Modules, []packagestest.Module{ |
| 3552 |
{ |
| 3553 |
Name: "fake/pkg", |
| 3554 |
Files: map[string]any{ |
| 3555 |
"pkg.go": "package pkg; type A int", |
| 3556 |
}, |
| 3557 |
}, |
| 3558 |
}) |
| 3559 |
t.Cleanup(exported.Cleanup) |
| 3560 |
|
| 3561 |
exported.Config.Mode = packages.LoadSyntax |
| 3562 |
pkgs, err := packages.Load(exported.Config, "file=pkg.go") |
| 3563 |
if err != nil { |
| 3564 |
t.Fatal(err) |
| 3565 |
} |
| 3566 |
if len(pkgs) != 1 { |
| 3567 |
t.Fatalf("len(pkgs) = %v; want = 1", len(pkgs)) |
| 3568 |
} |
| 3569 |
if pkgs[0].ID != "fake/pkg" { |
| 3570 |
t.Fatalf(`pkgs[0].Id = %q; want "fake/pkg"`, pkgs[0].ID) |
| 3571 |
} |
| 3572 |
} |
| 3573 |
|
| 3574 |
func TestLoad_populatesInfoMapsForUnsafePackage(t *testing.T) { |
| 3575 |
testenv.NeedsGoPackages(t) |
| 3576 |
|
| 3577 |
pkgs, err := packages.Load(&packages.Config{Mode: packages.LoadAllSyntax}, "unsafe") |
| 3578 |
if err != nil { |
| 3579 |
t.Fatal(err) |
| 3580 |
} |
| 3581 |
info := pkgs[0].TypesInfo |
| 3582 |
|
| 3583 |
if info.Defs == nil || |
| 3584 |
info.Uses == nil || |
| 3585 |
info.Selections == nil || |
| 3586 |
info.Types == nil || |
| 3587 |
info.FileVersions == nil || |
| 3588 |
info.Implicits == nil || |
| 3589 |
info.Instances == nil || |
| 3590 |
info.Scopes == nil { |
| 3591 |
t.Errorf("types.Info for package unsafe has one or more nil maps: %#v", *info) |
| 3592 |
} |
| 3593 |
} |