blob: 2d80f99c83d326178de2a3cc136e85e9787d233a [file] [log] [blame]
Roman Elizarov1f74a2d2018-06-29 19:19:45 +03001/*
2 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3 */
4
Sergey Mashkovfc84a632017-08-23 12:11:55 +03005package kotlinx.coroutines.experimental.io
6
Sergey Mashkov2c3a0dc2017-09-06 22:58:08 +03007import kotlinx.coroutines.experimental.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +03008import kotlinx.coroutines.experimental.io.internal.*
9import org.junit.*
Roman Elizarov75675e62017-11-30 15:14:44 +030010import org.junit.Test
Roman Elizarov9fe5f462018-02-21 19:05:52 +030011import java.io.*
12import kotlin.coroutines.experimental.*
13import kotlin.test.*
Sergey Mashkovfc84a632017-08-23 12:11:55 +030014
15class CopyAndCloseTest : TestBase() {
16 private val from = ByteChannel(true)
17 private val to = ByteChannel(true)
18
Sergey Mashkov2c3a0dc2017-09-06 22:58:08 +030019 @After
20 fun tearDown() {
21 from.close(CancellationException())
22 to.close(CancellationException())
23 }
24
Sergey Mashkovfc84a632017-08-23 12:11:55 +030025 @Test
26 fun smokeTest() = runBlocking {
27 expect(1)
28
29 launch(coroutineContext) {
30 expect(2)
31 val copied = from.copyAndClose(to) // should suspend
32
33 expect(7)
34
35 assertEquals(8, copied)
36 }
37
38 yield()
39
40 expect(3)
41 from.writeInt(1)
42 expect(4)
43 from.writeInt(2)
44 expect(5)
45
46 yield()
47 expect(6)
48
49 from.close()
50 yield()
51
52 finish(8)
53 }
54
55 @Test
Sergey Mashkov72e91502017-09-03 00:17:14 +030056 fun copyLimitedTest() = runBlocking {
57 expect(1)
58
59 launch(coroutineContext) {
60 expect(2)
61 val copied = from.copyTo(to, 3) // should suspend
62
63 expect(5)
64
65 assertEquals(3, copied)
66 }
67
68 yield()
69
70 expect(3)
71 from.writeByte(1)
72 yield()
73
74 expect(4)
75 from.writeInt(2)
76 yield()
77
78 finish(6)
79 }
Sergey Mashkov2c3a0dc2017-09-06 22:58:08 +030080
81 @Test
82 fun readRemaining() = runBlocking {
83 expect(1)
84
85 launch(coroutineContext) {
86 expect(2)
87 from.writeFully("123".toByteArray())
88
89 yield()
90 expect(3)
91 from.writeFully("456".toByteArray().asByteBuffer())
92
93 yield()
94 expect(4)
95 from.close()
96 }
97
98 yield()
99 assertEquals("123456", from.readRemaining().readText().toString())
100
101 yield()
102
103 finish(5)
104 }
105
106 @Test
107 fun readRemainingLimitFailed() = runBlocking {
108 expect(1)
109
110 launch(coroutineContext) {
111 expect(2)
112 from.writeFully("123".toByteArray())
113
114 yield()
115 expect(3)
116 from.writeFully("456".toByteArray().asByteBuffer())
117 }
118
119 yield()
120 assertEquals("12345", from.readRemaining(5).readText().toString())
121
122 finish(4)
123 }
124
125
Sergey Mashkovfc84a632017-08-23 12:11:55 +0300126}