summaryrefslogtreecommitdiffhomepage
path: root/pkg/sync/mutex_test.go
blob: 4fb51a8ab7c2492c5fc8ef63a5349aaa8d45ecc3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright 2019 The gVisor Authors.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package sync

import (
	"sync"
	"testing"
	"unsafe"
)

// TestStructSize verifies that syncMutex's size hasn't drifted from the
// standard library's version.
//
// The correctness of this package relies on these remaining in sync.
func TestStructSize(t *testing.T) {
	const (
		got  = unsafe.Sizeof(syncMutex{})
		want = unsafe.Sizeof(sync.Mutex{})
	)
	if got != want {
		t.Errorf("got sizeof(syncMutex) = %d, want = sizeof(sync.Mutex) = %d", got, want)
	}
}

// TestFieldValues verifies that the semantics of syncMutex.state from the
// standard library's implementation.
//
// The correctness of this package relies on these remaining in sync.
func TestFieldValues(t *testing.T) {
	var m Mutex
	m.Lock()
	if got := *m.m.state(); got != mutexLocked {
		t.Errorf("got locked sync.Mutex.state = %d, want = %d", got, mutexLocked)
	}
	m.Unlock()
	if got := *m.m.state(); got != mutexUnlocked {
		t.Errorf("got unlocked sync.Mutex.state = %d, want = %d", got, mutexUnlocked)
	}
}

func TestDoubleTryLock(t *testing.T) {
	var m Mutex
	if !m.TryLock() {
		t.Fatal("failed to aquire lock")
	}
	if m.TryLock() {
		t.Fatal("unexpectedly succeeded in aquiring locked mutex")
	}
}

func TestTryLockAfterLock(t *testing.T) {
	var m Mutex
	m.Lock()
	if m.TryLock() {
		t.Fatal("unexpectedly succeeded in aquiring locked mutex")
	}
}

func TestTryLockUnlock(t *testing.T) {
	var m Mutex
	if !m.TryLock() {
		t.Fatal("failed to aquire lock")
	}
	m.Unlock()
	if !m.TryLock() {
		t.Fatal("failed to aquire lock after unlock")
	}
}