
require 'rexml/document'
require 'amrita2'
require 'amrita2/testsupport'

include Amrita2
include Amrita2::Filters

context "Trace" do
  class BadFilter < Amrita2::Filters::Base
    def value_filter_code(de, cg, value_name)
      cg.code("aaa(")
    end
  end
  
  specify "code tracer" do
    text = '<div><span am:src="aaa" /></div>'
    t = Amrita2::Template.new(text) do |e, name, filters|
      filters.unshift BadFilter.new
    end
    code = ""
    t.set_trace(:code) do |msg|
      code << msg << "\n"
    end
    proc { t.render_with(:aaa=>'Amrita2') }.should raise_error
    code.should_not == nil
    code.should match(/aaa/) 
    #puts t.set_tracer.ruby_code
  end
  
  specify "element trace all" do
    text = '<div><span am:src="aaa" /></div>'
    t = Amrita2::Template.new(text)
    log = ""
    t.set_trace(:all_element) do |msg|
      log << msg << "\n"
    end
    t.render_with(:aaa=>'Amrita2')
    #puts log

    log.size.should > 0
    log.should match(/Amrita2/) 
  end
  
  specify "element tracer" do
    text = '<div><span am:src="aaa|Trace" /></div>'
    t = Amrita2::Template.new(text)
    log = ""
    t.set_trace(:element) do |msg|
      log << msg << "\n"
    end
    t.render_with(:aaa=>'Amrita2')
    #puts log

    log.size.should > 0
    log.should match(/Amrita2/) 
  end
  
  specify "element tracer with loop" do
    text = '<div><p am:src="aaa" /></div>'
    t = Amrita2::Template.new(text)
    log = ""
    t.set_trace(:all_element) do |msg|
      log << msg << "\n"
    end
    t.render_with(:aaa=>(1..5).collect {|n| "Amrita#{n}" })

    log.size.should > 0
    (1..5).each { |n| log.should match(/Amrita#{n}/) }
  end
  
  specify "trace with String" do
    text = '<div><span am:src="aaa" /></div>'
    t = Amrita2::Template.new(text)
    log = ""
    t.set_trace(log)
    t.render_with(:aaa=>'Amrita2')

    log.size.should > 0
    log.should match(/aaa/) 
    log.should match(/Amrita2/) 
  end
  
  specify "trace with StringIO" do
    require "stringio"
    text = '<div><span am:src="aaa" /></div>'
    t = Amrita2::Template.new(text)
    log = StringIO.new("", "w")
    t.set_trace(log)
    t.render_with(:aaa=>'Amrita2')

    log.string.size.should > 0
    log.string.should match(/aaa/) 
    log.string.should match(/Amrita2/) 
  end
end

