Home > Article > Backend Development > How to Unit Test Command Line Flag Enumeration Validation in Go?
Unit Testing Command Line Flags in Go
In Go, defining custom flags for command-line applications requires a thorough testing process to ensure their correctness. One specific scenario involves verifying that a particular flag's value falls within a predefined enumeration.
Code to Test
<code class="go">var formatType string const ( text = "text" json = "json" hash = "hash" ) func init() { const ( defaultFormat = "text" formatUsage = "desired output format" ) flag.StringVar(&formatType, "format", defaultFormat, formatUsage) flag.StringVar(&formatType, "f", defaultFormat, formatUsage+" (shorthand)") } func main() { flag.Parse() }</code>
Testing Approach
To unit test the desired behavior, we can harness the power of the flag.Var function, which allows us to define custom types and validation rules for flags.
<code class="go">type formatType string func (f *formatType) String() string { return fmt.Sprint(*f) } func (f *formatType) Set(value string) error { if len(*f) > 0 && *f != "text" { return errors.New("format flag already set") } if value != "text" && value != "json" && value != "hash" { return errors.New("Invalid Format Type") } *f = formatType(value) return nil }</code>
In this custom type implementation:
By employing this custom formatType flag, the testing process can now validate the flag's behavior when set to various values.
Example Testing
<code class="go">package main import "testing" func TestFormatType(t *testing.T) { tests := []struct { args []string expect string }{ {[]string{"-format", "text"}, "text"}, {[]string{"-f", "json"}, "json"}, {[]string{"-format", "foo"}, "Invalid Format Type"}, } for _, test := range tests { t.Run(test.args[0], func(t *testing.T) { flag.Parse() if typeFlag != test.expect { t.Errorf("Expected %s got %s", test.expect, typeFlag) } }) } }</code>
In this example:
The above is the detailed content of How to Unit Test Command Line Flag Enumeration Validation in Go?. For more information, please follow other related articles on the PHP Chinese website!