require 'test_helper'

class BackendClient::Application::LogRequestsTest < ActiveSupport::TestCase

  include TestHelpers::FakeWeb

  alias url fake_app_url

  def setup
    set_backend_host 'example.org'

    provider_account = Factory(:provider_account)
    @provider_key    = provider_account.api_key

    @application_plan             = Factory( :application_plan, :issuer => provider_account.default_service)
    cinstance        = Factory(:cinstance, :plan => @application_plan)
    @application_id  = cinstance.application_id
    @service_id      = cinstance.service.backend_id

    connection   = BackendClient::Connection.new(:host => backend_host)
    provider     = connection.provider(provider_account)
    @application = provider.application(cinstance)
  end


  # TODO: need to add more tests - timezone calculations
  #
  def test_parsing_backend_output
    timestamp = Time.zone.at(Time.zone.now.to_i) # round microseconds, ruby 1.9.3 has #round
    request = 'request text'
    response = 'response text'
    code = 409
    requests = [
      {:service_id => @service_id, :app_id => @application_id, :timestamp => timestamp, :request => request, :response => response, :code => code}
    ]
    fake_backend_app_log_requests requests

    log_requests = @application.log_requests

    assert_equal 1, log_requests.size
    log = log_requests.first

    assert_equal @service_id, log[:service_id]
    assert_equal @application_id, log[:app_id]
    assert_equal timestamp, log[:timestamp]
    assert_equal request, log[:request]
    assert_equal response, log[:response]
    assert_equal code.to_s, log[:code]
  end

  def test_convert_to_current_time_zone
    Time.use_zone('Alaska') do
      timestamp = Time.utc(2010, 9, 23, 14, 25).in_time_zone('Alaska')
      fake_backend_app_log_requests [{:timestamp => timestamp}]

      log_requests = @application.log_requests
      assert_equal timestamp, log_requests.first[:timestamp]
    end
  end

  def test_deleting_all_log_requests
    fake_backend_app_delete_log_requests

    assert @application.delete_all_log_requests
  end
end
