1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package atomic
22
23 import (
24 "encoding/json"
25 "testing"
26 "time"
27
28 "github.com/stretchr/testify/assert"
29 "github.com/stretchr/testify/require"
30 )
31
32 func TestDuration(t *testing.T) {
33 atom := NewDuration(5 * time.Minute)
34
35 require.Equal(t, 5*time.Minute, atom.Load(), "Load didn't work.")
36 require.Equal(t, 6*time.Minute, atom.Add(time.Minute), "Add didn't work.")
37 require.Equal(t, 4*time.Minute, atom.Sub(2*time.Minute), "Sub didn't work.")
38
39 require.True(t, atom.CAS(4*time.Minute, time.Minute), "CAS didn't report a swap.")
40 require.Equal(t, time.Minute, atom.Load(), "CAS didn't set the correct value.")
41
42 require.Equal(t, time.Minute, atom.Swap(2*time.Minute), "Swap didn't return the old value.")
43 require.Equal(t, 2*time.Minute, atom.Load(), "Swap didn't set the correct value.")
44
45 atom.Store(10 * time.Minute)
46 require.Equal(t, 10*time.Minute, atom.Load(), "Store didn't set the correct value.")
47
48 t.Run("JSON/Marshal", func(t *testing.T) {
49 atom.Store(time.Second)
50 bytes, err := json.Marshal(atom)
51 require.NoError(t, err, "json.Marshal errored unexpectedly.")
52 require.Equal(t, []byte("1000000000"), bytes, "json.Marshal encoded the wrong bytes.")
53 })
54
55 t.Run("JSON/Unmarshal", func(t *testing.T) {
56 err := json.Unmarshal([]byte("1000000000"), &atom)
57 require.NoError(t, err, "json.Unmarshal errored unexpectedly.")
58 require.Equal(t, time.Second, atom.Load(), "json.Unmarshal didn't set the correct value.")
59 })
60
61 t.Run("JSON/Unmarshal/Error", func(t *testing.T) {
62 err := json.Unmarshal([]byte("\"1000000000\""), &atom)
63 require.Error(t, err, "json.Unmarshal didn't error as expected.")
64 assertErrorJSONUnmarshalType(t, err,
65 "json.Unmarshal failed with unexpected error %v, want UnmarshalTypeError.", err)
66 })
67
68 t.Run("String", func(t *testing.T) {
69 assert.Equal(t, "42s", NewDuration(42*time.Second).String(),
70 "String() returned an unexpected value.")
71 })
72 }
73
View as plain text