Skip to content

Instantly share code, notes, and snippets.

@pyldin601
Created September 7, 2016 14:42
Show Gist options
  • Save pyldin601/a7e2c875882ce2d14a6835243d13d7ec to your computer and use it in GitHub Desktop.
Save pyldin601/a7e2c875882ce2d14a6835243d13d7ec to your computer and use it in GitHub Desktop.
package biz.radioteria.flow.stream
import com.sun.org.apache.xpath.internal.operations.Bool
import junit.framework.TestCase
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.OutputStream
class OutputStreamsTest : TestCase() {
private class BlockingOutputStream(val blockingTime: Long, var isClosed: Boolean = false) : OutputStream() {
override fun write(b: Int) {
Thread.sleep(blockingTime)
}
override fun write(b: ByteArray?) {
Thread.sleep(blockingTime)
}
override fun write(b: ByteArray?, off: Int, len: Int) {
Thread.sleep(blockingTime)
}
override fun flush() {
Thread.sleep(blockingTime)
}
override fun close() {
isClosed = true
}
}
fun testNonBlockingBasicCase() {
val innerOutputStream = ByteArrayOutputStream()
val outerOutputStream = NonblockingOutputStream(innerOutputStream)
val testData = "Hello, World!"
outerOutputStream.write(testData.toByteArray())
outerOutputStream.close()
assertEquals(testData, String(innerOutputStream.toByteArray()))
}
fun testBlockingBasicCase() {
val innerOutputStream = BlockingOutputStream(5000L)
val outerOutputStream = NonblockingOutputStream(innerOutputStream, 5)
val testData = byteArrayOf()
for (i in 0 until 5) {
outerOutputStream.write(testData)
}
try {
outerOutputStream.write(testData)
fail("Expected IOException")
} catch (e: IOException) {
}
assertTrue("Inner stream must be closed", innerOutputStream.isClosed)
}
fun testMulTeeBasicCase() {
val targetStreams = (0 until 5).map { ByteArrayOutputStream() }.toTypedArray()
val mulTeeOutputStream = MulTeeOutputStream(*targetStreams)
val testData = "foo"
mulTeeOutputStream.write(testData.toByteArray())
mulTeeOutputStream.close()
targetStreams.map { String(it.toByteArray()) }.forEach {
assertEquals(testData, it)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment