#!ruby

require "test/unit"
require "../xslt"

# Test::Unit suite for flattenx extension
#
# $Id: test.rb,v 1.4 2005/11/14 00:22:27 whateley Exp $
# $Author: whateley $

class XsltTest < Test::Unit::TestCase
  def setup 
    if @xslt.nil? == true
      @xslt = XML::XSLT.new( )
      @testOut = "<?xml version=\"1.0\"?>\nThis is a test file\n"
      @xml_simple = true
      begin
        require "xml/simple"
      rescue LoadError => e
        @xml_simple = false
      end
      
      @xml_smart = true
      begin
        require "xml/smart"
      rescue LoadError => e
        @xml_smart = false
      end
    end
  end
  
  def test_instance
    assert_instance_of( XML::XSLT, @xslt )
  end
  
  def test_from_file
    @xslt.xml = "t.xml"
    @xslt.xsl = "t.xsl"
    out = @xslt.serve
    assert_equal( @testOut, out )
  end

  def test_from_data
    @xslt.xml = IO::readlines( "t.xml" ).join
    @xslt.xsl = IO::readlines( "t.xsl" ).join
    out = @xslt.serve
    assert_equal( @testOut, out )
  end
  
  def test_from_simple
    if @xml_simple
      require 'xml/simple'
      @xslt.xml = XML::Simple.open( "t.xml" )
      @xslt.xsl = XML::Simple.open( "t.xsl" )
      out = @xslt.serve()
      assert_equal( @testOut, out )
    else
      assert( true )
    end
  end

  def test_from_smart
    if @xml_smart
      require 'xml/smart'
      @xslt.xml = XML::Smart.open( "t.xml" )
      @xslt.xsl = XML::Smart.open( "t.xsl" )
      out = @xslt.serve()
      assert_equal( @testOut, out )
    else
      assert( true ) 
    end
  end

  def test_from_rexml
    require 'rexml/document'
    @xslt.xml = REXML::Document.new File.open( "t.xml" )
    @xslt.xsl = REXML::Document.new File.open( "t.xsl" )
    out = @xslt.serve()
    assert_equal( @testOut, out )
  end

  def test_error_1
    begin
      @xslt.xsl = "nil"
    rescue => e
      assert_instance_of( XML::XSLT::ParsingError, e )
    end
  end

  def test_error_2
    begin
      @xslt.xml = "nil"
    rescue => e
      assert_instance_of( XML::XSLT::ParsingError, e )
    end
  end

  def test_error_3
    begin
      @xslt.xml = "t.xsl"
    rescue => e
      assert_instance_of( XML::XSLT::ParsingError, e )
    end
  end

  def test_base_uri_1
    @xslt.xml = "<test/>"
    xsl = "subdir/test.xsl"

    # the base URI of a loaded XSL file should be the URI of that file
    assert_nothing_raised( XML::XSLT::ParsingError ) do
      @xslt.xsl = xsl
    end
  end

  def test_base_uri_2
    @xslt.xml = "<test/>"
    xsl = File.read("subdir/test.xsl")
    
    # a file loaded from memory has no base URI, so this should fail
    assert_raises( XML::XSLT::ParsingError ) do
      @xslt.xsl = xsl
    end
  end
end
