...

Source file src/edge-infra.dev/test/framework/flags.go

Documentation: edge-infra.dev/test/framework

     1  package framework
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/bazelbuild/rules_go/go/runfiles"
    10  	"github.com/peterbourgon/ff/v3"
    11  
    12  	"edge-infra.dev/pkg/lib/build/bazel"
    13  	"edge-infra.dev/test/framework/config"
    14  )
    15  
    16  var (
    17  	cfgFlagName = "test-config"
    18  	cfgPath     = "test/config.json"
    19  	cfgFlag     string
    20  )
    21  
    22  // HandleFlags is the key entrypoint for test configuration for the framework.
    23  // It sets up flags for providing test configuration files, reading flags from
    24  // environment variables (flag separators are turned into `_` by ff), registering
    25  // common framework flags, and copying all of the flags registered via
    26  // `config.AddOptions` to the flag set.
    27  // NOTE: Currently must be called from TestMain so that flags are handled by
    28  //
    29  //	the time the first test begins.
    30  func HandleFlags() {
    31  	// register flag for config file path, so ff can find the it
    32  	config.Flags.StringVar(&cfgFlag, cfgFlagName, resolveCfgPath(), "path to test configuration file")
    33  	// copy all the flags from the global flagset each test suite registers
    34  	// config options with to the command line for parsing
    35  	config.CopyFlags(config.Flags, flag.CommandLine)
    36  	// register base framework flags
    37  	RegisterCommonFlags(flag.CommandLine)
    38  	// parse test configuration
    39  	if err := ff.Parse(flag.CommandLine, os.Args[1:],
    40  		ff.WithConfigFileFlag(cfgFlagName),
    41  		ff.WithConfigFileParser(ff.JSONParser),
    42  		ff.WithAllowMissingConfigFile(true),
    43  		ff.WithIgnoreUndefined(true),
    44  	); err != nil {
    45  		panic(err)
    46  	}
    47  	// validate parsed common flags
    48  	Context.Validate()
    49  }
    50  
    51  // resolve config attempts to locate the test configuration file. if a bazel
    52  // runtime is detected, it will look for config.json in the runfiles. otherwise,
    53  // it tries to find the repo root and build a relative path from root.
    54  func resolveCfgPath() string {
    55  	if bazel.IsBazelRun() || bazel.IsBazelTest() {
    56  		rfilesPath := filepath.Join("edge_infa", cfgPath)
    57  		path, err := runfiles.Rlocation(rfilesPath)
    58  		if err != nil {
    59  			panic(fmt.Sprintf(
    60  				"failed to locate test config file %s in Bazel sandbox: %v",
    61  				rfilesPath, err,
    62  			))
    63  		}
    64  		return path
    65  	}
    66  	cwd, err := os.Getwd()
    67  	if err != nil {
    68  		panic(fmt.Sprintf("failed to determine cwd: %v", err))
    69  	}
    70  	return filepath.Join(bazel.FindRepoRootOrDie(cwd), cfgPath)
    71  }
    72  

View as plain text