Skip to content

Commit 1e20ab0

Browse files
author
Dean Wampler
committed
Converted the InvariantSuite to a ScalaCheck test
1 parent a8823d2 commit 1e20ab0

File tree

1 file changed

+29
-19
lines changed

1 file changed

+29
-19
lines changed

src/test/scala/progscala3/meta/InvariantSuite.scala

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,30 +2,40 @@
22
package progscala3.meta
33

44
import munit.*
5+
import org.scalacheck.*
6+
7+
class InvariantSuite extends ScalaCheckSuite:
8+
import Prop.{forAll, propBoolean}
59

6-
class InvariantSuite extends FunSuite:
710
case class Variable(var i: Int, var s: String)
11+
val genVariables =
12+
for
13+
i <- Gen.posNum[Int]
14+
s <- Arbitrary.arbitrary[String]
15+
yield Variable(i, s)
816

9-
def succeed() = // <1>
10-
val v = Variable(0, "Hello!")
11-
val i1 = invariant(v.s == "Hello!") { // <2>
12-
v.i += 1
13-
v.i += 1
14-
v.i
17+
protected def passingInvariant =
18+
forAll(genVariables) { variable =>
19+
val s = variable.s
20+
val i = variable.i
21+
val i2 = invariant(variable.s == s) {
22+
variable.i += 2
23+
variable.i
24+
}
25+
(i2 == i+2 && variable.s == s) :| s"i2=$i2, s=$s, variable = $variable"
1526
}
16-
assert(i1 == 2)
17-
18-
test("invariant.apply should not fail if the invariant holds") { succeed() }
19-
20-
test("invariant.apply should return the value returned by the expressions") { succeed() }
2127

22-
test("invariant.apply should fail if the invariant is broken") {
23-
intercept[invariant.InvariantFailure] { // <3>
24-
val v = Variable(0, "Hello!")
25-
invariant(v.s == "Hello!") {
26-
v.i += 1
27-
v.s = "Goodbye!"
28-
v.i += 1
28+
property("invariant.apply should not fail if the invariant holds") { passingInvariant }
29+
property("invariant.apply should return the value returned by the expressions") { passingInvariant }
30+
property("invariant.apply should fail if the invariant is broken") {
31+
forAll(genVariables) { variable =>
32+
val s = variable.s
33+
intercept[invariant.InvariantFailure] {
34+
invariant(variable.s == s) {
35+
variable.i += 2
36+
variable.s = "bad"
37+
}
2938
}
39+
true // hack to make the types check.
3040
}
3141
}

0 commit comments

Comments
 (0)