You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.8 KiB

3 years ago
  1. import org.scalatest.funsuite.AnyFunSuite
  2. import sttp.client._
  3. import sttp.client.httpclient.monix.HttpClientMonixBackend
  4. import monix.execution.Scheduler
  5. import sttp.client.httpclient.monix.MonixWebSocketHandler
  6. import org.scalatest.BeforeAndAfterAll
  7. import monix.eval.Task
  8. import sttp.model.ws.WebSocketFrame
  9. import scala.concurrent.duration._
  10. import nova.monadic_sfx.implicits._
  11. import monix.catnap.ConcurrentQueue
  12. class WebSocketTest extends AnyFunSuite with BeforeAndAfterAll {
  13. implicit val sched = Scheduler.global
  14. implicit val backend = HttpClientMonixBackend().runSyncUnsafe()
  15. val ws = basicRequest
  16. .get(uri"ws://localhost:6789")
  17. .openWebsocketF(MonixWebSocketHandler())
  18. .map(_.result)
  19. .runSyncUnsafe()
  20. test("open websocket") {
  21. (for {
  22. isOpen <- ws.isOpen
  23. _ <- Task(assert(isOpen == true))
  24. _ <- Task(assert(isOpen != false))
  25. } yield ()).runSyncUnsafe(10.seconds)
  26. }
  27. test("send message") {
  28. (for {
  29. _ <- ws.send(WebSocketFrame.text("Test Message"))
  30. // _ <- Task.sleep(1.second)
  31. // _ <- Task(assert(isOpen == true))
  32. } yield ()).runSyncUnsafe(10.seconds)
  33. }
  34. test("receive messages observable") {
  35. (for {
  36. queue <- ConcurrentQueue.bounded[Task, Int](10)
  37. _ <-
  38. ws.observableSource
  39. .filter(_.isRight)
  40. .map(_.right.get)
  41. .doOnNext(s =>
  42. Task(println(s"Received item: $s")) >>
  43. s.toIntOption.fold(Task.unit)(queue.offer)
  44. )
  45. .take(5)
  46. .completedL
  47. .timeout(5.seconds)
  48. items <- queue.drain(5, 5).timeout(5.seconds)
  49. _ <- Task(assert(items == Seq(1, 2, 3, 4, 5)))
  50. _ <- Task(assert(items != Seq(1, 2, 3, 4, 5, 6)))
  51. } yield ()).runSyncUnsafe(10.seconds)
  52. }
  53. override def afterAll() = {
  54. ws.close.runSyncUnsafe()
  55. backend.close()
  56. }
  57. }