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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
|
package tests
import (
"fmt"
"testing"
"time"
)
var expectedI int
func checkI(t *testing.T, i int) {
if i != expectedI {
t.Errorf("expected %d, got %d", expectedI, i)
}
expectedI++
}
func TestDefer(t *testing.T) {
expectedI = 1
defer func() {
checkI(t, 2)
testDefer1(t)
checkI(t, 6)
}()
checkI(t, 1)
}
func testDefer1(t *testing.T) {
defer func() {
checkI(t, 4)
time.Sleep(0)
checkI(t, 5)
}()
checkI(t, 3)
}
func TestPanic(t *testing.T) {
expectedI = 1
defer func() {
checkI(t, 8)
err := recover()
time.Sleep(0)
checkI(t, err.(int))
}()
checkI(t, 1)
testPanic1(t)
checkI(t, -1)
}
func testPanic1(t *testing.T) {
defer func() {
checkI(t, 6)
time.Sleep(0)
err := recover()
checkI(t, err.(int))
panic(9)
}()
checkI(t, 2)
testPanic2(t)
checkI(t, -2)
}
func testPanic2(t *testing.T) {
defer func() {
checkI(t, 5)
}()
checkI(t, 3)
time.Sleep(0)
checkI(t, 4)
panic(7)
checkI(t, -3)
}
func TestPanicAdvanced(t *testing.T) {
expectedI = 1
defer func() {
recover()
checkI(t, 3)
testPanicAdvanced2(t)
checkI(t, 6)
}()
testPanicAdvanced1(t)
checkI(t, -1)
}
func testPanicAdvanced1(t *testing.T) {
defer func() {
checkI(t, 2)
}()
checkI(t, 1)
panic("")
}
func testPanicAdvanced2(t *testing.T) {
defer func() {
checkI(t, 5)
}()
checkI(t, 4)
}
func TestSelect(t *testing.T) {
expectedI = 1
a := make(chan int)
b := make(chan int)
c := make(chan int)
go func() {
select {
case <-a:
case <-b:
}
}()
go func() {
checkI(t, 1)
a <- 1
select {
case b <- 1:
checkI(t, -1)
default:
checkI(t, 2)
}
c <- 1
}()
<-c
checkI(t, 3)
}
func TestCloseAfterReceiving(t *testing.T) {
ch := make(chan struct{})
go func() {
<-ch
close(ch)
}()
ch <- struct{}{}
}
func TestDeferWithBlocking(t *testing.T) {
ch := make(chan struct{})
go func() { ch <- struct{}{} }()
defer func() { <-ch }()
fmt.Print("")
return
}
|