github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/sync2/mutex_test.go (about)

     1  package sync2_test
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  
     7  	"github.com/egonelbre/exp/sync2"
     8  )
     9  
    10  func TestMutexOwn(t *testing.T) {
    11  	var mu sync2.Mutex
    12  	mu.Lock()
    13  	defer mu.Unlock()
    14  	if !mu.Own() {
    15  		t.Errorf("owning returned wrong result")
    16  	}
    17  }
    18  
    19  func TestMutexNotOwned(t *testing.T) {
    20  	var mu sync2.Mutex
    21  	if mu.Own() {
    22  		t.Errorf("should not be owning")
    23  	}
    24  }
    25  
    26  func TestMutexContention(t *testing.T) {
    27  	var wg sync.WaitGroup
    28  
    29  	var mu sync2.Mutex
    30  	mu.Lock()
    31  
    32  	wg.Add(1)
    33  	go func() {
    34  		defer wg.Done()
    35  		defer func() {
    36  			if err := recover(); err != nil {
    37  				return
    38  			}
    39  			t.Errorf("did not detect failure")
    40  		}()
    41  
    42  		mu.MustOwn()
    43  	}()
    44  	wg.Wait()
    45  	mu.Unlock()
    46  
    47  	if mu.Own() {
    48  		t.Errorf("should not be owning")
    49  	}
    50  }