Dan Anglin
0ad02e0af4
This commit adds a new parser for the internal time duration flag value (TimeDurationValue). Previously this used the parser from the time package from the standard library but this was limited to parsing units of time up to hours. The new parser allows users to specify duration in days, hours, minutes, seconds and a combination of the above. It is quite flexible in the way users format their string input. Additonal changes: - Added unit tests for the command-line parsing of the TimeDurationValue type. - Updated the unit tests for the BoolPtrValue type. - Updated documentation. PR: #55
67 lines
1.3 KiB
Go
67 lines
1.3 KiB
Go
package flag_test
|
|
|
|
import (
|
|
"flag"
|
|
"slices"
|
|
"testing"
|
|
|
|
internalFlag "codeflow.dananglin.me.uk/apollo/enbas/internal/flag"
|
|
)
|
|
|
|
func TestTimeDurationValue(t *testing.T) {
|
|
parsingTests := []struct {
|
|
input string
|
|
want string
|
|
}{
|
|
{
|
|
input: `"1 day"`,
|
|
want: "24h0m0s",
|
|
},
|
|
{
|
|
input: `"3 days, 5 hours, 39 minutes and 6 seconds"`,
|
|
want: "77h39m6s",
|
|
},
|
|
{
|
|
input: `"1 minute and 30 seconds"`,
|
|
want: "1m30s",
|
|
},
|
|
{
|
|
input: `"(7 seconds) (21 hours) (41 days)"`,
|
|
want: "1005h0m7s",
|
|
},
|
|
}
|
|
|
|
for _, test := range slices.All(parsingTests) {
|
|
args := []string{"--duration", test.input}
|
|
|
|
t.Run("Flag parsing test: "+test.input, testTimeDurationValueParsing(args, test.want))
|
|
}
|
|
}
|
|
|
|
func testTimeDurationValueParsing(args []string, want string) func(t *testing.T) {
|
|
return func(t *testing.T) {
|
|
flagset := flag.NewFlagSet("test", flag.ExitOnError)
|
|
duration := internalFlag.NewTimeDurationValue()
|
|
|
|
flagset.Var(&duration, "duration", "Duration value")
|
|
|
|
if err := flagset.Parse(args); err != nil {
|
|
t.Fatalf("Received an error parsing the flag: %v", err)
|
|
}
|
|
|
|
got := duration.String()
|
|
|
|
if got != want {
|
|
t.Errorf(
|
|
"Unexpected duration parsed from the flag: want %s, got %s",
|
|
want,
|
|
got,
|
|
)
|
|
} else {
|
|
t.Logf(
|
|
"Expected duration parsed from the flag: got %s",
|
|
got,
|
|
)
|
|
}
|
|
}
|
|
}
|