require 'minitest_helper'

require 'events'
require 'app/jobs/events_fetch_job'

require 'resque_unit'
require 'resque_unit_scheduler'

class EventsTest < MiniTest::Unit::TestCase
  def test_async_fetch_backend_events
    Events.async_fetch_backend_events!

    assert_queued EventsFetchJob
    assert_queued_in 0, EventsFetchJob
  end

  def test_async_fetch_backend_events_is_immune_to_multithreading
    Resque.reset!(:events)

    3.times { Events.async_fetch_backend_events! }

    assert_equal 1, Resque.size(:events)
  end

  def test_fetch_backend_events
    timestamp = Time.now.iso8601
    one = ThreeScale::Core::Event.new({ type: 'one', id: 1, timestamp: timestamp })
    two = ThreeScale::Core::Event.new({ type: 'two', id: 2, timestamp: timestamp })

    Events::Importer.expects(:clear_services_cache)
    PersistEventWorker.expects(:enqueue).with(one.attributes)
    PersistEventWorker.expects(:enqueue).with(two.attributes)
    Events.expects(:delete_events_from_backend_until!).with(2)

    Events.fetch_backend_events! [one, two]
  end

  def test_delete_events_from_backend_until
    ThreeScale::Core::Event.expects(:delete_upto).with(42)
    Events.delete_events_from_backend_until!(42)
  end
end
