summaryrefslogtreecommitdiff
path: root/spec/services/keys/last_used_service_spec.rb
blob: c675df39f4d4ed4462170343709be1d24c1b8973 (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
# frozen_string_literal: true

require 'spec_helper'

describe Keys::LastUsedService do
  describe '#execute', :clean_gitlab_redis_shared_state do
    it 'updates the key when it has not been used recently' do
      key = create(:key, last_used_at: 1.year.ago)
      time = Time.zone.now

      Timecop.freeze(time) { described_class.new(key).execute }

      expect(key.reload.last_used_at).to be_like_time(time)
    end

    it 'does not update the key when it has been used recently' do
      time = 1.minute.ago
      key = create(:key, last_used_at: time)

      described_class.new(key).execute

      expect(key.last_used_at).to be_like_time(time)
    end

    it 'does not update the updated_at field' do
      # Since a lot of these updates could happen in parallel for different keys
      # we want these updates to be as lightweight as possible, hence we want to
      # make sure we _only_ update last_used_at and not always updated_at.
      key = create(:key, last_used_at: 1.year.ago)

      expect { described_class.new(key).execute }.not_to change { key.updated_at }
    end
  end

  describe '#update?', :clean_gitlab_redis_shared_state do
    it 'returns true when no last used timestamp is present' do
      key = build(:key, last_used_at: nil)
      service = described_class.new(key)

      expect(service.update?).to eq(true)
    end

    it 'returns true when the key needs to be updated' do
      key = build(:key, last_used_at: 1.year.ago)
      service = described_class.new(key)

      expect(service.update?).to eq(true)
    end

    it 'returns false when a lease has already been obtained' do
      key = build(:key, last_used_at: 1.year.ago)
      service = described_class.new(key)

      expect(service.update?).to eq(true)
      expect(service.update?).to eq(false)
    end

    it 'returns false when the key does not yet need to be updated' do
      key = build(:key, last_used_at: 1.minute.ago)
      service = described_class.new(key)

      expect(service.update?).to eq(false)
    end
  end
end