require 'spec_helper'

RSpec.describe JenkinsfileRunner::Commands::Init::Configuration do
  subject(:subject) { described_class.new(attributes) }

  let(:all_attributes) do
    [
      '--jfr-version', 'v1',
      '--jenkins-home', __dir__,
      '--jenkins-war', __FILE__,
      '--agent-type', 'shell',
      '--build-output', 'path/to/output'
    ]
  end

  describe '#initialize' do
    let(:attributes) { all_attributes }

    it { is_expected.to have_attributes(jfr_version: 'v1') }
    it { is_expected.to have_attributes(jenkins_home: __dir__) }
    it { is_expected.to have_attributes(jenkins_war: __FILE__) }
    it { is_expected.to have_attributes(agent_type: :shell) }
    it { is_expected.to have_attributes(build_output: 'path/to/output') }
  end

  describe '#valid?' do
    context 'without attributes' do
      let(:attributes) { [] }

      it { expect(subject.valid?).to be_falsey }
    end

    context 'with attributes' do
      let(:attributes) { all_attributes }

      it { expect(subject.valid?).to be_truthy }
    end
  end

  describe '#errors' do
    before do
      subject.valid?
    end

    context 'without attributes' do
      let(:attributes) { [] }

      it { expect(subject.errors).to include([:jfr_version, 'is missing']) }
      it { expect(subject.errors).to include([:jenkins_home, 'is missing']) }
      it { expect(subject.errors).to include([:jenkins_war, 'is missing']) }
      it { expect(subject.errors).to include([:agent_type, 'is missing']) }
      it { expect(subject.errors).to include([:build_output, 'is missing']) }
    end

    context 'with attributes' do
      let(:attributes) { all_attributes }

      it { expect(subject.errors).to be_empty }
    end

    context 'with non existing paths' do
      let(:attributes) do
        [
          '--jenkins-home', '/jenkins/home',
          '--jenkins-war', '/jenkins/home/jenkins.war',
        ]
      end

      it { expect(subject.errors).to include([:jenkins_home, '/jenkins/home does not exist']) }
      it { expect(subject.errors).to include([:jenkins_war, '/jenkins/home/jenkins.war does not exist']) }
    end
  end

  describe 'exceptions' do
    shared_examples 'acceptable agent type' do |agent_type|
      let(:attributes) { ['--agent-type', agent_type] }

      it { expect { subject }.to_not raise_error }
      it { expect(subject.agent_type).to eq(agent_type.to_sym) }
    end

    it_behaves_like 'acceptable agent type', 'shell'
    it_behaves_like 'acceptable agent type', 'docker'

    context 'with unknown agent types' do
      let(:attributes) do
        ['--agent-type', 'remote']
      end

      it 'raises exceptions' do
        expect { subject }.to raise_error OptionParser::InvalidArgument
      end
    end
  end
end
