require 'lib/executors/stack_executor/prioritized_groups_bootstrapper'

class Devops::Executor::StackExecutor
  RSpec.describe PrioritizedGroupsBootstrapper do
    let(:out) { double(:out, puts: nil, flush: nil) }
    let(:jid) { 1000 }
    let(:groups_bootstrapper) { described_class.new(out, jid, @servers_by_priority) }
    let(:task) { build(:task) }
    before do
      @array1 = []; @array2 = []; @array3 = []
      @servers_by_priority = {2 => @array2, 1 => @array1, 3 => @array3}
      allow(Devops::Model::JobTask).to receive(:find) { task }
    end

    describe '#bootstrap_servers_by_priority' do
      subject { groups_bootstrapper.bootstrap_servers_by_priority }

      it 'bootstraps servers in order by priorities, separately' do
        allow(ServersBootstrapper).to receive(:new) { instance_double(ServersBootstrapper, bootstrap_group: []) }
        expect(ServersBootstrapper).to receive(:new).with(out, jid, @array3).ordered
        expect(ServersBootstrapper).to receive(:new).with(out, jid, @array2).ordered
        expect(ServersBootstrapper).to receive(:new).with(out, jid, @array1).ordered
        expect(subject).to be_ok
      end

      it 'it returns :bootstrap_error result if error occured during bootstrap' do
        allow_any_instance_of(ServersBootstrapper).to receive(:bootstrap_group) {
          [ServersBootstrapper::Result.from_reason(:deploy_error), ServersBootstrapper::Result.from_reason(:bootstrap_error)]
        }
        expect(subject).to be_bootstrap_error
      end

      it 'it returns :deploy_error result if error occured during deploy' do
        allow_any_instance_of(ServersBootstrapper).to receive(:bootstrap_group) {
          [ServersBootstrapper::Result.from_reason(:deploy_error)]
        }
        expect(subject).to be_deploy_error
      end

      it "doesn't bootstrap group if previous one failed" do
        allow_any_instance_of(ServersBootstrapper).to receive(:bootstrap_group) {
          [ServersBootstrapper::Result.from_reason(:deploy_error)]
        }
        allow(ServersBootstrapper).to receive(:new).and_call_original
        expect(ServersBootstrapper).to receive(:new).once
        subject
      end


    end
  end
end
