Source file src/cmd/go/internal/modload/import_test.go

     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 modload
     6  
     7  import (
     8  	"context"
     9  	"internal/testenv"
    10  	"regexp"
    11  	"strings"
    12  	"testing"
    13  
    14  	"golang.org/x/mod/module"
    15  )
    16  
    17  var importTests = []struct {
    18  	path string
    19  	m    module.Version
    20  	err  string
    21  }{
    22  	{
    23  		path: "golang.org/x/net/context",
    24  		m: module.Version{
    25  			Path: "golang.org/x/net",
    26  		},
    27  	},
    28  	{
    29  		path: "golang.org/x/net",
    30  		err:  `module golang.org/x/net@.* found \(v[01]\.\d+\.\d+\), but does not contain package golang.org/x/net`,
    31  	},
    32  	{
    33  		path: "golang.org/x/text",
    34  		m: module.Version{
    35  			Path: "golang.org/x/text",
    36  		},
    37  	},
    38  	{
    39  		path: "github.com/rsc/quote/buggy",
    40  		m: module.Version{
    41  			Path:    "github.com/rsc/quote",
    42  			Version: "v1.5.2",
    43  		},
    44  	},
    45  	{
    46  		path: "github.com/rsc/quote",
    47  		m: module.Version{
    48  			Path:    "github.com/rsc/quote",
    49  			Version: "v1.5.2",
    50  		},
    51  	},
    52  	{
    53  		path: "golang.org/x/foo/bar",
    54  		err:  "cannot find module providing package golang.org/x/foo/bar",
    55  	},
    56  }
    57  
    58  func TestQueryImport(t *testing.T) {
    59  	loaderstate := NewState()
    60  	loaderstate.RootMode = NoRoot
    61  	loaderstate.AllowMissingModuleImports()
    62  
    63  	testenv.MustHaveExternalNetwork(t)
    64  	testenv.MustHaveExecPath(t, "git")
    65  
    66  	ctx := context.Background()
    67  	rs := LoadModFile(loaderstate, ctx)
    68  
    69  	for _, tt := range importTests {
    70  		t.Run(strings.ReplaceAll(tt.path, "/", "_"), func(t *testing.T) {
    71  			// Note that there is no build list, so Import should always fail.
    72  			m, err := queryImport(loaderstate, ctx, tt.path, rs)
    73  
    74  			if tt.err == "" {
    75  				if err != nil {
    76  					t.Fatalf("queryImport(_, %q): %v", tt.path, err)
    77  				}
    78  			} else {
    79  				if err == nil {
    80  					t.Fatalf("queryImport(_, %q) = %v, nil; expected error", tt.path, m)
    81  				}
    82  				if !regexp.MustCompile(tt.err).MatchString(err.Error()) {
    83  					t.Fatalf("queryImport(_, %q): error %q, want error matching %#q", tt.path, err, tt.err)
    84  				}
    85  			}
    86  
    87  			if m.Path != tt.m.Path || (tt.m.Version != "" && m.Version != tt.m.Version) {
    88  				t.Errorf("queryImport(_, %q) = %v, _; want %v", tt.path, m, tt.m)
    89  			}
    90  		})
    91  	}
    92  }
    93  

View as plain text