summaryrefslogtreecommitdiff
path: root/spec/lib/gitlab/ci/config/external/rules_spec.rb
blob: 1e42cb30ae7195ad44d4592072c5894d8f7cdcac (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
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::Ci::Config::External::Rules do
  let(:rule_hashes) {}

  subject(:rules) { described_class.new(rule_hashes) }

  describe '#evaluate' do
    let(:context) { double(variables: {}) }

    subject(:result) { rules.evaluate(context).pass? }

    context 'when there is no rule' do
      it { is_expected.to eq(true) }
    end

    context 'when there is a rule with if' do
      let(:rule_hashes) { [{ if: '$MY_VAR == "hello"' }] }

      context 'when the rule matches' do
        let(:context) { double(variables: { MY_VAR: 'hello' }) }

        it { is_expected.to eq(true) }
      end

      context 'when the rule does not match' do
        let(:context) { double(variables: { MY_VAR: 'invalid' }) }

        it { is_expected.to eq(false) }
      end
    end

    context 'when there is a rule with exists' do
      let(:project) { create(:project, :repository) }
      let(:context) { double(project: project, sha: project.repository.tree.sha, top_level_worktree_paths: ['test.md']) }
      let(:rule_hashes) { [{ exists: 'Dockerfile' }] }

      context 'when the file does not exist' do
        it { is_expected.to eq(false) }
      end

      context 'when the file exists' do
        let(:context) { double(project: project, sha: project.repository.tree.sha, top_level_worktree_paths: ['Dockerfile']) }

        before do
          project.repository.create_file(project.owner, 'Dockerfile', "commit", message: 'test', branch_name: "master")
        end

        it { is_expected.to eq(true) }
      end
    end

    context 'when there is a rule with if and when' do
      let(:rule_hashes) { [{ if: '$MY_VAR == "hello"', when: 'on_success' }] }

      it 'raises an error' do
        expect { result }.to raise_error(described_class::InvalidIncludeRulesError,
                                         'invalid include rule: {:if=>"$MY_VAR == \"hello\"", :when=>"on_success"}')
      end
    end

    context 'when there is a rule with changes' do
      let(:rule_hashes) { [{ changes: ['$MY_VAR'] }] }

      it 'raises an error' do
        expect { result }.to raise_error(described_class::InvalidIncludeRulesError,
                                         'invalid include rule: {:changes=>["$MY_VAR"]}')
      end
    end
  end
end