github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/util/syncutil/mutex_sync_race_test.go (about)

     1  // Copyright 2017 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  // +build !deadlock
    12  // +build race
    13  
    14  package syncutil
    15  
    16  import (
    17  	"testing"
    18  
    19  	"github.com/stretchr/testify/require"
    20  )
    21  
    22  func TestAssertHeld(t *testing.T) {
    23  	type mutex interface {
    24  		Lock()
    25  		Unlock()
    26  		AssertHeld()
    27  	}
    28  
    29  	testCases := []struct {
    30  		m mutex
    31  	}{
    32  		{&Mutex{}},
    33  		{&RWMutex{}},
    34  	}
    35  	for _, c := range testCases {
    36  		// The normal, successful case.
    37  		c.m.Lock()
    38  		c.m.AssertHeld()
    39  		c.m.Unlock()
    40  
    41  		// The unsuccessful case.
    42  		require.PanicsWithValue(t, "mutex is not write locked", c.m.AssertHeld)
    43  	}
    44  }
    45  
    46  func TestAssertRHeld(t *testing.T) {
    47  	var m RWMutex
    48  
    49  	// The normal, successful case.
    50  	m.RLock()
    51  	m.AssertRHeld()
    52  	m.RUnlock()
    53  
    54  	// The normal case with two readers.
    55  	m.RLock()
    56  	m.RLock()
    57  	m.AssertRHeld()
    58  	m.RUnlock()
    59  	m.RUnlock()
    60  
    61  	// The case where a write lock is held.
    62  	m.Lock()
    63  	m.AssertRHeld()
    64  	m.Unlock()
    65  
    66  	// The unsuccessful case with no readers.
    67  	require.PanicsWithValue(t, "mutex is not read locked", m.AssertRHeld)
    68  }