@@ -0,0 +1,88 @@
1+package options
2+
3+import (
4+ "encoding/json"
5+ "errors"
6+ "time"
7+
8+ . "github.com/onsi/ginkgo"
9+ . "github.com/onsi/ginkgo/extensions/table"
10+ . "github.com/onsi/gomega"
11+)
12+
13+var _ = Describe("Common", func() {
14+ Context("Duration", func() {
15+ type marshalJSONTableInput struct {
16+ duration Duration
17+ expectedJSON string
18+ }
19+
20+ DescribeTable("MarshalJSON",
21+ func(in marshalJSONTableInput) {
22+ data, err := in.duration.MarshalJSON()
23+ Expect(err).ToNot(HaveOccurred())
24+ Expect(string(data)).To(Equal(in.expectedJSON))
25+
26+ var d Duration
27+ Expect(json.Unmarshal(data, &d)).To(Succeed())
28+ Expect(d).To(Equal(in.duration))
29+ },
30+ Entry("30 seconds", marshalJSONTableInput{
31+ duration: Duration(30 * time.Second),
32+ expectedJSON: "\"30s\"",
33+ }),
34+ Entry("1 minute", marshalJSONTableInput{
35+ duration: Duration(1 * time.Minute),
36+ expectedJSON: "\"1m0s\"",
37+ }),
38+ Entry("1 hour 15 minutes", marshalJSONTableInput{
39+ duration: Duration(75 * time.Minute),
40+ expectedJSON: "\"1h15m0s\"",
41+ }),
42+ Entry("A zero Duration", marshalJSONTableInput{
43+ duration: Duration(0),
44+ expectedJSON: "\"0s\"",
45+ }),
46+ )
47+
48+ type unmarshalJSONTableInput struct {
49+ json string
50+ expectedErr error
51+ expectedDuration Duration
52+ }
53+
54+ DescribeTable("UnmarshalJSON",
55+ func(in unmarshalJSONTableInput) {
56+ // A duration must be initialised pointer before UnmarshalJSON will work.
57+ zero := Duration(0)
58+ d := &zero
59+
60+ err := d.UnmarshalJSON([]byte(in.json))
61+ if in.expectedErr != nil {
62+ Expect(err).To(MatchError(in.expectedErr.Error()))
63+ } else {
64+ Expect(err).ToNot(HaveOccurred())
65+ }
66+ Expect(d).ToNot(BeNil())
67+ Expect(*d).To(Equal(in.expectedDuration))
68+ },
69+ Entry("1m", unmarshalJSONTableInput{
70+ json: "\"1m\"",
71+ expectedDuration: Duration(1 * time.Minute),
72+ }),
73+ Entry("30s", unmarshalJSONTableInput{
74+ json: "\"30s\"",
75+ expectedDuration: Duration(30 * time.Second),
76+ }),
77+ Entry("1h15m", unmarshalJSONTableInput{
78+ json: "\"1h15m\"",
79+ expectedDuration: Duration(75 * time.Minute),
80+ }),
81+ Entry("am", unmarshalJSONTableInput{
82+ json: "\"am\"",
83+ expectedErr: errors.New("time: invalid duration \"am\""),
84+ expectedDuration: Duration(0),
85+ }),
86+ )
87+ })
88+})