Caliban GraphQL订阅的Scala集成测试
我们有一个Caliban GraphQL应用程序,它与Play框架一起使用。它包含了查询和突变的集成测试,现在我们将添加一些订阅的集成测试,并想知道如何正确地进行 对于查询/突变测试,我们使用常规的Caliban GraphQL订阅的Scala集成测试,scala,testing,playframework,graphql,caliban,Scala,Testing,Playframework,Graphql,Caliban,我们有一个Caliban GraphQL应用程序,它与Play框架一起使用。它包含了查询和突变的集成测试,现在我们将添加一些订阅的集成测试,并想知道如何正确地进行 对于查询/突变测试,我们使用常规的FakeRequest,将其发送到扩展Caliban的PlayRouter的路由器,效果非常好。有没有类似的方法来测试WebSocket/订阅 互联网上关于websocket测试的信息非常少,而关于GraphQL订阅测试的信息则一点也没有 如果您有任何想法,我将不胜感激 好的,我成功了。有两条规则需要
FakeRequest
,将其发送到扩展Caliban的PlayRouter
的路由器,效果非常好。有没有类似的方法来测试WebSocket/订阅
互联网上关于websocket测试的信息非常少,而关于GraphQL订阅测试的信息则一点也没有
如果您有任何想法,我将不胜感激 好的,我成功了。有两条规则需要遵循:
“websocket协议”->“graphql ws”
类型为“connection\u init”
“连接确认”
后,发送类型为“启动”
的图形QLWSRequest
,订阅查询作为有效负载
import caliban.client.GraphQLRequest
import caliban.client.ws.GraphQLWSRequest
import io.circe.syntax.EncoderOps
import play.api.libs.json.{JsValue, Json}
import play.api.test.Helpers.{POST, contentAsJson, contentAsString, contentType, route, status, _}
import org.awaitility.Awaitility
def getWS(subscriptionQuery: String, postQuery: String): JsValue = {
lazy val port = Helpers.testServerPort
val initRequest = prepareWSRequest("connection_init")
val startRequest = prepareWSRequest("start", Some(GraphQLRequest(subscriptionQuery, Map())))
Helpers.running(TestServer(port, app)) {
val headers = new java.util.HashMap[String, String]()
headers.put("WebSocket-Protocol", "graphql-ws")
val queue = new ArrayBlockingQueue[String](1)
lazy val ws = new WebSocketClient(new URI(s"ws://localhost:$port/ws/graphql"), headers) {
override def onOpen(handshakedata: ServerHandshake): Unit =
logger.info("Websocket connection established")
override def onClose(code: Port, reason: String, remote: Boolean): Unit =
logger.info(s"Websocket connection closed, reason: $reason")
override def onError(ex: Exception): Unit =
logger.error("Error handling websocket connection", ex)
override def onMessage(message: String): Unit = {
val ttp = (Json.parse(message) \ "type").as[JsString].value
if (ttp != "connection_ack" && ttp != "ka") queue.put(message)
}
}
ws.connectBlocking()
Future(ws.send(initRequest))
.flatMap(_ => Future(ws.send(startRequest)))
.flatMap(_ => post(query = postQuery)) // post is my local method, it sends usual FakeRequest
Awaitility.await().until(() => queue.peek() != null)
Json.parse(queue.take())
}
def prepareWSRequest(ttp: String, payload: Option[GraphQLRequest] = None) =
GraphQLWSRequest(ttp, None, payload).asJson.noSpaces
}