blob: 91f5c8bd23c27b53cb5ae81f1fbee7a333a1a1d7 [file] [log] [blame]
Vsevolod Tolstopyatov4b9a5592018-04-11 13:17:14 +03001package kotlinx.coroutines.experimental.io
2
3import kotlinx.coroutines.experimental.*
4import kotlinx.coroutines.experimental.channels.ClosedReceiveChannelException
5import org.junit.After
6import org.junit.Test
7import java.io.IOException
8import kotlin.coroutines.experimental.coroutineContext
9
10class ByteChannelCloseTest : TestBase() {
11
12 private val from = ByteChannel(true)
13 private val to = ByteChannel(true)
14
15 @After
16 fun tearDown() {
17 from.close(CancellationException())
18 to.close(CancellationException())
19 }
20
21 @Test
22 fun testCloseWithCause() = runBlocking {
23 expect(1)
24
25 launch(coroutineContext) {
26 expect(2)
27
28 try {
29 from.copyAndClose(to) // should suspend and then throw IOException
30 expectUnreached()
31 } catch (expected: IOException) {
32 expect(4)
33 }
34 }
35
36 yield()
37 expect(3)
38
39 from.close(IOException())
40 yield()
41
42 expect(5)
43
44 try {
45 to.readInt()
46 expectUnreached()
47 } catch (expected: IOException) {
48 finish(6)
49 }
50 }
51
52 @Test
53 fun testCancelWithCause() = runBlocking {
54 expect(1)
55
56 launch(coroutineContext) {
57 expect(2)
58
59 try {
60 from.copyAndClose(to) // should suspend and then throw IOException
61 expectUnreached()
62 } catch (expected: IOException) {
63 expect(4)
64 }
65 }
66
67 yield()
68 expect(3)
69
70 from.cancel(IOException())
71 yield()
72
73 expect(5)
74
75 try {
76 to.readInt()
77 expectUnreached()
78 } catch (expected: IOException) {
79 finish(6)
80 }
81 }
82
83 @Test
84 fun testCloseWithoutCause() = runBlocking {
85 expect(1)
86
87 launch(coroutineContext) {
88 expect(2)
89 from.copyAndClose(to)
90 expect(4)
91 }
92
93 yield()
94 expect(3)
95
96 from.close()
97 yield()
98
99 expect(5)
100 require(to.isClosedForWrite)
101
102 try {
103 to.readInt()
104 expectUnreached()
105 } catch (expected: ClosedReceiveChannelException) {
106 finish(6)
107 }
108 }
109
110 @Test
111 fun testCancelWithoutCause() = runBlocking {
112 expect(1)
113
114 launch(coroutineContext) {
115 expect(2)
116 try {
117 from.copyAndClose(to)
118 expectUnreached()
119 } catch (e: CancellationException) {
120 expect(4)
121 }
122 }
123
124 yield()
125 expect(3)
126
127 from.cancel()
128 yield()
129
130 expect(5)
131 require(to.isClosedForWrite)
132
133 try {
134 to.readInt()
135 expectUnreached()
136 } catch (expected: CancellationException) {
137 finish(6)
138 }
139 }
140}