#!/usr/bin/env ruby
# Copyright (C) 2003-2005 Kouichirou Eto, All rights reserved.

require "test/unit"
$LOAD_PATH.unshift("../../compat") unless $LOAD_PATH.include?("../../compat")
require "htree"

class CheckHTree < Test::Unit::TestCase
  def assert_xhtml(expected, template, message=nil) # from htree/test
    prefix = '<?xml version="1.0" encoding="US-ASCII"?>' +
      "<html xmlns=\"http://www.w3.org/1999/xhtml\"\n>"
    suffix = "</html\n>"
    result = HTree.expand_template(''){"<html>#{template}</html>"}
    assert_match(/\A#{Regexp.quote prefix}/, result)
    assert_match(/#{Regexp.quote suffix}\z/, result)
    result = result[prefix.length..(-suffix.length-1)]
    assert_equal(expected, result, message)
  end

  def test_htree
    assert_xhtml("<b\n>t</b\n>", "<b>t</b>")
    assert_xhtml("<e\n>1</e\n>", '<e _text=1>d</e>')
    str = "<html><e _text=1>d</e></html>"

    doc = HTree(str) # doc is a template
    assert_instance_of(HTree::Doc, doc)
    assert_instance_of(HTree::Elem, doc.root)
    assert_equal("{http://www.w3.org/1999/xhtml}html", doc.root.name)
    assert_instance_of(HTree::Elem, doc.root.children[0])
    assert_instance_of(HTree::Elem, doc.root.children[0])
    assert_instance_of(HTree::Text, doc.root.children[0].children[0])
    assert_instance_of(String, doc.root.children[0].children[0].rcdata)
    assert_equal("d", doc.root.children[0].children[0].rcdata)

    doc = HTree{str} # doc is a document. the template is evaluated.
    assert_instance_of(HTree::Doc, doc)
    assert_instance_of(HTree::Elem, doc.root)
    assert_instance_of(HTree::Elem, doc.root.children[0])
    assert_instance_of(HTree::Text, doc.root.children[0].children[0])
    assert_equal("1", doc.root.children[0].children[0].rcdata)

    str = "<html>\n  <body _text=\"body\"></body>\n</html>"
    body = "b"
    result = HTree.expand_template(''){str}
    assert_equal("<?xml version=\"1.0\" encoding=\"US-ASCII\"?><html xmlns=\"http://www.w3.org/1999/xhtml\"\n><body\n>b</body\n></html\n>", result)
  end
end
