Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Scalatest provider a matcher for NaN?

Does Scalatest provide a matcher for NaN and infinities?

I would like to make these assertions a bit more descriptive if there's a way:

Double.NaN.isNaN shouldBe true
Double.NegativeInfinity.isInfinite shouldBe true
like image 237
Midiparse Avatar asked Jun 13 '19 08:06

Midiparse


People also ask

What is Scala test Scala?

ScalaTest is one of the most popular, complete and easy-to-use testing frameworks in the Scala ecosystem. Where ScalaTest differs from other testing tools is its ability to support a number of different testing styles such as XUnit and BDD out of the box.

Why does be fail in Scalatest matcher?

Because be is used in several ways in ScalaTest matcher syntax, just as it is used in many ways in English, one potential point of confusion in the event of a failure is determining whether be was being used as an equality comparison or in some other way, such as a property assertion.

What is a Scalatest suite?

At the heart of ScalaTest is the concept of a suite, which is simply a collection of zero or more tests 4. Creating Our First Unit Test Now that we have ScalaTest configured and understand some of the philosophy behind the framework, let’s start by defining a simple unit test for testing a List:

Why do we need to import matchers in Scala?

The ability to import them is useful, for example, when you want to use the matchers defined in a trait in the Scala interpreter console. This trait contains one matcher class, FileEndsWithExtensionMatcher, and a def named endWithExtension that returns a new instance of FileEndsWithExtensionMatcher.


1 Answers

The most flexible way to handle this is probably using ScalaTest's support for symbols to handle boolean matches on properties. So, the following tests all work and give a pretty useful error message on failure:

class DoubleSpec extends FreeSpec with Matchers {

  "NaN should be NaN" in {
    Double.box(Double.NaN) shouldBe 'NaN
  }

  "1 should not be NaN" in {
    Double.box(1d) should not be 'NaN
  }

  "Infinity should be infinite" in {
    Double.box(Double.PositiveInfinity) shouldBe 'Infinite
  }

  "1 should not be infinite" in {
    Double.box(1d) should not be 'Infinite
  }
}

Unfortunately, symbol support only exists for reference types - there's an implicit parameter T <:< AnyRef required. I welcome suggestions for handling this without needing to call Double.box every single time.

You can also write your own matchers for this:

  val NaN : BeMatcher[Double] = (left: Double) => MatchResult(
    left.isNaN,
    s"$left is not NaN",
    s"$left is NaN"
  )

  "NaN should be NaN" in {
    Double.NaN shouldBe NaN
  }

  "1 should not be NaN" in {
    1d should not be NaN
  }

Avoids the boxing problem and is more type-safe, but does require a few extra lines of code.

like image 56
Astrid Avatar answered Sep 22 '22 13:09

Astrid