Black Lives Matter. Support the Equal Justice Initiative.

Source file src/cmd/go/internal/test/testflag.go

Documentation: cmd/go/internal/test

     1  // Copyright 2011 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 test
     6  
     7  import (
     8  	"errors"
     9  	"flag"
    10  	"fmt"
    11  	"os"
    12  	"path/filepath"
    13  	"strconv"
    14  	"strings"
    15  	"time"
    16  
    17  	"cmd/go/internal/base"
    18  	"cmd/go/internal/cfg"
    19  	"cmd/go/internal/cmdflag"
    20  	"cmd/go/internal/work"
    21  )
    22  
    23  //go:generate go run ./genflags.go
    24  
    25  // The flag handling part of go test is large and distracting.
    26  // We can't use (*flag.FlagSet).Parse because some of the flags from
    27  // our command line are for us, and some are for the test binary, and
    28  // some are for both.
    29  
    30  func init() {
    31  	work.AddBuildFlags(CmdTest, work.OmitVFlag)
    32  
    33  	cf := CmdTest.Flag
    34  	cf.BoolVar(&testC, "c", false, "")
    35  	cf.BoolVar(&cfg.BuildI, "i", false, "")
    36  	cf.StringVar(&testO, "o", "", "")
    37  
    38  	cf.BoolVar(&testCover, "cover", false, "")
    39  	cf.Var(coverFlag{(*coverModeFlag)(&testCoverMode)}, "covermode", "")
    40  	cf.Var(coverFlag{commaListFlag{&testCoverPaths}}, "coverpkg", "")
    41  
    42  	cf.Var((*base.StringsFlag)(&work.ExecCmd), "exec", "")
    43  	cf.BoolVar(&testJSON, "json", false, "")
    44  	cf.Var(&testVet, "vet", "")
    45  
    46  	// Register flags to be forwarded to the test binary. We retain variables for
    47  	// some of them so that cmd/go knows what to do with the test output, or knows
    48  	// to build the test in a way that supports the use of the flag.
    49  
    50  	cf.StringVar(&testBench, "bench", "", "")
    51  	cf.Bool("benchmem", false, "")
    52  	cf.String("benchtime", "", "")
    53  	cf.StringVar(&testBlockProfile, "blockprofile", "", "")
    54  	cf.String("blockprofilerate", "", "")
    55  	cf.Int("count", 0, "")
    56  	cf.Var(coverFlag{stringFlag{&testCoverProfile}}, "coverprofile", "")
    57  	cf.String("cpu", "", "")
    58  	cf.StringVar(&testCPUProfile, "cpuprofile", "", "")
    59  	cf.Bool("failfast", false, "")
    60  	cf.StringVar(&testList, "list", "", "")
    61  	cf.StringVar(&testMemProfile, "memprofile", "", "")
    62  	cf.String("memprofilerate", "", "")
    63  	cf.StringVar(&testMutexProfile, "mutexprofile", "", "")
    64  	cf.String("mutexprofilefraction", "", "")
    65  	cf.Var(&testOutputDir, "outputdir", "")
    66  	cf.Int("parallel", 0, "")
    67  	cf.String("run", "", "")
    68  	cf.Bool("short", false, "")
    69  	cf.DurationVar(&testTimeout, "timeout", 10*time.Minute, "")
    70  	cf.StringVar(&testTrace, "trace", "", "")
    71  	cf.BoolVar(&testV, "v", false, "")
    72  	cf.Var(&testShuffle, "shuffle", "")
    73  
    74  	for name := range passFlagToTest {
    75  		cf.Var(cf.Lookup(name).Value, "test."+name, "")
    76  	}
    77  }
    78  
    79  // A coverFlag is a flag.Value that also implies -cover.
    80  type coverFlag struct{ v flag.Value }
    81  
    82  func (f coverFlag) String() string { return f.v.String() }
    83  
    84  func (f coverFlag) Set(value string) error {
    85  	if err := f.v.Set(value); err != nil {
    86  		return err
    87  	}
    88  	testCover = true
    89  	return nil
    90  }
    91  
    92  type coverModeFlag string
    93  
    94  func (f *coverModeFlag) String() string { return string(*f) }
    95  func (f *coverModeFlag) Set(value string) error {
    96  	switch value {
    97  	case "", "set", "count", "atomic":
    98  		*f = coverModeFlag(value)
    99  		return nil
   100  	default:
   101  		return errors.New(`valid modes are "set", "count", or "atomic"`)
   102  	}
   103  }
   104  
   105  // A commaListFlag is a flag.Value representing a comma-separated list.
   106  type commaListFlag struct{ vals *[]string }
   107  
   108  func (f commaListFlag) String() string { return strings.Join(*f.vals, ",") }
   109  
   110  func (f commaListFlag) Set(value string) error {
   111  	if value == "" {
   112  		*f.vals = nil
   113  	} else {
   114  		*f.vals = strings.Split(value, ",")
   115  	}
   116  	return nil
   117  }
   118  
   119  // A stringFlag is a flag.Value representing a single string.
   120  type stringFlag struct{ val *string }
   121  
   122  func (f stringFlag) String() string { return *f.val }
   123  func (f stringFlag) Set(value string) error {
   124  	*f.val = value
   125  	return nil
   126  }
   127  
   128  // outputdirFlag implements the -outputdir flag.
   129  // It interprets an empty value as the working directory of the 'go' command.
   130  type outputdirFlag struct {
   131  	abs string
   132  }
   133  
   134  func (f *outputdirFlag) String() string {
   135  	return f.abs
   136  }
   137  func (f *outputdirFlag) Set(value string) (err error) {
   138  	if value == "" {
   139  		f.abs = ""
   140  	} else {
   141  		f.abs, err = filepath.Abs(value)
   142  	}
   143  	return err
   144  }
   145  func (f *outputdirFlag) getAbs() string {
   146  	if f.abs == "" {
   147  		return base.Cwd()
   148  	}
   149  	return f.abs
   150  }
   151  
   152  // vetFlag implements the special parsing logic for the -vet flag:
   153  // a comma-separated list, with a distinguished value "off" and
   154  // a boolean tracking whether it was set explicitly.
   155  type vetFlag struct {
   156  	explicit bool
   157  	off      bool
   158  	flags    []string // passed to vet when invoked automatically during 'go test'
   159  }
   160  
   161  func (f *vetFlag) String() string {
   162  	if f.off {
   163  		return "off"
   164  	}
   165  
   166  	var buf strings.Builder
   167  	for i, f := range f.flags {
   168  		if i > 0 {
   169  			buf.WriteByte(',')
   170  		}
   171  		buf.WriteString(f)
   172  	}
   173  	return buf.String()
   174  }
   175  
   176  func (f *vetFlag) Set(value string) error {
   177  	if value == "" {
   178  		*f = vetFlag{flags: defaultVetFlags}
   179  		return nil
   180  	}
   181  
   182  	if value == "off" {
   183  		*f = vetFlag{
   184  			explicit: true,
   185  			off:      true,
   186  		}
   187  		return nil
   188  	}
   189  
   190  	if strings.Contains(value, "=") {
   191  		return fmt.Errorf("-vet argument cannot contain equal signs")
   192  	}
   193  	if strings.Contains(value, " ") {
   194  		return fmt.Errorf("-vet argument is comma-separated list, cannot contain spaces")
   195  	}
   196  	*f = vetFlag{explicit: true}
   197  	for _, arg := range strings.Split(value, ",") {
   198  		if arg == "" {
   199  			return fmt.Errorf("-vet argument contains empty list element")
   200  		}
   201  		f.flags = append(f.flags, "-"+arg)
   202  	}
   203  	return nil
   204  }
   205  
   206  type shuffleFlag struct {
   207  	on   bool
   208  	seed *int64
   209  }
   210  
   211  func (f *shuffleFlag) String() string {
   212  	if !f.on {
   213  		return "off"
   214  	}
   215  	if f.seed == nil {
   216  		return "on"
   217  	}
   218  	return fmt.Sprintf("%d", *f.seed)
   219  }
   220  
   221  func (f *shuffleFlag) Set(value string) error {
   222  	if value == "off" {
   223  		*f = shuffleFlag{on: false}
   224  		return nil
   225  	}
   226  
   227  	if value == "on" {
   228  		*f = shuffleFlag{on: true}
   229  		return nil
   230  	}
   231  
   232  	seed, err := strconv.ParseInt(value, 10, 64)
   233  	if err != nil {
   234  		return fmt.Errorf(`-shuffle argument must be "on", "off", or an int64: %v`, err)
   235  	}
   236  
   237  	*f = shuffleFlag{on: true, seed: &seed}
   238  	return nil
   239  }
   240  
   241  // testFlags processes the command line, grabbing -x and -c, rewriting known flags
   242  // to have "test" before them, and reading the command line for the test binary.
   243  // Unfortunately for us, we need to do our own flag processing because go test
   244  // grabs some flags but otherwise its command line is just a holding place for
   245  // pkg.test's arguments.
   246  // We allow known flags both before and after the package name list,
   247  // to allow both
   248  //	go test fmt -custom-flag-for-fmt-test
   249  //	go test -x math
   250  func testFlags(args []string) (packageNames, passToTest []string) {
   251  	base.SetFromGOFLAGS(&CmdTest.Flag)
   252  	addFromGOFLAGS := map[string]bool{}
   253  	CmdTest.Flag.Visit(func(f *flag.Flag) {
   254  		if short := strings.TrimPrefix(f.Name, "test."); passFlagToTest[short] {
   255  			addFromGOFLAGS[f.Name] = true
   256  		}
   257  	})
   258  
   259  	// firstUnknownFlag helps us report an error when flags not known to 'go
   260  	// test' are used along with -i or -c.
   261  	firstUnknownFlag := ""
   262  
   263  	explicitArgs := make([]string, 0, len(args))
   264  	inPkgList := false
   265  	afterFlagWithoutValue := false
   266  	for len(args) > 0 {
   267  		f, remainingArgs, err := cmdflag.ParseOne(&CmdTest.Flag, args)
   268  
   269  		wasAfterFlagWithoutValue := afterFlagWithoutValue
   270  		afterFlagWithoutValue = false // provisionally
   271  
   272  		if errors.Is(err, flag.ErrHelp) {
   273  			exitWithUsage()
   274  		}
   275  
   276  		if errors.Is(err, cmdflag.ErrFlagTerminator) {
   277  			// 'go list' allows package arguments to be named either before or after
   278  			// the terminator, but 'go test' has historically allowed them only
   279  			// before. Preserve that behavior and treat all remaining arguments —
   280  			// including the terminator itself! — as arguments to the test.
   281  			explicitArgs = append(explicitArgs, args...)
   282  			break
   283  		}
   284  
   285  		if nf := (cmdflag.NonFlagError{}); errors.As(err, &nf) {
   286  			if !inPkgList && packageNames != nil {
   287  				// We already saw the package list previously, and this argument is not
   288  				// a flag, so it — and everything after it — must be either a value for
   289  				// a preceding flag or a literal argument to the test binary.
   290  				if wasAfterFlagWithoutValue {
   291  					// This argument could syntactically be a flag value, so
   292  					// optimistically assume that it is and keep looking for go command
   293  					// flags after it.
   294  					//
   295  					// (If we're wrong, we'll at least be consistent with historical
   296  					// behavior; see https://golang.org/issue/40763.)
   297  					explicitArgs = append(explicitArgs, nf.RawArg)
   298  					args = remainingArgs
   299  					continue
   300  				} else {
   301  					// This argument syntactically cannot be a flag value, so it must be a
   302  					// positional argument, and so must everything after it.
   303  					explicitArgs = append(explicitArgs, args...)
   304  					break
   305  				}
   306  			}
   307  
   308  			inPkgList = true
   309  			packageNames = append(packageNames, nf.RawArg)
   310  			args = remainingArgs // Consume the package name.
   311  			continue
   312  		}
   313  
   314  		if inPkgList {
   315  			// This argument is syntactically a flag, so if we were in the package
   316  			// list we're not anymore.
   317  			inPkgList = false
   318  		}
   319  
   320  		if nd := (cmdflag.FlagNotDefinedError{}); errors.As(err, &nd) {
   321  			// This is a flag we do not know. We must assume that any args we see
   322  			// after this might be flag arguments, not package names, so make
   323  			// packageNames non-nil to indicate that the package list is complete.
   324  			//
   325  			// (Actually, we only strictly need to assume that if the flag is not of
   326  			// the form -x=value, but making this more precise would be a breaking
   327  			// change in the command line API.)
   328  			if packageNames == nil {
   329  				packageNames = []string{}
   330  			}
   331  
   332  			if nd.RawArg == "-args" || nd.RawArg == "--args" {
   333  				// -args or --args signals that everything that follows
   334  				// should be passed to the test.
   335  				explicitArgs = append(explicitArgs, remainingArgs...)
   336  				break
   337  			}
   338  
   339  			if firstUnknownFlag == "" {
   340  				firstUnknownFlag = nd.RawArg
   341  			}
   342  
   343  			explicitArgs = append(explicitArgs, nd.RawArg)
   344  			args = remainingArgs
   345  			if !nd.HasValue {
   346  				afterFlagWithoutValue = true
   347  			}
   348  			continue
   349  		}
   350  
   351  		if err != nil {
   352  			fmt.Fprintln(os.Stderr, err)
   353  			exitWithUsage()
   354  		}
   355  
   356  		if short := strings.TrimPrefix(f.Name, "test."); passFlagToTest[short] {
   357  			explicitArgs = append(explicitArgs, fmt.Sprintf("-test.%s=%v", short, f.Value))
   358  
   359  			// This flag has been overridden explicitly, so don't forward its implicit
   360  			// value from GOFLAGS.
   361  			delete(addFromGOFLAGS, short)
   362  			delete(addFromGOFLAGS, "test."+short)
   363  		}
   364  
   365  		args = remainingArgs
   366  	}
   367  	if firstUnknownFlag != "" && (testC || cfg.BuildI) {
   368  		buildFlag := "-c"
   369  		if !testC {
   370  			buildFlag = "-i"
   371  		}
   372  		fmt.Fprintf(os.Stderr, "go test: unknown flag %s cannot be used with %s\n", firstUnknownFlag, buildFlag)
   373  		exitWithUsage()
   374  	}
   375  
   376  	var injectedFlags []string
   377  	if testJSON {
   378  		// If converting to JSON, we need the full output in order to pipe it to
   379  		// test2json.
   380  		injectedFlags = append(injectedFlags, "-test.v=true")
   381  		delete(addFromGOFLAGS, "v")
   382  		delete(addFromGOFLAGS, "test.v")
   383  	}
   384  
   385  	// Inject flags from GOFLAGS before the explicit command-line arguments.
   386  	// (They must appear before the flag terminator or first non-flag argument.)
   387  	// Also determine whether flags with awkward defaults have already been set.
   388  	var timeoutSet, outputDirSet bool
   389  	CmdTest.Flag.Visit(func(f *flag.Flag) {
   390  		short := strings.TrimPrefix(f.Name, "test.")
   391  		if addFromGOFLAGS[f.Name] {
   392  			injectedFlags = append(injectedFlags, fmt.Sprintf("-test.%s=%v", short, f.Value))
   393  		}
   394  		switch short {
   395  		case "timeout":
   396  			timeoutSet = true
   397  		case "outputdir":
   398  			outputDirSet = true
   399  		}
   400  	})
   401  
   402  	// 'go test' has a default timeout, but the test binary itself does not.
   403  	// If the timeout wasn't set (and forwarded) explicitly, add the default
   404  	// timeout to the command line.
   405  	if testTimeout > 0 && !timeoutSet {
   406  		injectedFlags = append(injectedFlags, fmt.Sprintf("-test.timeout=%v", testTimeout))
   407  	}
   408  
   409  	// Similarly, the test binary defaults -test.outputdir to its own working
   410  	// directory, but 'go test' defaults it to the working directory of the 'go'
   411  	// command. Set it explicitly if it is needed due to some other flag that
   412  	// requests output.
   413  	if testProfile() != "" && !outputDirSet {
   414  		injectedFlags = append(injectedFlags, "-test.outputdir="+testOutputDir.getAbs())
   415  	}
   416  
   417  	// If the user is explicitly passing -help or -h, show output
   418  	// of the test binary so that the help output is displayed
   419  	// even though the test will exit with success.
   420  	// This loop is imperfect: it will do the wrong thing for a case
   421  	// like -args -test.outputdir -help. Such cases are probably rare,
   422  	// and getting this wrong doesn't do too much harm.
   423  helpLoop:
   424  	for _, arg := range explicitArgs {
   425  		switch arg {
   426  		case "--":
   427  			break helpLoop
   428  		case "-h", "-help", "--help":
   429  			testHelp = true
   430  			break helpLoop
   431  		}
   432  	}
   433  
   434  	// Ensure that -race and -covermode are compatible.
   435  	if testCoverMode == "" {
   436  		testCoverMode = "set"
   437  		if cfg.BuildRace {
   438  			// Default coverage mode is atomic when -race is set.
   439  			testCoverMode = "atomic"
   440  		}
   441  	}
   442  	if cfg.BuildRace && testCoverMode != "atomic" {
   443  		base.Fatalf(`-covermode must be "atomic", not %q, when -race is enabled`, testCoverMode)
   444  	}
   445  
   446  	// Forward any unparsed arguments (following --args) to the test binary.
   447  	return packageNames, append(injectedFlags, explicitArgs...)
   448  }
   449  
   450  func exitWithUsage() {
   451  	fmt.Fprintf(os.Stderr, "usage: %s\n", CmdTest.UsageLine)
   452  	fmt.Fprintf(os.Stderr, "Run 'go help %s' and 'go help %s' for details.\n", CmdTest.LongName(), HelpTestflag.LongName())
   453  
   454  	base.SetExitStatus(2)
   455  	base.Exit()
   456  }
   457  

View as plain text