1// Copyright (c) 2020 Uber Technologies, Inc.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19// THE SOFTWARE.
20
21package atomic
22
23import (
24	"encoding/json"
25	"testing"
26
27	"github.com/stretchr/testify/assert"
28	"github.com/stretchr/testify/require"
29)
30
31func TestFloat64(t *testing.T) {
32	atom := NewFloat64(4.2)
33
34	require.Equal(t, float64(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, float64(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, float64(42.0), atom.Load(), "Store didn't set the correct value.")
42	require.Equal(t, float64(42.5), atom.Add(0.5), "Add didn't work.")
43	require.Equal(t, float64(42.0), atom.Sub(0.5), "Sub didn't work.")
44
45	t.Run("JSON/Marshal", func(t *testing.T) {
46		atom.Store(42.5)
47		bytes, err := json.Marshal(atom)
48		require.NoError(t, err, "json.Marshal errored unexpectedly.")
49		require.Equal(t, []byte("42.5"), bytes, "json.Marshal encoded the wrong bytes.")
50	})
51
52	t.Run("JSON/Unmarshal", func(t *testing.T) {
53		err := json.Unmarshal([]byte("40.5"), &atom)
54		require.NoError(t, err, "json.Unmarshal errored unexpectedly.")
55		require.Equal(t, float64(40.5), atom.Load(), "json.Unmarshal didn't set the correct value.")
56	})
57
58	t.Run("JSON/Unmarshal/Error", func(t *testing.T) {
59		err := json.Unmarshal([]byte("\"40.5\""), &atom)
60		require.Error(t, err, "json.Unmarshal didn't error as expected.")
61		assertErrorJSONUnmarshalType(t, err,
62			"json.Unmarshal failed with unexpected error %v, want UnmarshalTypeError.", err)
63	})
64
65	t.Run("String", func(t *testing.T) {
66		assert.Equal(t, "42.5", NewFloat64(42.5).String(),
67			"String() returned an unexpected value.")
68	})
69}
70