Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created September 27, 2024 20:58
Show Gist options
  • Save fancellu/fcf06131da0de1fe7d5a74f9623852db to your computer and use it in GitHub Desktop.
Save fancellu/fcf06131da0de1fe7d5a74f9623852db to your computer and use it in GitHub Desktop.
FakeConsoleExample zio supplying a fake Console
import zio._
object FakeConsoleExample extends ZIOAppDefault {
private val program = ZIO.serviceWithZIO[Console] { console =>
for {
_ <- console.printLine("Going to the grocery store")
input <- console.readLine("How are you? ")
_ <- console.printLine(s"You said: $input")
} yield ()
}
private val live = Console.ConsoleLive
private val fakeConsoleLayer: ULayer[Console] = ZLayer.succeed(
new Console {
override def readLine(implicit trace: Trace): UIO[String] =
ZIO.succeed(
"I'm fine(this is canned)"
)
// Delegate all other methods to ConsoleLive, but always send to stderr
override def print(line: => Any)(implicit trace: Trace) =
live.printError(line)
override def printError(line: => Any)(implicit trace: Trace) =
live.printError(line)
override def printLine(line: => Any)(implicit trace: Trace) =
live.printLineError(line)
override def printLineError(line: => Any)(implicit trace: Trace) =
live.printLineError(line)
}
)
override def run = program.provide(
fakeConsoleLayer
)
}
@fancellu
Copy link
Author

Output, all to stderr

Going to the grocery store
How are you? You said: I'm fine(this is canned)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment