mod.rs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. use anyhow::{anyhow, Result};
  2. use serde_json::Value;
  3. use warp::{filters::BoxedFilter, test::WsClient, Reply};
  4. /// A test WebSocket client that sends and receives JSON messages.
  5. pub struct JsonSocket(WsClient);
  6. impl JsonSocket {
  7. pub async fn send(&mut self, msg: &Value) {
  8. self.0.send_text(msg.to_string()).await
  9. }
  10. pub async fn recv(&mut self) -> Result<Value> {
  11. let msg = self.0.recv().await?;
  12. let msg = msg.to_str().map_err(|_| anyhow!("non-string message"))?;
  13. Ok(serde_json::from_str(msg)?)
  14. }
  15. pub async fn recv_closed(&mut self) -> Result<()> {
  16. self.0.recv_closed().await.map_err(|e| e.into())
  17. }
  18. }
  19. /// Connect a new test client WebSocket.
  20. pub async fn connect(
  21. filter: &BoxedFilter<(impl Reply + 'static,)>,
  22. id: &str,
  23. ) -> Result<JsonSocket> {
  24. let client = warp::test::ws()
  25. .path(&format!("/api/socket/{}", id))
  26. .handshake(filter.clone())
  27. .await?;
  28. Ok(JsonSocket(client))
  29. }
  30. /// Check the text route.
  31. pub async fn expect_text(filter: &BoxedFilter<(impl Reply + 'static,)>, id: &str, text: &str) {
  32. let resp = warp::test::request()
  33. .path(&format!("/api/text/{}", id))
  34. .reply(filter)
  35. .await;
  36. assert_eq!(resp.status(), 200);
  37. assert_eq!(resp.body(), text);
  38. }