Browse code

Use timeouts instead of relying on runtime.GoSched

Signed-off-by: Brian Goff <cpuguy83@gmail.com>

Brian Goff authored on 2015/11/12 10:49:06
Showing 1 changed files
... ...
@@ -1,8 +1,8 @@
1 1
 package locker
2 2
 
3 3
 import (
4
-	"runtime"
5 4
 	"testing"
5
+	"time"
6 6
 )
7 7
 
8 8
 func TestLockCounter(t *testing.T) {
... ...
@@ -34,7 +34,21 @@ func TestLockerLock(t *testing.T) {
34 34
 		close(chDone)
35 35
 	}()
36 36
 
37
-	runtime.Gosched()
37
+	chWaiting := make(chan struct{})
38
+	go func() {
39
+		for range time.Tick(1 * time.Millisecond) {
40
+			if ctr.count() == 1 {
41
+				close(chWaiting)
42
+				break
43
+			}
44
+		}
45
+	}()
46
+
47
+	select {
48
+	case <-chWaiting:
49
+	case <-time.After(3 * time.Second):
50
+		t.Fatal("timed out waiting for lock waiters to be incremented")
51
+	}
38 52
 
39 53
 	select {
40 54
 	case <-chDone:
... ...
@@ -42,25 +56,14 @@ func TestLockerLock(t *testing.T) {
42 42
 	default:
43 43
 	}
44 44
 
45
-	if ctr.count() != 1 {
46
-		t.Fatalf("expected waiters to be 1, got: %d", ctr.count())
47
-	}
48
-
49 45
 	if err := l.Unlock("test"); err != nil {
50 46
 		t.Fatal(err)
51 47
 	}
52
-	runtime.Gosched()
53 48
 
54 49
 	select {
55 50
 	case <-chDone:
56
-	default:
57
-		// one more time just to be sure
58
-		runtime.Gosched()
59
-		select {
60
-		case <-chDone:
61
-		default:
62
-			t.Fatalf("lock should have completed")
63
-		}
51
+	case <-time.After(3 * time.Second):
52
+		t.Fatalf("lock should have completed")
64 53
 	}
65 54
 
66 55
 	if ctr.count() != 0 {
... ...
@@ -80,11 +83,9 @@ func TestLockerUnlock(t *testing.T) {
80 80
 		close(chDone)
81 81
 	}()
82 82
 
83
-	runtime.Gosched()
84
-
85 83
 	select {
86 84
 	case <-chDone:
87
-	default:
85
+	case <-time.After(3 * time.Second):
88 86
 		t.Fatalf("lock should not be blocked")
89 87
 	}
90 88
 }