Run ZIO Http server during ZIO tests

93 views Asked by At

I have hard time understanding how to properly provide and kill the http server fiber.

Ideally I would want the tests to wait for the server to be ready to handle requests and later kill it. Unfortunately all the questions are for either ZIO1 or other case:

My code so far, FakeServer aspect:

object FakeServer {

  val withServer = TestAspect.aroundWith {
    ZIO.logInfo(s"Starting server") *>
      Server
        .serve(Routes(Method.GET / "test" -> handler {
          Response.text("test")
        }).toHttpApp)
        .provide(Server.default)
        .fork
  } { server =>
    ZIO.logInfo(s"Stopping server") *>
      server.interrupt
  }

}

and I am trying to use it as:

object MainSpec extends ZIOSpecDefault {

  override def spec: Spec[Any, Any] = suite("Main") {
    test("should properly work for sample files") {
      // some test that downloads the files
    }
      @@ FakeServer.withServer @@ TestAspect.withLiveClock // seems necessary
  }

}

and so far the server is never ready for the tests and I can't kill it when the test completes.

Any advice highly appreciated!

1

There are 1 answers

0
Atais On

I have requested support on GitHub: https://github.com/zio/zio/issues/8655 and with that help I have managed to make it work with:

  val layer =
    ZLayer.scoped {
      for {
        _ <- ZIO.debug("starting server")
        _ <- ZIO.addFinalizer(ZIO.debug("stopped server"))
        _ <- Server
          .serve(Routes(Method.GET / "test" -> handler {
            Response.text("test")
          }).toHttpApp @@ Middleware.debug)
          .provide(Server.default)
          .forkScoped
        _ <- ZIO.debug("started server")
        _ <- ZIO.addFinalizer(ZIO.debug("stopping server"))
      } yield ()
    }

and now I have extended my test as in the docs:

object MainSpec extends FakeServer {

  override def spec: Spec[Any, Any] = suite("Main") {
    test("should properly work for sample files") {
      // some test that downloads the files
    }
  }.provideLayerShared(layer)

}

and it works fine!

The solution is also on my GitHub: https://github.com/atais/zio-http-e2e-test