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// +build cgo
6
7package packages_test
8
9import (
10	"golang.org/x/tools/go/packages"
11	"runtime"
12	"strings"
13	"testing"
14)
15
16func TestLoadImportsC(t *testing.T) {
17	// This test checks that when a package depends on the
18	// test variant of "syscall", "unsafe", or "runtime/cgo", that dependency
19	// is not removed when those packages are added when it imports "C".
20	//
21	// For this test to work, the external test of syscall must have a dependency
22	// on net, and net must import "syscall" and "C".
23	if runtime.GOOS == "windows" {
24		t.Skipf("skipping on windows; packages on windows do not satisfy conditions for test.")
25	}
26	if runtime.GOOS == "plan9" {
27		// See https://github.com/golang/go/issues/27100.
28		t.Skip(`skipping on plan9; for some reason "net [syscall.test]" is not loaded`)
29	}
30
31	cfg := &packages.Config{
32		Mode:  packages.LoadImports,
33		Tests: true,
34	}
35	initial, err := packages.Load(cfg, "syscall", "net")
36	if err != nil {
37		t.Fatalf("failed to load imports: %v", err)
38	}
39
40	_, all := importGraph(initial)
41
42	for _, test := range []struct {
43		pattern    string
44		wantImport string // an import to check for
45	}{
46		{"net", "syscall:syscall"},
47		{"net [syscall.test]", "syscall:syscall [syscall.test]"},
48		{"syscall_test [syscall.test]", "net:net [syscall.test]"},
49	} {
50		// Test the import paths.
51		pkg := all[test.pattern]
52		if pkg == nil {
53			t.Errorf("package %q not loaded", test.pattern)
54			continue
55		}
56		if imports := strings.Join(imports(pkg), " "); !strings.Contains(imports, test.wantImport) {
57			t.Errorf("package %q: got \n%s, \nwant to have %s", test.pattern, imports, test.wantImport)
58		}
59	}
60}
61