on 8ebab21 help sign in
crush/internal/csync/value_test.go
97 lines 1.5 kB history raw
1package csync
3import (
4 "sync"
5 "testing"
7 "github.com/stretchr/testify/require"
8)
10func TestValue_GetSet(t *testing.T) {
11 t.Parallel()
13 v := NewValue(42)
14 require.Equal(t, 42, v.Get())
16 v.Set(100)
17 require.Equal(t, 100, v.Get())
20func TestValue_ZeroValue(t *testing.T) {
21 t.Parallel()
23 v := NewValue("")
24 require.Equal(t, "", v.Get())
26 v.Set("hello")
27 require.Equal(t, "hello", v.Get())
30func TestValue_Struct(t *testing.T) {
31 t.Parallel()
33 type config struct {
34 Name string
35 Count int
36 }
38 v := NewValue(config{Name: "test", Count: 1})
39 require.Equal(t, config{Name: "test", Count: 1}, v.Get())
41 v.Set(config{Name: "updated", Count: 2})
42 require.Equal(t, config{Name: "updated", Count: 2}, v.Get())
45func TestValue_PointerPanics(t *testing.T) {
46 t.Parallel()
48 require.Panics(t, func() {
49 NewValue(&struct{}{})
50 })
53func TestValue_SlicePanics(t *testing.T) {
54 t.Parallel()
56 require.Panics(t, func() {
57 NewValue([]string{"a", "b"})
58 })
61func TestValue_MapPanics(t *testing.T) {
62 t.Parallel()
64 require.Panics(t, func() {
65 NewValue(map[string]int{"a": 1})
66 })
69func TestValue_ConcurrentAccess(t *testing.T) {
70 t.Parallel()
72 v := NewValue(0)
73 var wg sync.WaitGroup
75 // Concurrent writers.
76 for i := range 100 {
77 wg.Add(1)
78 go func(val int) {
79 defer wg.Done()
80 v.Set(val)
81 }(i)
82 }
84 // Concurrent readers.
85 for range 100 {
86 wg.Go(func() {
87 _ = v.Get()
88 })
89 }
91 wg.Wait()
93 // Value should be one of the set values (0-99).
94 got := v.Get()
95 require.GreaterOrEqual(t, got, 0)
96 require.Less(t, got, 100)