|
| 1 | +package org.scalajs.dom.tests.shared |
| 2 | + |
| 3 | +import org.junit.Assert.assertEquals |
| 4 | +import org.junit.Test |
| 5 | +import org.scalajs.dom.ReadableStream |
| 6 | +import org.scalajs.dom.ReadableStreamController |
| 7 | +import org.scalajs.dom.ReadableStreamUnderlyingSource |
| 8 | +import org.scalajs.dom.tests.shared.AsyncTesting.AsyncResult |
| 9 | +import org.scalajs.dom.tests.shared.AsyncTesting._ |
| 10 | +import org.scalajs.dom.tests.shared.AsyncTesting.async |
| 11 | + |
| 12 | +import scala.concurrent.Future |
| 13 | +import scala.scalajs.js |
| 14 | +import scala.scalajs.js.Thenable.Implicits._ |
| 15 | + |
| 16 | +trait BrowserTests { |
| 17 | + |
| 18 | + @Test |
| 19 | + final def ReadableStreamTest: AsyncResult = async { |
| 20 | + case class Tuna(color: String) |
| 21 | + |
| 22 | + val expectedTunas = Seq( |
| 23 | + Tuna("blue"), |
| 24 | + Tuna("red") |
| 25 | + ) |
| 26 | + |
| 27 | + val stream = ReadableStream[Tuna]( |
| 28 | + new ReadableStreamUnderlyingSource[Tuna] { |
| 29 | + start = { (controller: ReadableStreamController[Tuna]) => |
| 30 | + controller.enqueue(Tuna("blue")) |
| 31 | + controller.enqueue(Tuna("red")) |
| 32 | + controller.close() |
| 33 | + }: js.Function1[ReadableStreamController[Tuna], Unit] |
| 34 | + } |
| 35 | + ) |
| 36 | + |
| 37 | + val reader = stream.getReader() |
| 38 | + |
| 39 | + def read(tunas: Seq[Tuna]): Future[Seq[Tuna]] = { |
| 40 | + reader |
| 41 | + .read() |
| 42 | + .flatMap { chunk => |
| 43 | + if (chunk.done) { |
| 44 | + Future.successful(tunas) |
| 45 | + } else { |
| 46 | + read(tunas :+ chunk.value) |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + read(Seq.empty) |
| 51 | + .map { receivedTunas => |
| 52 | + assertEquals(receivedTunas, expectedTunas) |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments