Merge branch '15348-pam-module'
[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(string(buf), check.Equals, `{"D":"1.234s"}`)
27
28         for _, trial := range []struct {
29                 seconds int
30                 out     string
31         }{
32                 {30, "30s"},
33                 {60, "1m"},
34                 {120, "2m"},
35                 {150, "2m30s"},
36                 {3600, "1h"},
37                 {7201, "2h1s"},
38                 {360600, "100h10m"},
39                 {360610, "100h10m10s"},
40         } {
41                 buf, err := json.Marshal(Duration(time.Duration(trial.seconds) * time.Second))
42                 c.Check(err, check.IsNil)
43                 c.Check(string(buf), check.Equals, `"`+trial.out+`"`)
44         }
45 }
46
47 func (s *DurationSuite) TestUnmarshalJSON(c *check.C) {
48         var d struct {
49                 D Duration
50         }
51         err := json.Unmarshal([]byte(`{"D":1.234}`), &d)
52         c.Check(err, check.ErrorMatches, `missing unit in duration 1.234`)
53         err = json.Unmarshal([]byte(`{"D":"1.234"}`), &d)
54         c.Check(err, check.ErrorMatches, `.*missing unit in duration 1.234`)
55         err = json.Unmarshal([]byte(`{"D":"1"}`), &d)
56         c.Check(err, check.ErrorMatches, `.*missing unit in duration 1`)
57         err = json.Unmarshal([]byte(`{"D":"foobar"}`), &d)
58         c.Check(err, check.ErrorMatches, `.*invalid duration foobar`)
59         err = json.Unmarshal([]byte(`{"D":"60s"}`), &d)
60         c.Check(err, check.IsNil)
61         c.Check(d.D.Duration(), check.Equals, time.Minute)
62 }