|
| 1 | +package feral.lambda |
| 2 | + |
| 3 | +import cats.effect.IO |
| 4 | +import cats.effect.Ref |
| 5 | +import cats.effect.kernel.Resource |
| 6 | +import cats.syntax.all._ |
| 7 | +import io.circe.scalajs._ |
| 8 | +import munit.CatsEffectSuite |
| 9 | + |
| 10 | +import scala.scalajs.js |
| 11 | +import scala.scalajs.js.| |
| 12 | + |
| 13 | +class ExportedLambdaSuite extends CatsEffectSuite { |
| 14 | + test("exported lambda") { |
| 15 | + val context = DummyContext.asInstanceOf[facade.Context] |
| 16 | + |
| 17 | + for { |
| 18 | + allocationCounter <- IO.ref(0) |
| 19 | + invokeCounter <- IO.ref(0) |
| 20 | + lambda = new CountingIOLambda(allocationCounter, invokeCounter) |
| 21 | + |
| 22 | + _ <- ('0' to 'z') |
| 23 | + .map(_.toString) |
| 24 | + .toList |
| 25 | + .traverse(x => |
| 26 | + IO.fromPromise(IO(lambda.impl(x, context))) |
| 27 | + .assertEquals(x.asJsAny.asInstanceOf[js.Any | Unit])) |
| 28 | + |
| 29 | + _ <- allocationCounter.get.assertEquals(1) |
| 30 | + _ <- invokeCounter.get.assertEquals(75) |
| 31 | + } yield () |
| 32 | + |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +class CountingIOLambda(allocationCounter: Ref[IO, Int], invokeCounter: Ref[IO, Int]) |
| 37 | + extends IOLambda[String, String] { |
| 38 | + |
| 39 | + override def handler: Resource[IO, LambdaEnv[IO, String] => IO[Option[String]]] = |
| 40 | + Resource |
| 41 | + .eval(allocationCounter.getAndUpdate(_ + 1)) |
| 42 | + .as(_.event.map(Some(_)) <* invokeCounter.getAndUpdate(_ + 1)) |
| 43 | + |
| 44 | + // This would be exported with `@JSExportTopLevel("handler")` |
| 45 | + def impl: HandlerFn = handlerFn |
| 46 | +} |
| 47 | + |
| 48 | +object DummyContext extends js.Object { |
| 49 | + def callbackWaitsForEmptyEventLoop: Boolean = true |
| 50 | + def functionName: String = "" |
| 51 | + def functionVersion: String = "" |
| 52 | + def invokedFunctionArn: String = "" |
| 53 | + def memoryLimitInMB: String = "512" |
| 54 | + def awsRequestId: String = "" |
| 55 | + def logGroupName: String = "" |
| 56 | + def logStreamName: String = "" |
| 57 | + def identity: js.UndefOr[CognitoIdentity] = js.undefined |
| 58 | + def clientContext: js.UndefOr[ClientContext] = js.undefined |
| 59 | + def getRemainingTimeInMillis(): Double = 0 |
| 60 | +} |
0 commit comments