
module Amrita2GetTextTestSupport

  def redirect_stderr
    stderr_sv = STDERR.dup  
    STDERR.reopen("/dev/null") 
    yield
    STDERR.flush             
    STDERR.reopen(stderr_sv)
  end
  
  def test_gettext(domain, fname, template, po_matchers, data, ja_result)
    FileUtils::rm_rf("locale")
    FileUtils::rm_rf("po")
    FileUtils::rm_rf(fname)

    File::open(fname, "w") do |f|
      f.puts template
    end


    redirect_stderr do 
      GetText.update_pofiles(domain,
                             [fname],
                             "#{domain} 1.0.0"  
                             )
    end
    po = File::open("po/#{domain}.pot").read

    po_matchers.each do |m|
      po.should match(m)
    end

    FileUtils::mkdir_p("po/ja")
    File::open("po/#{domain}.pot") do |potf|
      File::open("po/ja/#{domain}.po", "w") do |pof|
        l = yield(potf.read) 
        pof.puts l
      end
    end

    redirect_stderr do 
      GetText.create_mofiles(true, "po", "locale")
    end

    Locale.set_current("ja", "JP", "utf8")
    ENV['GETTEXT_PATH'] = "./locale"

    t = Template.new(template) do |e, src, filters|
      filters << Amrita2::Filters::GetTextFilter.new
    end

    t.text_domain = domain
    if data.kind_of?(Binding)
      eval "bindtextdomain(#{domain.inspect})", data
    end
    t.test_with(data) do |result|
      result.strip.should_be_samexml_as ja_result
    end
  ensure
    FileUtils::rm_rf("locale")
    FileUtils::rm_rf("po")
    FileUtils::rm_rf(fname)
  end
end
