github.com/go-playground/pkg/v5@v5.29.1/sync/mutex2_test.go (about) 1 //go:build go1.18 2 // +build go1.18 3 4 package syncext 5 6 import ( 7 resultext "github.com/go-playground/pkg/v5/values/result" 8 "sync" 9 "testing" 10 11 . "github.com/go-playground/assert/v2" 12 ) 13 14 func TestMutex2(t *testing.T) { 15 m := NewMutex2(make(map[string]int)) 16 guard := m.Lock() 17 guard.T["foo"] = 1 18 guard.Unlock() 19 20 m.PerformMut(func(m map[string]int) { 21 m["boo"] = 1 22 }) 23 guard = m.Lock() 24 myMap := guard.T 25 Equal(t, 2, len(myMap)) 26 Equal(t, myMap["foo"], 1) 27 Equal(t, myMap["boo"], 1) 28 Equal(t, m.TryLock(), resultext.Err[MutexGuard[map[string]int, *sync.Mutex]](struct{}{})) 29 guard.Unlock() 30 31 result := m.TryLock() 32 Equal(t, result.IsOk(), true) 33 result.Unwrap().Unlock() 34 } 35 36 func TestRWMutex2(t *testing.T) { 37 m := NewRWMutex2(make(map[string]int)) 38 guard := m.Lock() 39 guard.T["foo"] = 1 40 Equal(t, m.TryLock().IsOk(), false) 41 Equal(t, m.TryRLock().IsOk(), false) 42 guard.Unlock() 43 44 m.PerformMut(func(m map[string]int) { 45 m["boo"] = 2 46 }) 47 guard = m.Lock() 48 mp := guard.T 49 Equal(t, mp["foo"], 1) 50 Equal(t, mp["boo"], 2) 51 guard.Unlock() 52 53 rguard := m.RLock() 54 myMap := rguard.T 55 Equal(t, len(myMap), 2) 56 Equal(t, m.TryRLock().IsOk(), true) 57 rguard.RUnlock() 58 59 m.Perform(func(m map[string]int) { 60 Equal(t, 1, m["foo"]) 61 Equal(t, 2, m["boo"]) 62 }) 63 rguard = m.RLock() 64 myMap = rguard.T 65 Equal(t, len(myMap), 2) 66 Equal(t, myMap["foo"], 1) 67 Equal(t, myMap["boo"], 2) 68 rguard.RUnlock() 69 }