| 1 |
package clock_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"testing" |
| 6 |
|
| 7 |
"github.com/stretchr/testify/suite" |
| 8 |
"github.com/vulcand/oxy/v2/internal/holsterv4/clock" |
| 9 |
) |
| 10 |
|
| 11 |
type DurationSuite struct { |
| 12 |
suite.Suite |
| 13 |
} |
| 14 |
|
| 15 |
func TestDurationSuite(t *testing.T) { |
| 16 |
suite.Run(t, new(DurationSuite)) |
| 17 |
} |
| 18 |
|
| 19 |
func (s *DurationSuite) TestNewOk() { |
| 20 |
for _, v := range []interface{}{ |
| 21 |
42 * clock.Second, |
| 22 |
int(42000000000), |
| 23 |
int64(42000000000), |
| 24 |
42000000000., |
| 25 |
"42s", |
| 26 |
[]byte("42s"), |
| 27 |
} { |
| 28 |
d, err := clock.NewDurationJSON(v) |
| 29 |
s.Nil(err) |
| 30 |
s.Equal(42*clock.Second, d.Duration) |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
func (s *DurationSuite) TestNewError() { |
| 35 |
for _, tc := range []struct { |
| 36 |
v interface{} |
| 37 |
errMsg string |
| 38 |
}{{ |
| 39 |
v: "foo", |
| 40 |
errMsg: "while parsing string: time: invalid duration \"foo\"", |
| 41 |
}, { |
| 42 |
v: []byte("foo"), |
| 43 |
errMsg: "while parsing []byte: time: invalid duration \"foo\"", |
| 44 |
}, { |
| 45 |
v: true, |
| 46 |
errMsg: "bad type bool", |
| 47 |
}} { |
| 48 |
d, err := clock.NewDurationJSON(tc.v) |
| 49 |
s.Equal(tc.errMsg, err.Error()) |
| 50 |
s.Equal(clock.DurationJSON{}, d) |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
func (s *DurationSuite) TestUnmarshal() { |
| 55 |
for _, v := range []string{ |
| 56 |
`{"foo": 42000000000}`, |
| 57 |
`{"foo": 0.42e11}`, |
| 58 |
`{"foo": "42s"}`, |
| 59 |
} { |
| 60 |
var withDuration struct { |
| 61 |
Foo clock.DurationJSON `json:"foo"` |
| 62 |
} |
| 63 |
err := json.Unmarshal([]byte(v), &withDuration) |
| 64 |
s.Nil(err) |
| 65 |
s.Equal(42*clock.Second, withDuration.Foo.Duration) |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
func (s *DurationSuite) TestMarshalling() { |
| 70 |
d, err := clock.NewDurationJSON(42 * clock.Second) |
| 71 |
s.Nil(err) |
| 72 |
encoded, err := d.MarshalJSON() |
| 73 |
s.Nil(err) |
| 74 |
var decoded clock.DurationJSON |
| 75 |
err = decoded.UnmarshalJSON(encoded) |
| 76 |
s.Nil(err) |
| 77 |
s.Equal(d, decoded) |
| 78 |
s.Equal("42s", decoded.String()) |
| 79 |
} |