require 'test/unit'
require 'feed_tools'
require 'mock_cache'

# scaffolding
class XMLTests < Test::Unit::TestCase
  def setup
    @@save_cache = FeedTools.feed_cache
    FeedTools.feed_cache = MockCache
    FeedTools.tidy_enabled = false
  end

  def teardown
    FeedTools.feed_cache = @@save_cache
  end
end

# default methods to be public
XMLTests.send(:public)

# add one unit test for each file
Dir['test/**/*.xml'].each do |xmlfile|
  XMLTests.send(:define_method, xmlfile.gsub('/','_').sub('.xml','')) {

    # extract description, evalString
    feed_data = MockCache.loadfile(xmlfile)
    test = feed_data.scan /Description:\s*(.*?)\s*Expect:\s*(.*)\s*-->/
    raise RuntimeError, "can't parse #{xmlfile}" if test.empty?
    description, evalString = test.first.map {|s| s.strip}
  
    # Python to Ruby
    evalString.gsub! /\bu('.*?')/, '\1'    # u'string' => 'string'
    evalString.gsub! /\bu(".*?")/, '\1'    # u"string" => "string"
    evalString.gsub! /\['(\w+)'\]/, '.\1'  # ['x'] => .x
  
    # Evaluate feed
    feed = FeedTools::Feed.open(MockCache.cache_object.url)
    assert feed.instance_eval(evalString), description.inspect

  }
end

# adjust for expected differences between the UFP and FeedTools
class FeedTools::Feed
  def bozo
    return false
  end

  alias_method :textinput, :text_input
end
