add comments

This commit is contained in:
georgehao 2025-02-04 15:28:34 +08:00
parent 288d85f411
commit 8bad1bbfc2
No known key found for this signature in database

View file

@ -5,6 +5,9 @@ import (
"time"
)
// TestClosableMutex_TryLock tests the TryLock functionality of ClosableMutex.
// It verifies that TryLock succeeds when the mutex is unlocked, fails when already locked,
// succeeds after unlocking, and fails after the mutex is closed.
func TestClosableMutex_TryLock(t *testing.T) {
cm := NewClosableMutex()
if !cm.TryLock() {
@ -23,6 +26,8 @@ func TestClosableMutex_TryLock(t *testing.T) {
}
}
// TestClosableMutex_MustLock tests the MustLock functionality of ClosableMutex.
// It verifies that MustLock succeeds when the mutex is unlocked and panics when already locked.
func TestClosableMutex_MustLock(t *testing.T) {
cm := NewClosableMutex()
cm.MustLock()
@ -34,6 +39,8 @@ func TestClosableMutex_MustLock(t *testing.T) {
cm.MustLock()
}
// TestClosableMutex_Unlock tests the Unlock functionality of ClosableMutex.
// It verifies that Unlock succeeds when the mutex is locked and panics when already unlocked.
func TestClosableMutex_Unlock(t *testing.T) {
cm := NewClosableMutex()
cm.MustLock()
@ -46,6 +53,8 @@ func TestClosableMutex_Unlock(t *testing.T) {
cm.Unlock()
}
// TestClosableMutex_Close tests the Close functionality of ClosableMutex.
// It verifies that Close succeeds when the mutex is locked and panics when already closed.
func TestClosableMutex_Close(t *testing.T) {
cm := NewClosableMutex()
cm.MustLock()
@ -58,20 +67,23 @@ func TestClosableMutex_Close(t *testing.T) {
cm.Close()
}
// TestClosableMutex_Concurrent tests the concurrent behavior of ClosableMutex.
// It verifies that TryLock fails when the mutex is locked by another goroutine
// and succeeds after the other goroutine unlocks it.
func TestClosableMutex_Concurrent(t *testing.T) {
cm := NewClosableMutex()
done := make(chan struct{})
go func() {
cm.MustLock()
time.Sleep(100 * time.Millisecond)
time.Sleep(100 * time.Millisecond) // Simulate work while holding the lock
cm.Unlock()
close(done)
}()
time.Sleep(50 * time.Millisecond)
time.Sleep(50 * time.Millisecond) // Wait for the goroutine to acquire the lock
if cm.TryLock() {
t.Fatal("expected TryLock to fail when locked by another goroutine")
}
<-done
<-done // Wait for the goroutine to release the lock
if !cm.TryLock() {
t.Fatal("expected TryLock to succeed after other goroutine unlocks")
}