Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala XML equality issues

Tags:

xml

scala

equals

I want to write a test case for a case class, that has a toXML method.

import java.net.URI

case class Person(
  label: String = "author",
  name: String,
  email: Option[String] = None,
  uri: Option[URI] = None) {

  // author must be either "author" or "contributor"
  assert(label == "author" ||
    label == "contributor")

  def toXML = {
    val res =
      <author>
        <name>{ name }</name>
        {
          email match {
            case Some(email) => <email>{ email }</email>
            case None => Null
          }
        }
        {
          uri match {
            case Some(uri) => <uri>{ uri }</uri>
            case None => Null
          }
        }
      </author>

    label match {
      case "author" => res
      case _ => res.copy(label = label) // rename element
    }
  }
}

Now, I want to assert, that the output is correct. Therefor I use scala.xml.Utility.trim

import scala.xml.Utility.trim

val p1 = Person("author", "John Doe", Some("[email protected]"),
  Some(new URI("http://example.com/john")))
val p2 =
  <author>
    <name>John Doe</name>
    <email>[email protected]</name>
    <uri>http://example.com/john</uri>
  </author>

assert(trim(p1.toXML) == trim(p2))

But this will cause an assertion error. If I try to assert equality by comparing the String representations

assert(trim(p1.toXML).toString == trim(p2).toString)

there’s no assertion error.

What am I doing wrong?

like image 305
pvorb Avatar asked Dec 06 '25 09:12

pvorb


1 Answers

First of all there's something wrong with your code: you have uri: Option[URI] (which I'm assuming is java.net.URI) as a constructor argument, but then you call the constructor with an Option[String].

This is also the source of your problem:

scala> val uri = "http://stackoverflow.com/q/10676812/334519"
uri: java.lang.String = http://stackoverflow.com/q/10676812/334519

scala> <u>{new java.net.URI(uri)}</u> == <u>{uri}</u>
res0: Boolean = false

scala> <u>{new java.net.URI(uri)}</u>.toString == <u>{uri}</u>.toString
res1: Boolean = true

What's happening is that the element's child is an Atom, which has a type parameter for the data value it carries. In your p1 this is a URI (assuming we've corrected the test so that it matches the constructor), and in p2 it's a String.

like image 90
Travis Brown Avatar answered Dec 09 '25 01:12

Travis Brown