package framework import ( "flag" "fmt" "os" "path/filepath" "github.com/bazelbuild/rules_go/go/runfiles" "github.com/peterbourgon/ff/v3" "edge-infra.dev/pkg/lib/build/bazel" "edge-infra.dev/test/framework/config" ) var ( cfgFlagName = "test-config" cfgPath = "test/config.json" cfgFlag string ) // HandleFlags is the key entrypoint for test configuration for the framework. // It sets up flags for providing test configuration files, reading flags from // environment variables (flag separators are turned into `_` by ff), registering // common framework flags, and copying all of the flags registered via // `config.AddOptions` to the flag set. // NOTE: Currently must be called from TestMain so that flags are handled by // // the time the first test begins. func HandleFlags() { // register flag for config file path, so ff can find the it config.Flags.StringVar(&cfgFlag, cfgFlagName, resolveCfgPath(), "path to test configuration file") // copy all the flags from the global flagset each test suite registers // config options with to the command line for parsing config.CopyFlags(config.Flags, flag.CommandLine) // register base framework flags RegisterCommonFlags(flag.CommandLine) // parse test configuration if err := ff.Parse(flag.CommandLine, os.Args[1:], ff.WithConfigFileFlag(cfgFlagName), ff.WithConfigFileParser(ff.JSONParser), ff.WithAllowMissingConfigFile(true), ff.WithIgnoreUndefined(true), ); err != nil { panic(err) } // validate parsed common flags Context.Validate() } // resolve config attempts to locate the test configuration file. if a bazel // runtime is detected, it will look for config.json in the runfiles. otherwise, // it tries to find the repo root and build a relative path from root. func resolveCfgPath() string { if bazel.IsBazelRun() || bazel.IsBazelTest() { rfilesPath := filepath.Join("edge_infa", cfgPath) path, err := runfiles.Rlocation(rfilesPath) if err != nil { panic(fmt.Sprintf( "failed to locate test config file %s in Bazel sandbox: %v", rfilesPath, err, )) } return path } cwd, err := os.Getwd() if err != nil { panic(fmt.Sprintf("failed to determine cwd: %v", err)) } return filepath.Join(bazel.FindRepoRootOrDie(cwd), cfgPath) }