我在測驗我的第一個 ZIO HTTP4S 應用程式時遇到問題。測驗掛起且未完成。
我的應用程式(簡化)的代碼是
object Main extends App {
def server: ZIO[AppEnvironment, Throwable, Unit] =
for {
(...)
fullApp <- ZIO.runtime[AppEnvironment].flatMap { implicit rts =>
BlazeServerBuilder[AppTask](ec)
.bindHttp(api.port, api.endpoint)
.withHttpApp(CORS(httpApp))
.serve
.compile[AppTask, AppTask, CatsExitCode]
.drain
}
} yield fullApp
override def run(args: List[String]): ZIO[ZEnv, Nothing, ExitCode] = {
server.provideSomeLayer[ZEnv](appEnvironment).tapError(err => putStrLn(s"Execution failed with: $err")).exitCode
}
}
這是我的測驗代碼。請注意,它基本上是從THIS OTHER STACKOVERFLOW QUESTION 復制粘貼的
object ApiTest extends DefaultRunnableSpec {
val ec: ExecutionContext = ExecutionContext.global
def httpServer = Main.run(List()).forkManaged.toLayer
val clockDuration = ofSeconds(1)
val blocker = Blocker.liftExecutionContext(ec)
//did the httpserver start listening on 8080?
private def isLocalPortInUse(port: Int): ZIO[Clock, Throwable, Unit] = {
IO.effect {
println("checking for local port in use")
new Socket("0.0.0.0", port).close()
}
.retry(Schedule.linear(clockDuration) && Schedule.recurs(10))
}
override def spec: ZSpec[Environment, Failure] =
suite("MainTest")(
testM("Health check") {
for {
_ <- TestClock.adjust(clockDuration).fork
_ = println("1")
_ <- isLocalPortInUse(8080)
_ = println("2")
client <- Task(JavaNetClientBuilder[Task](blocker).create)
_ = println("3")
response <- client.expect[String]("http://localhost:8080/healthcheck")
_ = println("4")
} yield assert(response)(equalTo(""))
}
).provideCustomLayerShared(httpServer)
}
問題是一旦服務器啟動,測驗就會停止運行并且不會執行。輸出是
1
checking for local port in use
checking for local port in use
<server init message>
In Suite "MainTest", test "Health check" has taken more than 1 m to execute. If this is not expected, consider using TestAspect.timeout to timeout runaway tests for faster diagnostics.
如您所見,測驗運行正常,直到服務器啟動,然后不再繼續執行。
另外,我如何執行 POST 呼叫而不是 GET 呼叫?我有點迷失在 HTTP4S/ZIO 生態系統與 http4sClients、ZHTTP、BlazeClientBuilders 等。在上一個測驗中對我的服務器進行 POST 呼叫的最簡單方法是什么?
干杯!
編輯:我已經檢查過服務器掛在這里時作業正常,我可以從終端進行 CURL 呼叫并且它回應正確。因此,問題似乎很明顯,一旦服務器啟動,它就會停留在前面,而不是后臺,并且測驗沒有機會完成執行。
uj5u.com熱心網友回復:
您將時鐘提前 1 秒,但您的應用程式可能需要更多時間才能運行。此外,您的特定測驗將需要無限的時間來運行,因為雖然單元測驗在 ZIO 中是即時的,但集成測驗不是。
將單元測驗的時間提前 1 秒理論上需要 0 秒。這可能不足以使埠變得免費。
由于您正在嘗試創建集成測驗,因此您應該使用真實的Clock而不是測驗套件提供的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/489619.html
