Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 6, 2023 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/31b388ed519e805a5bc25d9f11d5a59e to your computer and use it in GitHub Desktop.
Save dacr/31b388ed519e805a5bc25d9f11d5a59e to your computer and use it in GitHub Desktop.
ZIO learning - guess number game tests / published by https://github.com/dacr/code-examples-manager #9961b3ce-0e45-4dcb-afa7-a4daea66bceb/b3bacc6e1006cb40680391e0244bf82df6a88ded
// summary : ZIO learning - guess number game tests
// keywords : scala, zio, learning, pure-functional, number-guess, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 9961b3ce-0e45-4dcb-afa7-a4daea66bceb
// created-on : 2021-10-30T09:56:36+02:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.2.2"
//> using dep "dev.zio::zio:2.0.13"
//> using dep "dev.zio::zio-test:2.0.13"
//> using dep "fr.janalyse::zio-worksheet:2.0.13.0"
// ---------------------
import zio.*, zio.worksheet.*
import zio.test.*
import zio.test.Assertion.*
object GameSpec extends ZIOSpecDefault {
val guessNumberGameLogic = for { // TODO - encapsulated as work around for some threading issue when defined globally
_ <- Console.printLine("Let's play a guess number game")
limit <- System.envOrElse("GAME_LIMIT", "5").mapAttempt(_.toInt)
numberToGuess <- Random.nextIntBounded(limit)
_ <- Console.printLine(s"Your choice( 0<=?<$limit) :")
givenNumber <- Console.readLine.mapAttempt(_.toInt)
result = if (numberToGuess == givenNumber) "YOU WIN" else "YOU LOOSE"
_ <- Console.printLine(result)
_ <- Console.printLine("Play again (yes/no) ? ")
playAgain <- Console.readLine.map(_.trim.toLowerCase)
} yield "no" != playAgain
override def spec = suite("guess number tests") {
test("basic game play behavior") {
for {
_ <- TestSystem.putEnv("GAME_LIMIT", "50")
_ <- TestRandom.feedInts(42)
_ <- TestConsole.feedLines("42", "no")
playAgain <- guessNumberGameLogic
output <- TestConsole.output
} yield assertTrue(output.map(_.trim).contains("YOU WIN"))
}
}
}
GameSpec.main(Array.empty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment