Skip to content

Instantly share code, notes, and snippets.

@bvenners
Last active August 29, 2015 13:57
Show Gist options
  • Save bvenners/9379784 to your computer and use it in GitHub Desktop.
Save bvenners/9379784 to your computer and use it in GitHub Desktop.
In ScalaTest 2.1.0, String beauty is no longer just skin deep
// In ScalaTest/ScalaUtils 2.1.0 the Prettifier, which in 2.0 just prettified objects at the top level,
// has been enhanced to prettify objects contained inside other objects, including Scala and Java
// collections, Option, Either, and Try. Here's an example:
scala> val actual = Set(List(Map(1 -> Some("2"), 2 -> Some("3"))))
actual: scala.collection.immutable.Set[List[scala.collection.immutable.Map[Int,Some[String]]]] =
Set(List(Map(1 -> Some(2), 2 -> Some(3))))
scala> val expected = Set(List(Map('1' -> Some(2), '2' -> Some(3))))
expected: scala.collection.immutable.Set[List[scala.collection.immutable.Map[Char,Some[Int]]]] =
Set(List(Map(1 -> Some(2), 2 -> Some(3))))
// Note that the toStrings above are identical with each other, even though none
// of the types are identical. Now take a look at an error message involving these
// values:
scala> import org.scalatest.Assertions._
import org.scalatest.Assertions._
scala> assert(actual == expected)
org.scalatest.exceptions.TestFailedException: Set(List(Map(1 -> Some("2"), 2 -> Some("3")))) did not
equal Set(List(Map('1' -> Some(2), '2' -> Some(3))))
// ScalaTest 2.1.0 prettified the Strings that were inside an Option that were values in a Map contained
// inside a List sitting inside a first Set, and prettified the Chars that were keys in the Map in the
// List in the second Set.
// Of course a better way to detect this particular kind of problem is at compile time. Since the two
// types of expected and actual are different, you could catch the bug this way:
scala> import org.scalautils.TypeCheckedTripleEquals._
import org.scalautils.TypeCheckedTripleEquals._
scala> assert(actual === expected)
<console>:28: error: types scala.collection.immutable.Set[List[scala.collection.immutable.Map[Int,Some[String]]]]
and scala.collection.immutable.Set[List[scala.collection.immutable.Map[Char,Some[Int]]]] do not adhere to the
type constraint selected for the === and !== operators; the missing implicit parameter is of type
org.scalautils.Constraint[scala.collection.immutable.Set[List[scala.collection.immutable.Map[Int,Some[String]]]],
scala.collection.immutable.Set[List[scala.collection.immutable.Map[Char,Some[Int]]]]]
assert(actual === expected)
^
// The rather long-winded compiler error message explains that the types are not compatible for being compared
// for equality. Nevertheless, many error messages do make it out the door as test failures, and
// the enhanced Prettifier in 2.1.0 should help clarify which objects were involved.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment