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
27 "github.com/stretchr/testify/assert"
28 "github.com/stretchr/testify/require"
29 )
30
31 func TestFloat32(t *testing.T) {
32 atom := NewFloat32(4.2)
33
34 require.Equal(t, float32(4.2), atom.Load(), "Load didn't work.")
35
36 require.True(t, atom.CAS(4.2, 0.5), "CAS didn't report a swap.")
37 require.Equal(t, float32(0.5), atom.Load(), "CAS didn't set the correct value.")
38 require.False(t, atom.CAS(0.0, 1.5), "CAS reported a swap.")
39
40 atom.Store(42.0)
41 require.Equal(t, float32(42.0), atom.Load(), "Store didn't set the correct value.")
42 require.Equal(t, float32(42.5), atom.Add(0.5), "Add didn't work.")
43 require.Equal(t, float32(42.0), atom.Sub(0.5), "Sub didn't work.")
44
45 require.Equal(t, float32(42.0), atom.Swap(45.0), "Swap didn't return the old value.")
46 require.Equal(t, float32(45.0), atom.Load(), "Swap didn't set the correct value.")
47
48 t.Run("JSON/Marshal", func(t *testing.T) {
49 atom.Store(42.5)
50 bytes, err := json.Marshal(atom)
51 require.NoError(t, err, "json.Marshal errored unexpectedly.")
52 require.Equal(t, []byte("42.5"), bytes, "json.Marshal encoded the wrong bytes.")
53 })
54
55 t.Run("JSON/Unmarshal", func(t *testing.T) {
56 err := json.Unmarshal([]byte("40.5"), &atom)
57 require.NoError(t, err, "json.Unmarshal errored unexpectedly.")
58 require.Equal(t, float32(40.5), 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("\"40.5\""), &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, "42.5", NewFloat32(42.5).String(),
70 "String() returned an unexpected value.")
71 })
72 }
73
View as plain text