require 'lib/helpers/job_waiter'
require "db/mongo/models/job_task"

module Devops::Helpers
  RSpec.describe JobWaiter do
    let(:job_waiter) { described_class.new('job_id') }
    let(:task) { build(:task) }

    before do
      allow(Devops::Model::JobTask).to receive(:find) { task }
      allow(job_waiter).to receive(:sleep)
    end

    it 'it returns 0 when job become completed' do
      allow(task).to receive(:status) { 'completed' }
      expect(job_waiter.wait).to eq 0
    end

    it 'returns error code when job failes' do
      allow(task).to receive(:status) { 'failed' }
      allow(task).to receive(:job_result_code) { 1 }
      expect(job_waiter.wait).to eq 1
    end

    it 'sleeps until something happens' do
      allow(task).to receive(:status).and_return('running', 'running', 'running', 'completed')
      expect(job_waiter).to receive(:sleep).exactly(4).times
      job_waiter.wait
    end

    it 'raises JobWaiter::TimeoutReached if nothing happens for too long' do
      allow(task).to receive(:status) { 'running' }
      expect { job_waiter.wait }.to raise_error(JobWaiter::TimeoutReached)
    end
  end
end
