require "test/unit/testcase"

require 'rexml/source'

class EncodingTester < Test::Unit::TestCase
  include REXML

  def setup
    @encoded = "<?xml version='1.0' encoding='ISO-8859-3'?>"+
    "<a><b>\346</b></a>"
    @not_encoded = "<a><b>ĉ</b></a>"
  end

  # Given an encoded document, try to write out to that encoding
	def test_encoded_in_encoded_out
    doc = Document.new( @encoded )
    out = ""
    doc.write( out )
    assert_equal( @encoded, out )
  end

  # Given an encoded document, try to change the encoding and write it out
  def test_encoded_in_change_out
    doc = Document.new( @encoded )
    doc.xml_decl.encoding = "UTF-8"
    assert_equal( doc.encoding, "UTF-8" )
    out = ""
    doc.root.write( out )
    assert_equal( @not_encoded, out )
    char = XPath.first( doc, "/a/b/text()" ).to_s
    assert_equal( "ĉ", char )
  end

  # * Given an encoded document, try to write it to a different encoding
  def test_encoded_in_different_out
    doc = Document.new( @encoded )
    out = ""
    doc.root.write( Output.new( out, "UTF-8" ) )
    assert_equal( @not_encoded, out )
  end

  # * Given a non-encoded document, change the encoding
  def test_in_change_out
    doc = Document.new( @not_encoded )
    doc.xml_decl.encoding = "ISO-8859-3"
    assert_equal( doc.encoding, "ISO-8859-3" )
    out = ""
    doc.write( out )
    assert_equal( @encoded, out )
  end

  # * Given a non-encoded document, write to a different encoding
  def test_in_different_out
    doc = Document.new( @not_encoded )
    out = ""
    doc.write( Output.new( out, "ISO-8859-3" ) )
    assert_equal( @encoded, out )
  end
end
