summaryrefslogtreecommitdiff
path: root/spec/lib/gitlab/sidekiq_middleware/worker_context/server_spec.rb
blob: 377ff6fd166d6524014034e861fc27d3493c1de4 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::SidekiqMiddleware::WorkerContext::Server do
  let(:test_worker) do
    Class.new do
      def self.name
        "TestWorker"
      end

      # To keep track of the context that was active for certain arguments
      cattr_accessor(:contexts) { {} }

      include ApplicationWorker

      feature_category :foo
      worker_context user: nil

      def perform(identifier, *args)
        self.class.contexts.merge!(identifier => Gitlab::ApplicationContext.current)
      end
    end
  end

  let(:not_owned_worker) do
    Class.new(test_worker) do
      def self.name
        "NotOwnedWorker"
      end

      feature_category_not_owned!
    end
  end

  let(:other_worker) do
    Class.new do
      def self.name
        "OtherWorker"
      end

      include Sidekiq::Worker

      def perform
      end
    end
  end

  before do
    stub_const("TestWorker", test_worker)
    stub_const("NotOwnedWorker", not_owned_worker)
    stub_const("OtherWorker", other_worker)
  end

  around do |example|
    with_sidekiq_server_middleware do |chain|
      chain.add described_class
      Sidekiq::Testing.inline! { example.run }
    end
  end

  describe "#call" do
    it 'applies a class context' do
      Gitlab::ApplicationContext.with_context(user: build_stubbed(:user)) do
        TestWorker.perform_async("identifier", 1)
      end

      expect(TestWorker.contexts['identifier'].keys).not_to include('meta.user')
    end

    context 'feature category' do
      it 'takes the feature category from the worker' do
        Gitlab::ApplicationContext.with_context(feature_category: 'authentication_and_authorization') do
          TestWorker.perform_async('identifier', 1)
        end

        expect(TestWorker.contexts['identifier']).to include('meta.feature_category' => 'foo')
      end

      context 'when the worker is not owned' do
        it 'takes the feature category from the surrounding context' do
          Gitlab::ApplicationContext.with_context(feature_category: 'authentication_and_authorization') do
            NotOwnedWorker.perform_async('identifier', 1)
          end

          expect(NotOwnedWorker.contexts['identifier']).to include('meta.feature_category' => 'authentication_and_authorization')
        end
      end
    end

    it "doesn't fail for unknown workers" do
      expect { OtherWorker.perform_async }.not_to raise_error
    end
  end
end