Merge branch '21316-left-panel-collapse'
[arvados.git] / sdk / go / arvados / duration_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package arvados
6
7 import (
8         "encoding/json"
9         "time"
10
11         check "gopkg.in/check.v1"
12 )
13
14 var _ = check.Suite(&DurationSuite{})
15
16 type DurationSuite struct{}
17
18 func (s *DurationSuite) TestMarshalJSON(c *check.C) {
19         var d struct {
20                 D Duration
21         }
22         err := json.Unmarshal([]byte(`{"D":"1.234s"}`), &d)
23         c.Check(err, check.IsNil)
24         c.Check(d.D, check.Equals, Duration(time.Second+234*time.Millisecond))
25         buf, err := json.Marshal(d)
26         c.Check(err, check.IsNil)
27         c.Check(string(buf), check.Equals, `{"D":"1.234s"}`)
28
29         for _, trial := range []struct {
30                 seconds int
31                 out     string
32         }{
33                 {30, "30s"},
34                 {60, "1m"},
35                 {120, "2m"},
36                 {150, "2m30s"},
37                 {3600, "1h"},
38                 {7201, "2h1s"},
39                 {360600, "100h10m"},
40                 {360610, "100h10m10s"},
41         } {
42                 buf, err := json.Marshal(Duration(time.Duration(trial.seconds) * time.Second))
43                 c.Check(err, check.IsNil)
44                 c.Check(string(buf), check.Equals, `"`+trial.out+`"`)
45         }
46 }
47
48 func (s *DurationSuite) TestUnmarshalJSON(c *check.C) {
49         var d struct {
50                 D Duration
51         }
52         err := json.Unmarshal([]byte(`{"D":1.234}`), &d)
53         c.Check(err, check.ErrorMatches, `.*missing unit in duration "?1\.234"?`)
54         err = json.Unmarshal([]byte(`{"D":"1.234"}`), &d)
55         c.Check(err, check.ErrorMatches, `.*missing unit in duration "?1\.234"?`)
56         err = json.Unmarshal([]byte(`{"D":"1"}`), &d)
57         c.Check(err, check.ErrorMatches, `.*missing unit in duration "?1"?`)
58         err = json.Unmarshal([]byte(`{"D":"foobar"}`), &d)
59         c.Check(err, check.ErrorMatches, `.*invalid duration "?foobar"?`)
60         err = json.Unmarshal([]byte(`{"D":"60s"}`), &d)
61         c.Check(err, check.IsNil)
62         c.Check(d.D.Duration(), check.Equals, time.Minute)
63
64         d.D = Duration(time.Second)
65         err = json.Unmarshal([]byte(`{"D":"0"}`), &d)
66         c.Check(err, check.IsNil)
67         c.Check(d.D.Duration(), check.Equals, time.Duration(0))
68
69         d.D = Duration(time.Second)
70         err = json.Unmarshal([]byte(`{"D":0}`), &d)
71         c.Check(err, check.IsNil)
72         c.Check(d.D.Duration(), check.Equals, time.Duration(0))
73 }