Skip to main content
Version: 2.x

Law Testing

Many abstractions come with laws. An equality must be reflexive, symmetric and transitive, and a map operation must keep a value unchanged when given the identity function. The package zio.test.laws describes such laws as values, so a library writes the laws of a type class once and checks every instance of it with generators. You rarely need this in application code; it is for libraries that define type classes, such as ZIO Prelude.

Writing Lawsโ€‹

A law is a property that every instance of a capability must satisfy. A capability is a type class such as Equal[A], and the laws are written once for any type A that has it. We write a law by extending Laws.Law1, Laws.Law2 or Laws.Law3, which check one, two or three values, and implementing its apply method. The string given to the constructor names the law in test results:

import zio.test._
import zio.test.laws._

trait Equal[-A] {
def equal(a1: A, a2: A): Boolean
}

val reflexive: Laws.Law1[Equal] =
new Laws.Law1[Equal]("reflexive") {
def apply[A: Equal](a1: A): TestResult =
assertTrue(implicitly[Equal[A]].equal(a1, a1))
}

val symmetric: Laws.Law2[Equal] =
new Laws.Law2[Equal]("symmetric") {
def apply[A: Equal](a1: A, a2: A): TestResult = {
val eq = implicitly[Equal[A]]
assertTrue(eq.equal(a1, a2) == eq.equal(a2, a1))
}
}

val transitive: Laws.Law3[Equal] =
new Laws.Law3[Equal]("transitive") {
def apply[A: Equal](a1: A, a2: A, a3: A): TestResult = {
val eq = implicitly[Equal[A]]
assertTrue(!(eq.equal(a1, a2) && eq.equal(a2, a3)) || eq.equal(a1, a3))
}
}

val equalLaws: Laws[Equal] = reflexive + symmetric + transitive

ZLaws#+ combines laws into one set. Laws[Caps] is short for ZLaws[Caps, Any]; the second type parameter is the environment the laws need. A law that runs an effect extends ZLaws.Law1ZIO, ZLaws.Law2ZIO or ZLaws.Law3ZIO, whose apply returns a ZIO that produces the TestResult.

Running Lawsโ€‹

ZLaws#run takes a generator of values of a type that has the capability, and returns an effect that produces a TestResult. Each law uses check to draw its own samples, 200 by default, stops at its first failing sample, shrinks it, and labels the failure with the law's name. The effect itself does not fail.

An equality that treats numbers one apart as equal is reflexive and symmetric but not transitive, so it fails the laws:

val closeEnoughResult = {
implicit val closeEnough: Equal[Int] =
new Equal[Int] {
def equal(a1: Int, a2: Int): Boolean = (a1 - a2).abs <= 1
}

equalLaws.run(Gen.int(0, 2))
}

Running the check shows that the result is a failure:

zio.Unsafe.unsafe { implicit unsafe =>
zio.Runtime.default.unsafe.run(closeEnoughResult.map(_.isSuccess)).getOrThrowFiberFailure()
}
// res0: Boolean = false

In a spec, the result of ZLaws#run is the body of a test, and checkAllLaws does the same for a lawful object, described next.

Lawful Objectsโ€‹

A type class usually keeps its laws in its companion object. Extending ZLawful, or its alias Lawful for laws with no environment, means defining a laws member; checkAllLaws(lawful)(gen) then checks an instance against them. Two lawful objects combine with ZLawful#+, and the combined laws need one instance that has both capabilities:

trait Hash[-A] extends Equal[A] {
def hash(a: A): Int
}

object EqualLaws extends Lawful[Equal] {
val laws: Laws[Equal] = equalLaws
}

object HashLaws extends Lawful[Hash] {
val laws: Laws[Hash] =
new Laws.Law2[Hash]("consistent") {
def apply[A: Hash](a1: A, a2: A): TestResult = {
val h = implicitly[Hash[A]]
assertTrue(!h.equal(a1, a2) || h.hash(a1) == h.hash(a2))
}
}
}

object IntHashSpec extends ZIOSpecDefault {
implicit val intHash: Hash[Int] =
new Hash[Int] {
def equal(a1: Int, a2: Int): Boolean = a1 == a2
def hash(a: Int): Int = a.hashCode
}

def spec =
test("Int obeys the Equal and Hash laws") {
checkAllLaws(EqualLaws + HashLaws)(Gen.int)
}
}

ZLaws2 and ZLawful2 do the same for capabilities that relate two types, such as a conversion from A to B; checkAllLaws then takes a generator for each type.

Laws for Parameterized Typesโ€‹

Some capabilities belong to a type constructor F[_] rather than a type, such as a Mappable[F] that can map over an F[A]. Their laws hold for every element type A, so they need a way to generate F[A] values for any A. A GenF[R, F] is that recipe: given a Gen of A values, it returns a Gen of F[A] values. GenF has instances for Chunk, List, Option, Set and Vector, and GenF.either and GenF.map build them for Either and Map from a generator of the other type parameter.

ZLawsF.Covariant, ZLawsF.Contravariant and ZLawsF.Invariant hold laws for covariant, contravariant and invariant type constructors, and ZLawsF2.Divariant for those with one contravariant and one covariant parameter. Each companion has constructors to extend: Law1 to Law3, their ZIO variants, and ComposeLaw for laws about two composed functions. ZLawsF.Covariant also has FlattenLaw for laws about nested values. Their run methods, such as ZLawsF.Covariant#run, and checkAllLaws for the matching ZLawfulF objects, take a GenF and a Gen:

trait Mappable[F[+_]] {
def map[A, B](fa: F[A])(f: A => B): F[B]
}

val identityLaw: ZLawsF.Covariant[Mappable, Equal, Any] =
new ZLawsF.Covariant.Law1[Mappable, Equal]("identity") {
def apply[F[+_]: Mappable, A: Equal](fa: F[A]): TestResult =
assertTrue(implicitly[Mappable[F]].map(fa)(identity) == fa)
}

val optionIdentity = {
implicit val optionMappable: Mappable[Option] =
new Mappable[Option] {
def map[A, B](fa: Option[A])(f: A => B): Option[B] = fa.map(f)
}
implicit val intEqual: Equal[Int] =
new Equal[Int] {
def equal(a1: Int, a2: Int): Boolean = a1 == a2
}

identityLaw.run(GenF.option, Gen.int)
}

Polymorphic Generatorsโ€‹

A law checked only with Int values may hide a bug that shows up with another type. The package zio.test.poly generates values of a type that is chosen at random. A GenPoly holds a type member T and a generator genT of T values, and GenPoly.genPoly is a generator of GenPolys that picks among Boolean, Byte, Char, Double, Float, Int, Long, String and Unit, and lists, options and vectors of them. Its subtypes add a type class for T: GenOrderingPoly an Ordering[T], GenNumericPoly a Numeric[T], and GenIntegralPoly and GenFractionalPoly an Integral[T] or a Fractional[T]. Each has its own generator, such as GenNumericPoly.genNumericPoly.

To check that sorting is idempotent for many element types instead of one:

import zio.test.poly._

object SortSpec extends ZIOSpecDefault {
def spec =
test("sorting twice equals sorting once") {
check(GenOrderingPoly.genOrderingPoly) { poly =>
implicit val ordering: Ordering[poly.T] = poly.ordT
check(Gen.listOf(poly.genT)) { values =>
assertTrue(values.sorted.sorted == values.sorted)
}
}
}
}

See Alsoโ€‹

  • Built-in Generators โ€” The generators that laws draw their samples from.
  • Shrinking โ€” How ZIO Test reduces a failing sample to a smaller one.

ZIO Chat

Hi there! ๐Ÿ‘‹ I'm ZIO Chat, your friendly neighborhood ZIO expert. I'm here to help you navigate the world of ZIO. Whether you're a seasoned pro or just starting out, fire away with your ZIO questions. I will hit you back with the best insights I've got. Let's dive into the world of ZIO together!