codeberg.org/gruf/go-mutexes@v1.5.0/mutex_test.go (about) 1 package mutexes_test 2 3 import ( 4 "testing" 5 "time" 6 7 "codeberg.org/gruf/go-mutexes" 8 ) 9 10 const timeout = time.Millisecond 11 12 func TestMutexTimeout(t *testing.T) { 13 var timedOut bool 14 15 mu := mutexes.WithTimeout(mutexes.New(), timeout) 16 17 unlockFn := mu.LockFunc(func() { timedOut = true }) 18 time.Sleep(timeout * 10) 19 unlockFn() 20 21 if !timedOut { 22 t.Fatal("Should have timed out") 23 } 24 } 25 26 func TestRWMutexTimeout(t *testing.T) { 27 var rTimedOut bool 28 var wTimedOut bool 29 30 mu := mutexes.WithTimeoutRW(mutexes.NewRW(), timeout, timeout) 31 32 unlockFn := mu.RLockFunc(func() { rTimedOut = true }) 33 time.Sleep(timeout * 10) 34 unlockFn() 35 36 unlockFn = mu.LockFunc(func() { wTimedOut = true }) 37 time.Sleep(timeout * 2) 38 unlockFn() 39 40 if !rTimedOut || !wTimedOut { 41 t.Fatal("Should have timed out") 42 } 43 } 44 45 func TestMutexSafety(t *testing.T) { 46 mu := mutexes.WithSafety(mutexes.New()) 47 unlockFn := mu.Lock() 48 49 catchPanic( 50 t, 51 func() { 52 // Defer unlock 53 defer unlockFn() 54 55 // Unlock early 56 unlockFn() 57 58 panic("panic! at the golang?") 59 }, 60 func(v interface{}) { 61 if v != nil && v != "panic! at the golang?" { 62 t.Fatalf("Panic during unlock: %v", v) 63 } 64 }, 65 ) 66 } 67 68 func TestRWMutexSafety(t *testing.T) { 69 mu := mutexes.WithSafetyRW(mutexes.NewRW()) 70 71 // Try read lock 72 unlockFn := mu.RLock() 73 74 catchPanic( 75 t, 76 func() { 77 // Defer unlock 78 defer unlockFn() 79 80 // Unlock early 81 unlockFn() 82 83 panic("panic! at the golang?") 84 }, 85 func(v interface{}) { 86 if v != nil && v != "panic! at the golang?" { 87 t.Fatalf("Panic during unlock: %v", v) 88 } 89 }, 90 ) 91 92 // Try write lock 93 unlockFn = mu.Lock() 94 95 catchPanic( 96 t, 97 func() { 98 // Defer unlock 99 defer unlockFn() 100 101 // Unlock early 102 unlockFn() 103 104 panic("panic! at the golang?") 105 }, 106 func(v interface{}) { 107 if v != nil && v != "panic! at the golang?" { 108 t.Fatalf("Panic during unlock: %v", v) 109 } 110 }, 111 ) 112 } 113 114 func TestMutexFunc(t *testing.T) { 115 mu := mutexes.WithFunc( 116 mutexes.New(), 117 func() { t.Log("lock") }, 118 func() { t.Log("unlock") }, 119 ) 120 mu.Lock()() 121 } 122 123 func TestRWMutexFunc(t *testing.T) { 124 mu := mutexes.WithFuncRW( 125 mutexes.NewRW(), 126 func() { t.Log("lock") }, 127 func() { t.Log("rlock") }, 128 func() { t.Log("unlock") }, 129 func() { t.Log("runlock") }, 130 ) 131 mu.RLock()() 132 mu.Lock()() 133 } 134 135 func catchPanic(t *testing.T, do func(), onRecover func(v interface{})) { 136 defer func() { 137 r := recover() 138 onRecover(r) 139 }() 140 do() 141 }