summaryrefslogtreecommitdiff
path: root/internal/duration/parse_test.go
blob: d1f1f379f61b3e5342402adf9a34f838df2ed722 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package duration

import (
	"testing"
	"time"
)

func TestParseValidDurations(t *testing.T) {
	tests := []struct {
		name  string
		input string
		want  time.Duration
	}{
		{
			name:  "go-style mixed",
			input: "1h30m",
			want:  90 * time.Minute,
		},
		{
			name:  "go-style minutes",
			input: "30m",
			want:  30 * time.Minute,
		},
		{
			name:  "go-style hours",
			input: "8h",
			want:  8 * time.Hour,
		},
		{
			name:  "bare integer seconds",
			input: "3600",
			want:  time.Hour,
		},
		{
			name:  "trimmed bare integer",
			input: "  120  ",
			want:  120 * time.Second,
		},
		{
			name:  "negative bare integer",
			input: "-60",
			want:  -60 * time.Second,
		},
	}

	for _, test := range tests {
		test := test
		t.Run(test.name, func(t *testing.T) {
			t.Parallel()
			got, err := Parse(test.input)
			if err != nil {
				t.Fatalf("Parse(%q) error = %v", test.input, err)
			}
			if got != test.want {
				t.Fatalf("Parse(%q) = %v, want %v", test.input, got, test.want)
			}
		})
	}
}

func TestParseInvalidDurations(t *testing.T) {
	tests := []string{
		"",
		"   ",
		"abc",
		"1h30x",
		"9223372036854775807",
		"-9223372036854775808",
	}

	for _, input := range tests {
		input := input
		t.Run(input, func(t *testing.T) {
			t.Parallel()
			if _, err := Parse(input); err == nil {
				t.Fatalf("Parse(%q) error = nil, want error", input)
			}
		})
	}
}

func FuzzParse(f *testing.F) {
	seeds := []string{
		"1h30m",
		"3600",
		"-60",
		"abc",
		"",
		"   ",
	}
	for _, seed := range seeds {
		f.Add(seed)
	}

	f.Fuzz(func(t *testing.T, input string) {
		_, _ = Parse(input)
	})
}