# frozen_string_literal: true

module Gitlab
  module QA
    describe Component::Praefect do
      subject(:praefect_component) { described_class.new }
      let(:full_ce_address) { 'registry.gitlab.com/foo/gitlab/gitlab-ce' }
      let(:full_ce_address_with_complex_tag) { "#{full_ce_address}:omnibus-7263a2" }

      describe '#release' do
        context 'with no release' do
          it 'defaults to CE' do
            expect(praefect_component.release.to_s).to eq 'gitlab/gitlab-ce:nightly'
          end
        end
      end

      describe '#release=' do
        before do
          praefect_component.release = release
        end

        context 'when release is a Release object' do
          let(:release) { Release.new('EE') }

          it 'returns a correct release' do
            expect(praefect_component.release.to_s).to eq 'gitlab/gitlab-ee:nightly'
          end
        end

        context 'when release is a string' do
          context 'with a simple tag' do
            let(:release) { full_ce_address_with_complex_tag }

            it 'returns a correct release' do
              expect(praefect_component.release.to_s).to eq full_ce_address_with_complex_tag
            end
          end
        end
      end

      describe '#name' do
        before do
          praefect_component.release = Release.new('CE')
        end

        it 'returns a unique name' do
          expect(praefect_component.name).to match(/\Apraefect-(\w+){8}\z/)
        end
      end

      describe '#reconfigure' do
        let(:docker) { spy('docker') }

        before do
          stub_const('Gitlab::QA::Support::ShellCommand', docker)
          praefect_component.name = "praefect-#{SecureRandom.hex(4)}"
        end

        it 'configures omnibus by writing gitlab.rb' do
          praefect_component.reconfigure

          config = praefect_component.praefect_omnibus_configuration
          expect(docker).to have_received(:new).with(
            eq("docker exec #{praefect_component.name} bash -c \"echo \\\"#{config}\\\" > /etc/gitlab/gitlab.rb;\""),
            anything
          )
        end
      end

      describe '#wait_until_ready' do
        let(:docker) { spy('docker') }

        before do
          stub_const('Gitlab::QA::Support::ShellCommand', docker)
          praefect_component.name = "praefect-#{SecureRandom.hex(4)}"
        end

        it 'waits until praefect is ready' do
          praefect_component.wait_until_ready

          ready_check_cmd = "praefect -config /var/opt/gitlab/praefect/cluster_config.toml check || true"
          expect(docker).to have_received(:new).with(
            eq("docker exec #{praefect_component.name} bash -c \"#{ready_check_cmd}\""), anything
          )
        end
      end
    end
  end
end
