Search code examples
haskellhunit

Comparison for Text.XML.Light.Element in test


I am trying to write a simple hunit-test to verify how a Text.XML.Light.Element is created from a function.

The function is:

createElement :: String -> String -> XML.Element
createElement tg txt =
 blank_element{ elName = qualName tg
          , elContent = [ Text blank_cdata { cdData = txt } ]
          }

and my test is simply:

import Test.Framework (defaultMain)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (Assertion, assertEqual)
import Text.XML.Light as XML
import MyModule.MyCode (createElement)

testCreateElement :: Assertion
testCreateElement = do
    let tg = "item"
    let txt = "example of text"
    let expectedElement = XML.Element {
                           elName = XML.QName{ qName = tg, qURI = Nothing, qPrefix = Nothing }
                           , elAttribs = [] :: [ Attr ]
                           , elContent = [ fromString txt ] :: [ Content ]
                           , elLine = Nothing
                           }
    assertEqual "create an element" expectedElement (createElement tg txt)

-- utils

fromString :: String -> Content
fromString txt = Text blank_cdata { cdData = txt }

What I get is this error:

No instance for (Eq Element) arising from a use of ‘assertEqual’
    In a stmt of a 'do' block:
      assertEqual "create an element" expectedElement (xmlElement tg txt)
    In the expression:....

I have checked in the source code of Text.XML.Light and it looks like there is no Eq instance defined for Element. How can I make the test work?


Solution

  • You can avoid orphan instances by writing your own equality predicate:

    equalElement :: XML.Element -> XML.Element -> Bool
    equalElement = ...
    

    and then using it via assertBool instead of assertEqual:

    assertBool "create an element" $ equalElement expectedElement (createElement tg txt)