github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/debug/badmutex_test.go (about)

     1  package debug
     2  
     3  import (
     4  	"sync"
     5  	"sync/atomic"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/lmorg/murex/test/count"
    10  )
    11  
    12  // TestBadMutex proves our test bad mutex (used to help diagnose locking faults)
    13  // does not lock
    14  func TestBadMutex(t *testing.T) {
    15  	count.Tests(t, 1)
    16  
    17  	var (
    18  		m BadMutex // if we swap this for sync.Mutex the error should be raised
    19  		i int32
    20  	)
    21  
    22  	go func() {
    23  		m.Lock()
    24  		time.Sleep(500 * time.Millisecond)
    25  		atomic.AddInt32(&i, 1)
    26  		m.Unlock()
    27  	}()
    28  
    29  	time.Sleep(100 * time.Millisecond)
    30  	m.Lock()
    31  	m.Unlock()
    32  
    33  	if atomic.LoadInt32(&i) != 0 {
    34  		t.Error("BadMutex caused a locking condition. This should not happen")
    35  	}
    36  }
    37  
    38  // TestGoodMutex proves our bad mutex test works
    39  func TestGoodMutex(t *testing.T) {
    40  	count.Tests(t, 1)
    41  
    42  	var (
    43  		m sync.Mutex // if we swap this for sync.Mutex the error should be raised
    44  		i int32
    45  	)
    46  
    47  	go func() {
    48  		m.Lock()
    49  		time.Sleep(500 * time.Millisecond)
    50  		atomic.AddInt32(&i, 1)
    51  		m.Unlock()
    52  	}()
    53  
    54  	time.Sleep(100 * time.Millisecond)
    55  	m.Lock()
    56  	m.Unlock()
    57  
    58  	if atomic.LoadInt32(&i) == 0 {
    59  		t.Error("Mutex did not cause a locking condition. The test logic has failed")
    60  	}
    61  }