summaryrefslogtreecommitdiff
path: root/spec/workers/container_expiration_policy_worker_spec.rb
blob: 6b185c30670d394428ea7570fc9246d16d5ba7ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ContainerExpirationPolicyWorker do
  include ExclusiveLeaseHelpers

  subject { described_class.new.perform }

  RSpec.shared_examples 'not executing any policy' do
    it 'does not run any policy' do
      expect(ContainerExpirationPolicyService).not_to receive(:new)

      subject
    end
  end

  context 'With no container expiration policies' do
    it_behaves_like 'not executing any policy'
  end

  context 'With container expiration policies' do
    let_it_be(:container_expiration_policy, reload: true) { create(:container_expiration_policy, :runnable) }
    let_it_be(:container_repository) { create(:container_repository, project: container_expiration_policy.project) }
    let_it_be(:user) { container_expiration_policy.project.owner }

    context 'a valid policy' do
      it 'runs the policy' do
        service = instance_double(ContainerExpirationPolicyService, execute: true)

        expect(ContainerExpirationPolicyService)
          .to receive(:new).with(container_expiration_policy.project, user).and_return(service)

        subject
      end
    end

    context 'a disabled policy' do
      before do
        container_expiration_policy.disable!
      end

      it_behaves_like 'not executing any policy'
    end

    context 'a policy that is not due for a run' do
      before do
        container_expiration_policy.update_column(:next_run_at, 2.minutes.from_now)
      end

      it_behaves_like 'not executing any policy'
    end

    context 'a policy linked to no container repository' do
      before do
        container_expiration_policy.container_repositories.delete_all
      end

      it_behaves_like 'not executing any policy'
    end

    context 'an invalid policy' do
      before do
        container_expiration_policy.update_column(:name_regex, '*production')
      end

      it 'runs the policy and tracks an error' do
        expect(ContainerExpirationPolicyService)
          .to receive(:new).with(container_expiration_policy.project, user).and_call_original
        expect(Gitlab::ErrorTracking).to receive(:log_exception).with(instance_of(ContainerExpirationPolicyService::InvalidPolicyError), container_expiration_policy_id: container_expiration_policy.id)

        expect { subject }.to change { container_expiration_policy.reload.enabled }.from(true).to(false)
      end
    end
  end
end