How to Unit Test Command Line Flag Enumeration Validation in Go?

Barbara Streisand
Release: 2024-11-17 10:57:02
Original
896 people have browsed it

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>
Copy after login

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>
Copy after login

In this custom type implementation:

  • String() returns the current value of the flag in string form.
  • Set() updates the flag's value and ensures that it falls within the permitted enumeration.

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>
Copy after login

In this example:

  • TestFormatType iterates over a list of tests.
  • Each test sets up command-line arguments, parses the flags, and compares the resulting typeFlag value with the expected results.
  • If any test fails, it reports an error.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template