pomerium/internal/atomicutil/value_test.go
Ryota 711394d51f
Fix typo, add more test cases for atomicutil, and mention about atomic.Pointer migration (#5736)
I found the `atomicutil` package used throughout the code base, but it
seems to predate the addition of `atomic.Pointer[T]`. Potentially this
should allow us to remove the package altogether and use stdlib directly
instead. But I went ahead with starting with adding simple test cases
first, so that we have better test coverage across the code base.

Also, I added an example of how `atomicutil` usage may be problematic in
some specific scenario compared to how it's implemented with
`atomic.Pointer[T]`. Not to mention, there is some performance gain of
not using the direct casting with its generic support. (Though this is
probably a minor one and the code clarity is a benefit we may want to
keep rather than using other atomic values such as `atomic.Bool`.)

---------

Co-authored-by: Kenneth Jenkins <51246568+kenjenkins@users.noreply.github.com>
2025-07-22 15:11:30 -07:00

59 lines
1.1 KiB
Go

package atomicutil
import (
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
)
func TestValue(t *testing.T) {
v := NewValue(5)
assert.Equal(t, 5, v.Load())
t.Run("nil", func(t *testing.T) {
var v *Value[int]
assert.Equal(t, 0, v.Load())
})
t.Run("default", func(t *testing.T) {
var v Value[int]
assert.Equal(t, 0, v.Load())
})
}
func TestStore(t *testing.T) {
v := NewValue(5)
v.Store(42)
assert.Equal(t, 42, v.Load())
}
func TestSwap(t *testing.T) {
v := NewValue(42)
v.Swap(33)
assert.Equal(t, 33, v.Load())
}
func TestCompareAndSwap(t *testing.T) {
v := NewValue(42)
swapped := v.CompareAndSwap(42, 33)
assert.True(t, swapped)
assert.Equal(t, 33, v.Load())
swapped = v.CompareAndSwap(42, 33)
assert.False(t, swapped)
assert.Equal(t, 33, v.Load())
}
// Unlike atomic.Pointer[T], calling Load() on an uninitialized Value[T] will
// return the zero value for type T.
func TestWithPointer(t *testing.T) {
var withUtil *Value[int]
var withPointer atomic.Pointer[int]
// This becomes the zero value.
assert.NotNil(t, withUtil.Load())
// This is nil.
assert.Nil(t, withPointer.Load())
}