codeberg.org/gruf/go-mutexes@v1.5.0/muctx/ctx_test.go (about) 1 package muctx_test 2 3 import ( 4 "context" 5 "testing" 6 7 "codeberg.org/gruf/go-mutexes" 8 "codeberg.org/gruf/go-mutexes/muctx" 9 ) 10 11 func TestMapLockCtx(t *testing.T) { 12 var mm mutexes.MutexMap 13 14 ctx := context.Background() 15 16 ctx, lock := muctx.LockCtx(&mm, ctx, "hello") 17 18 if !lock.Locked() || !lock.IsLock() || lock.IsRLock() { 19 t.Fatal("lock was not locked / incorrect lock type") 20 } 21 22 ctx2, lock2 := muctx.LockCtx(&mm, ctx, "hello") 23 24 if ctx != ctx2 { 25 t.Fatal("returned new context for ctx with existing lock") 26 } 27 28 if !lock2.Locked() { 29 t.Fatal("lock2 was not locked") 30 } 31 32 if lock2.Unlock() || !lock.Locked() || !lock2.Locked() { 33 t.Fatal("call to lock2 should not succeed") 34 } 35 36 if !lock.Unlock() || lock.Locked() || lock2.Locked() { 37 t.Fatalf("call to lock should succeed: %#v %#v", lock, lock2) 38 } 39 } 40 41 func TestRLockCtx(t *testing.T) { 42 var mm mutexes.MutexMap 43 44 ctx := context.Background() 45 46 ctx, lock := muctx.RLockCtx(&mm, ctx, "hello") 47 48 if !lock.Locked() || lock.IsLock() || !lock.IsRLock() { 49 t.Fatal("lock was not locked / incorrect lock type") 50 } 51 52 ctx2, lock2 := muctx.RLockCtx(&mm, ctx, "hello") 53 54 if ctx != ctx2 { 55 t.Fatal("returned new context for ctx with existing lock") 56 } 57 58 if !lock2.Locked() { 59 t.Fatal("lock2 was not locked") 60 } 61 62 if lock2.Unlock() || !lock.Locked() || !lock2.Locked() { 63 t.Fatal("call to lock2 should not succeed") 64 } 65 66 if !lock.Unlock() || lock.Locked() || lock2.Locked() { 67 t.Fatalf("call to lock should succeed: %#v %#v", lock, lock2) 68 } 69 }