/ internal / flag / timedurationvalue_test.go
timedurationvalue_test.go
 1  package flag_test
 2  
 3  import (
 4  	"flag"
 5  	"slices"
 6  	"testing"
 7  
 8  	internalFlag "codeflow.dananglin.me.uk/apollo/enbas/internal/flag"
 9  )
10  
11  func TestTimeDurationValue(t *testing.T) {
12  	parsingTests := []struct {
13  		input string
14  		want  string
15  	}{
16  		{
17  			input: `"1 day"`,
18  			want:  "24h0m0s",
19  		},
20  		{
21  			input: `"3 days, 5 hours, 39 minutes and 6 seconds"`,
22  			want:  "77h39m6s",
23  		},
24  		{
25  			input: `"1 minute and 30 seconds"`,
26  			want:  "1m30s",
27  		},
28  		{
29  			input: `"(7 seconds) (21 hours) (41 days)"`,
30  			want:  "1005h0m7s",
31  		},
32  	}
33  
34  	for _, test := range slices.All(parsingTests) {
35  		args := []string{"--duration", test.input}
36  
37  		t.Run("Flag parsing test: "+test.input, testTimeDurationValueParsing(args, test.want))
38  	}
39  }
40  
41  func testTimeDurationValueParsing(args []string, want string) func(t *testing.T) {
42  	return func(t *testing.T) {
43  		flagset := flag.NewFlagSet("test", flag.ExitOnError)
44  		duration := internalFlag.NewTimeDurationValue()
45  
46  		flagset.Var(&duration, "duration", "Duration value")
47  
48  		if err := flagset.Parse(args); err != nil {
49  			t.Fatalf("Received an error parsing the flag: %v", err)
50  		}
51  
52  		got := duration.String()
53  
54  		if got != want {
55  			t.Errorf(
56  				"Unexpected duration parsed from the flag: want %s, got %s",
57  				want,
58  				got,
59  			)
60  		} else {
61  			t.Logf(
62  				"Expected duration parsed from the flag: got %s",
63  				got,
64  			)
65  		}
66  	}
67  }