golang.org/x/tools@v0.21.1-0.20240520172518-788d39e776b1/internal/testfiles/testfiles_test.go (about)

     1  // Copyright 2024 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 testfiles_test
     6  
     7  import (
     8  	"os"
     9  	"path/filepath"
    10  	"testing"
    11  
    12  	"golang.org/x/tools/go/analysis"
    13  	"golang.org/x/tools/go/analysis/analysistest"
    14  	"golang.org/x/tools/internal/testenv"
    15  	"golang.org/x/tools/internal/testfiles"
    16  	"golang.org/x/tools/internal/versions"
    17  )
    18  
    19  func TestTestDir(t *testing.T) {
    20  	testenv.NeedsGo1Point(t, 22)
    21  
    22  	// TODO(taking): Expose a helper for this pattern?
    23  	// dir must contain a go.mod file to be picked up by Run().
    24  	// So this pattern or Join(TestDir(t, TestData()), "versions")  are
    25  	// probably what everyone will want.
    26  	dir := testfiles.CopyDirToTmp(t, filepath.Join(analysistest.TestData(), "versions"))
    27  
    28  	filever := &analysis.Analyzer{
    29  		Name: "filever",
    30  		Doc:  "reports file go versions",
    31  		Run: func(pass *analysis.Pass) (any, error) {
    32  			for _, file := range pass.Files {
    33  				ver := versions.FileVersion(pass.TypesInfo, file)
    34  				name := filepath.Base(pass.Fset.Position(file.Package).Filename)
    35  				pass.Reportf(file.Package, "%s@%s", name, ver)
    36  			}
    37  			return nil, nil
    38  		},
    39  	}
    40  	analysistest.Run(t, dir, filever, "golang.org/fake/versions", "golang.org/fake/versions/sub")
    41  }
    42  
    43  func TestCopyTestFilesErrors(t *testing.T) {
    44  	tmp := t.TempDir() // a real tmp dir
    45  	for _, dir := range []string{
    46  		filepath.Join(analysistest.TestData(), "not_there"),    // dir does not exist
    47  		filepath.Join(analysistest.TestData(), "somefile.txt"), // not a dir
    48  	} {
    49  		err := testfiles.CopyFS(tmp, os.DirFS(dir))
    50  		if err == nil {
    51  			t.Error("Expected an error from CopyTestFiles")
    52  		}
    53  	}
    54  }