require 'spec_helper'
require 'debci/job_latency'
require 'debci/job'

describe Debci::JobLatency do
  let(:package) { Debci::Package.create!(name: 'mypkg') }
  let(:theuser) { Debci::User.create!(username: 'debci') }

  def create_job(**data)
    Debci::Job.create!(
      package: package,
      suite: 'unstable',
      arch: Debci.config.arch,
      requestor: theuser,
      status: 'pass',
      **data,
    )
  end

  after(:each) do
    Debci::JobLatency.reset!
  end

  it 'gets latency per architecture' do
    now = Time.now
    create_job(created_at: now - 2.hours, received_at: now - 1.hour)
    results = Debci::JobLatency.fetch
    expect(results.length).to be > 0

    # the following tests don't work with sqlite; ENOTIME to debug now
    next if ActiveRecord::Base.connection.class.name =~ /sqlite/i

    entry = results.first
    expect(entry.arch).to eq(Debci.config.arch)
    expect(entry.latency).to eq(1.hour)
  end

  it 'caches results when calling #get' do
    data = Object.new
    expect(Debci::JobLatency).to receive(:fetch).once.and_return(data)
    expect(Debci::JobLatency.get).to be(data)
    expect(Debci::JobLatency.get).to be(data)
  end

  def entry(duration)
    Debci::JobLatency.new('arm64', duration)
  end

  it 'displays the latency in days, hours, minutes' do
    # ActiveSupport::Duration#isnpect has a weird way of displaying durations
    expect(entry(77.hours).in_words).to eq("3 days, 5 hours")
    expect(entry(25.hours).in_words).to eq("1 day, 1 hour")
    expect(entry(111.minutes).in_words).to eq("1 hour, 51 minutes")
  end
end
