summaryrefslogtreecommitdiff
path: root/spec/lib/gitlab/metrics/transaction_spec.rb
blob: 6862fc9e2d19d1939cca2b68478f4fda12f58512 (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
require 'spec_helper'

describe Gitlab::Metrics::Transaction do
  let(:transaction) { described_class.new }

  describe '#duration' do
    it 'returns the duration of a transaction in seconds' do
      transaction.run { sleep(0.5) }

      expect(transaction.duration).to be >= 0.5
    end
  end

  describe '#run' do
    it 'yields the supplied block' do
      expect { |b| transaction.run(&b) }.to yield_control
    end

    it 'stores the transaction in the current thread' do
      transaction.run do
        expect(Thread.current[described_class::THREAD_KEY]).to eq(transaction)
      end
    end

    it 'removes the transaction from the current thread upon completion' do
      transaction.run { }

      expect(Thread.current[described_class::THREAD_KEY]).to be_nil
    end
  end

  describe '#add_metric' do
    it 'adds a metric tagged with the transaction UUID' do
      expect(Gitlab::Metrics::Metric).to receive(:new).
        with('foo', { number: 10 }, { transaction_id: transaction.uuid })

      transaction.add_metric('foo', number: 10)
    end
  end

  describe '#add_tag' do
    it 'adds a tag' do
      transaction.add_tag(:foo, 'bar')

      expect(transaction.tags).to eq({ foo: 'bar' })
    end
  end

  describe '#finish' do
    it 'tracks the transaction details and submits them to Sidekiq' do
      expect(transaction).to receive(:track_self)
      expect(transaction).to receive(:submit)

      transaction.finish
    end
  end

  describe '#track_self' do
    it 'adds a metric for the transaction itself' do
      expect(transaction).to receive(:add_metric).
        with(described_class::SERIES, { duration: transaction.duration }, {})

      transaction.track_self
    end
  end

  describe '#submit' do
    it 'submits the metrics to Sidekiq' do
      transaction.track_self

      expect(Gitlab::Metrics).to receive(:submit_metrics).
        with([an_instance_of(Hash)])

      transaction.submit
    end
  end
end