github.com/fluhus/gostuff@v0.4.1-0.20240331134726-be71864f2b5d/nlock/nlock_test.go (about)

     1  package nlock
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  )
     7  
     8  func TestNLock(t *testing.T) {
     9  	lock := New(3)
    10  	expected := []bool{true, true, true, false, false}
    11  	for _, e := range expected {
    12  		if ok := lock.TryLock(); ok != e {
    13  			t.Fatalf("TryLock() = %v, want %v", ok, e)
    14  		}
    15  	}
    16  	lock.Unlock()
    17  	lock.Unlock()
    18  	lock.Unlock()
    19  
    20  	defer func() {
    21  		if recover() == nil {
    22  			t.Fatalf("Unlock() returned normally, want panic")
    23  		}
    24  	}()
    25  	lock.Unlock()
    26  }
    27  
    28  func TestNLock_async(t *testing.T) {
    29  	x := 0
    30  	lock := New(3)
    31  	go func() {
    32  		for i := 0; i < 5; i++ {
    33  			lock.Lock()
    34  			x++
    35  		}
    36  	}()
    37  	expected := []int{3, 4, 5, 5, 5}
    38  	for _, e := range expected {
    39  		time.Sleep(100 * time.Millisecond)
    40  		if x != e {
    41  			t.Fatalf("Lock() -> x = %v, want %v", x, e)
    42  		}
    43  		lock.Unlock()
    44  	}
    45  }
    46  
    47  func TestNLock_badN(t *testing.T) {
    48  	defer func() {
    49  		if recover() == nil {
    50  			t.Fatalf("New(0) returned normally, want panic")
    51  		}
    52  	}()
    53  	New(0)
    54  }