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.

62 lines
1.8 KiB

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