iTranslated by AI
Tips for using the flag package in Go tests
Recently, I gave a presentation at a Findy event about utilizing the testdata directory.
In this event, I discussed how to use the standard flag package to implement Golden Tests. This tip is useful regardless of whether you use testdata or not, so I decided to write this article to make it easier to share this knowledge.
How to use it
There are 3 steps to use the flag package in tests.
// 1. Import the package
import "flag"
// 2. Define flags as global variables
var example = flag.Bool("example", false, "example flag.")
// 3. Reference the value in the test (use *example to get the value from the pointer)
func TestExample(t *testing.T) {
if *example {
// Process when the flag is enabled
}
}
All you have to do is run go test -example.
Since go test calls flag.Parse() internally, no additional code is required.
This tip is widely used in the golang/go code, so I will introduce some usage examples along with actual code.
Utilizing in Golden Tests
Although it overlaps with my presentation the other day, Golden Test is a common pattern for utilizing this approach. Golden Test is a testing method that compares the output result of the target code against a pre-saved "Golden" file, which is particularly useful for verifying whether there are any unintended changes or regressions when code is modified.
The following code is an example from src/go/doc/doc_test.go. An update flag is defined using flag.Bool, and it is set up to update the Golden files in the testdata directory only when it is enabled.
var update = flag.Bool("update", false, "update golden (.out) files")
...
func test(t *testing.T, mode Mode) {
...
for _, pkg := range pkgs {
t.Run(pkg.Name, func(t *testing.T) {
...
// Update Golden files
golden := filepath.Join(dataDir, fmt.Sprintf("%s.%d.golden", pkg.Name, mode))
if *update {
err := os.WriteFile(golden, got, 0644)
if err != nil {
t.Fatal(err)
}
}
// Get Golden files
want, err := os.ReadFile(golden)
if err != nil {
t.Fatal(err)
}
// Verification
...
There are also instances where README files are automatically generated as Golden files.
In the link above, the README for a custom scripting language implemented for testing various CLI tools is being handled. Being able to detect missing updates in the README is great.
Usage for Debugging Purposes
Flags for receiving support during debugging are defined in various places. For instance, in src/cmd/compile/internal/ssa/debug_test.go, there are various flags to print detailed output from the debugger, perform dry-run executions, or use GDB instead of Delve.
For filesystem tests, there are also flags to prevent the deletion of files generated in the tmp directory, which can be very handy for debugging.
Controlling Test Verbosity
The Go testing package has built-in support for parsing the -short flag. By using testing.Short() to write conditional branches, it is possible to control tests, such as skipping time-consuming tests during regular test runs.
The flag package is sometimes used in scenarios where you want to expand upon patterns of verbosity, such as executing tests that take even more time.
Usage as Feature Flags
SIMD support is scheduled to begin experimentally from Go 1.26.
↓ Proposal
Along with this, code considering SIMD is being written for tests around the compiler, and it is also used as a feature flag for tests by switching processing using an SIMD enable flag.
Simply using it for Script Execution
In src/unicode/letter_test.go, a script to find the cutoff point for linear search and binary search is implemented and made executable via go test -calibrate.
Implementing scripts used only for testing and debugging this way is beneficial in preventing unintended usage and excluding them from go build targets.
Conclusion
The examples introduced this time were compiled by listing the usages of the flag package in the test code of golang/go using the following search query:
(Filtered using the GitHub code search query repo:golang/go "= flag." path:/src/**/*_test.go)
Flags defined with the flag package are often used more for developers to adjust and verify tests or peripheral code locally, rather than being used routinely in continuous CI testing.
I hope you will keep these tips in your repertoire for when you want to enhance the flexibility and efficiency of your tests.
Discussion