/
ShortCircuitSpec.scala
77 lines (69 loc) · 1.83 KB
/
ShortCircuitSpec.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package uk.co.odinconsultants.fp.cats.applicatives
import cats.Applicative
import cats.data.Validated.Valid
import cats.data.{NonEmptyList, Validated, ValidatedNec}
import cats.effect.IO
import org.scalatest.{Matchers, WordSpec}
import cats.implicits._
import uk.co.odinconsultants.fp.cats.validation.ValidatedFixture
class ShortCircuitSpec extends WordSpec with Matchers {
class ExpectedException extends Throwable
object ExpectedException extends ExpectedException
"Applicatives" should {
"not short circuit" in new ValidatedFixture {
var i = 0
def failure(): Validated[String, String] = {
println("failure")
i = i + 1
invalid1
}
def success(): Validated[String, String] = {
println("valid")
i = i + 1
valid1
}
success() *> failure() *> success()
i shouldBe 3
}
}
"Monadic effects" should {
type MonadType = IO[Int]
val aye: MonadType = IO {
println("aye")
42
}
val nay: MonadType = IO.raiseError(ExpectedException)
"short-circuit if one nay" in {
val io = for {
result <- aye *> nay
expected <- nay
} yield {
fail(s"result = $result, expected = $expected")
}
assertThrows[ExpectedException] {
io.unsafeRunSync()
}
}
"not short circuit if both aye" in {
val io = for {
result <- aye *> aye
expected <- aye
} yield {
println(s"result = $result, expected = $expected")
result shouldBe expected
}
io.unsafeRunSync()
}
}
"Monads" should {
type MonadType = Either[String, Int]
val aye: MonadType = Right(1)
val nay: MonadType = Left("nope")
"short-circuit" in {
aye *> nay *> aye shouldBe nay
}
"not short circuit" in {
aye *> aye shouldBe aye
}
}
}