github.com/go-playground/pkg/v5@v5.29.1/sync/mutex_test.go (about) 1 //go:build go1.18 2 // +build go1.18 3 4 package syncext 5 6 import ( 7 optionext "github.com/go-playground/pkg/v5/values/option" 8 "testing" 9 10 . "github.com/go-playground/assert/v2" 11 ) 12 13 func TestMutex(t *testing.T) { 14 m := NewMutex(make(map[string]int)) 15 m.Lock()["foo"] = 1 16 m.Unlock(optionext.None[map[string]int]()) 17 18 err := m.PerformMut(func(m map[string]int) (map[string]int, error) { 19 m["boo"] = 1 20 return m, nil 21 }) 22 Equal(t, err, nil) 23 24 myMap := m.Lock() 25 Equal(t, 2, len(myMap)) 26 m.Unlock(optionext.None[map[string]int]()) 27 } 28 29 func TestRWMutex(t *testing.T) { 30 m := NewRWMutex(make(map[string]int)) 31 m.Lock()["foo"] = 1 32 Equal(t, m.TryLock().IsOk(), false) 33 Equal(t, m.TryRLock().IsOk(), false) 34 m.Unlock(optionext.None[map[string]int]()) 35 36 err := m.PerformMut(func(m map[string]int) (map[string]int, error) { 37 m["boo"] = 2 38 return m, nil 39 }) 40 Equal(t, err, nil) 41 42 myMap := m.RLock() 43 Equal(t, len(myMap), 2) 44 Equal(t, m.TryRLock().IsOk(), true) 45 m.RUnlock() 46 47 err = m.Perform(func(m map[string]int) error { 48 Equal(t, 1, m["foo"]) 49 Equal(t, 2, m["boo"]) 50 return nil 51 }) 52 Equal(t, err, nil) 53 }