...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 package atomic
25
26 import (
27 "fmt"
28 "testing"
29
30 "github.com/stretchr/testify/require"
31 )
32
33 func TestPointer(t *testing.T) {
34 type foo struct{ v int }
35
36 i := foo{42}
37 j := foo{0}
38 k := foo{1}
39
40 tests := []struct {
41 desc string
42 newAtomic func() *Pointer[foo]
43 initial *foo
44 }{
45 {
46 desc: "New",
47 newAtomic: func() *Pointer[foo] {
48 return NewPointer(&i)
49 },
50 initial: &i,
51 },
52 {
53 desc: "New/nil",
54 newAtomic: func() *Pointer[foo] {
55 return NewPointer[foo](nil)
56 },
57 initial: nil,
58 },
59 {
60 desc: "zero value",
61 newAtomic: func() *Pointer[foo] {
62 var p Pointer[foo]
63 return &p
64 },
65 initial: nil,
66 },
67 }
68
69 for _, tt := range tests {
70 t.Run(tt.desc, func(t *testing.T) {
71 t.Run("Load", func(t *testing.T) {
72 atom := tt.newAtomic()
73 require.Equal(t, tt.initial, atom.Load(), "Load should report nil.")
74 })
75
76 t.Run("Swap", func(t *testing.T) {
77 atom := tt.newAtomic()
78 require.Equal(t, tt.initial, atom.Swap(&k), "Swap didn't return the old value.")
79 require.Equal(t, &k, atom.Load(), "Swap didn't set the correct value.")
80 })
81
82 t.Run("CAS", func(t *testing.T) {
83 atom := tt.newAtomic()
84 require.True(t, atom.CompareAndSwap(tt.initial, &j), "CAS didn't report a swap.")
85 require.Equal(t, &j, atom.Load(), "CAS didn't set the correct value.")
86 })
87
88 t.Run("Store", func(t *testing.T) {
89 atom := tt.newAtomic()
90 atom.Store(&i)
91 require.Equal(t, &i, atom.Load(), "Store didn't set the correct value.")
92 })
93 t.Run("String", func(t *testing.T) {
94 atom := tt.newAtomic()
95 require.Equal(t, fmt.Sprint(tt.initial), atom.String(), "String did not return the correct value.")
96 })
97 })
98 }
99 }
100
View as plain text