In playing with Scala’s combinator parsing framework, I came across the following problem when parsing floating point numbers:
import scala.util.parsing.combinator.JavaTokenParsers
import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.junit.ShouldMatchersForJUnit
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class SandboxSpec extends FlatSpec with ShouldMatchersForJUnit {
"A java token parser" should "parse a float" in {
class Parser extends JavaTokenParsers {
def realValue: Parser[Float] = floatingPointNumber ^^ {
s => s.toFloat
}
}
val p = new Parser()
val result = p.parseAll(p.realValue, "5.4") match {
case p.Success(x, _) => x
case p.Failure(msg, _) => fail(msg)
}
result should equal (5.4f plusOrMinus 0.0001f)
}
}
This test produces the following error:
5.4 did not equal FloatTolerance(5.4,1.0E-4)
I’m not sure if it’s the parser code producing something not float-like (though, looking at it with the debugger, it’s clearly a Java Float), or if it’s an issue with the ScalaTest matcher.
Any thoughts?
In ScalaTest
equalalways means==, thus object equality. Thus, your code does not succeed because5.4is not equal to an instance ofFloatTolerance.To correct your test case use
be, which is overloaded to take an instance ofFloatTolerance:Btw, your code throws a warning:
To eliminate it choose
case p.NoSuccess(msg, _) =>instead ofcase p.Failure(msg, _) =>