require 'test_helper'

class BackendClient::Application::UtilizationTest < 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: more tests - for infinity stuff, ordering and others

  def test_parsing_backend_output
    metric = @application_plan.metrics.first
    period = 'day'
    max_value = 10
    current_value = 5

    report = {
      :usage_reports => [
        {:max => max_value, :current => current_value, :name => metric.name, :period => period}
      ]
    }

    fake_backend_utilization report

    utilization = @application.utilization([metric])

    assert_equal 1, utilization.size
    record = utilization.first

    assert_equal period, record.period
    assert_equal max_value.to_s, record.max_value.to_s
    assert_equal current_value.to_s, record.current_value.to_s
    assert_equal metric.name, record.system_name
    assert_equal metric.friendly_name, record.friendly_name
  end

  def test_output_order
    metric = @application_plan.metrics.first
    report = {
      :usage_reports => [
        {:max => 10, :current => 1, :name => metric.name, :period => 'minute'},
        {:max => 10, :current => 5, :name => metric.name, :period => 'hour'},
        {:max => 0, :current => 10.5, :name => metric.name, :period => 'day'}
      ]
    }
    fake_backend_utilization report

    utilization = @application.utilization([metric])

    assert_equal 3, utilization.size

    assert_equal '10.5', utilization.first.current_value
    assert_equal 0.0, utilization.first.percentage

    assert_equal '5', utilization.second.current_value
    assert_equal 50.0, utilization.second.percentage

    assert_equal '1', utilization.third.current_value
    assert_equal 10.0, utilization.third.percentage
  end

end
