summaryrefslogtreecommitdiff
path: root/spec/lib/gitlab/avatar_cache_spec.rb
blob: ffe6f81b6e7316108b19297c34c500c66bf0b355 (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
96
97
98
99
100
101
# frozen_string_literal: true

require "spec_helper"

RSpec.describe Gitlab::AvatarCache, :clean_gitlab_redis_cache do
  def with(&blk)
    Gitlab::Redis::Cache.with(&blk) # rubocop:disable CodeReuse/ActiveRecord
  end

  def read(key, subkey)
    with do |redis|
      redis.hget(key, subkey)
    end
  end

  let(:thing) { double("thing", avatar_path: avatar_path) }
  let(:avatar_path) { "/avatars/my_fancy_avatar.png" }
  let(:key) { described_class.send(:email_key, "foo@bar.com") }

  let(:perform_fetch) do
    described_class.by_email("foo@bar.com", 20, 2, true) do
      thing.avatar_path
    end
  end

  describe "#by_email" do
    it "writes a new value into the cache" do
      expect(read(key, "20:2:true")).to eq(nil)

      perform_fetch

      expect(read(key, "20:2:true")).to eq(avatar_path)
    end

    it "finds the cached value and doesn't execute the block" do
      expect(thing).to receive(:avatar_path).once

      described_class.by_email("foo@bar.com", 20, 2, true) do
        thing.avatar_path
      end

      described_class.by_email("foo@bar.com", 20, 2, true) do
        thing.avatar_path
      end
    end

    it "finds the cached value in the request store and doesn't execute the block" do
      expect(thing).to receive(:avatar_path).once

      Gitlab::WithRequestStore.with_request_store do
        described_class.by_email("foo@bar.com", 20, 2, true) do
          thing.avatar_path
        end

        described_class.by_email("foo@bar.com", 20, 2, true) do
          thing.avatar_path
        end

        expect(Gitlab::SafeRequestStore.read([key, "20:2:true"])).to eq(avatar_path)
      end
    end
  end

  describe "#delete_by_email" do
    subject { described_class.delete_by_email(*emails) }

    before do
      perform_fetch
    end

    context "no emails, somehow" do
      let(:emails) { [] }

      it { is_expected.to eq(0) }
    end

    context "single email" do
      let(:emails) { "foo@bar.com" }

      it "removes the email" do
        expect(read(key, "20:2:true")).to eq(avatar_path)

        expect(subject).to eq(1)

        expect(read(key, "20:2:true")).to eq(nil)
      end
    end

    context "multiple emails" do
      let(:emails) { ["foo@bar.com", "missing@baz.com"] }

      it "removes the emails it finds" do
        expect(read(key, "20:2:true")).to eq(avatar_path)

        expect(subject).to eq(1)

        expect(read(key, "20:2:true")).to eq(nil)
      end
    end
  end
end