summaryrefslogtreecommitdiff
path: root/spec/lib/gitlab/pagination/keyset/cursor_based_request_context_spec.rb
blob: 79de6f230ec14e0e1de839815f59ba1a4cb9a9cb (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
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::Pagination::Keyset::CursorBasedRequestContext do
  let(:params) { { per_page: 2, cursor: 'eyJuYW1lIjoiR2l0TGFiIEluc3RhbmNlIiwiaWQiOiI1MiIsIl9rZCI6Im4ifQ==', order_by: :name, sort: :asc } }
  let(:request) { double('request', url: 'http://localhost') }
  let(:request_context) { double('request_context', header: nil, params: params, request: request) }

  describe '#per_page' do
    subject(:per_page) { described_class.new(request_context).per_page }

    it { is_expected.to eq 2 }
  end

  describe '#cursor' do
    subject(:cursor) { described_class.new(request_context).cursor }

    it { is_expected.to eq 'eyJuYW1lIjoiR2l0TGFiIEluc3RhbmNlIiwiaWQiOiI1MiIsIl9rZCI6Im4ifQ==' }
  end

  describe '#order_by' do
    subject(:order_by) { described_class.new(request_context).order_by }

    it { is_expected.to eq({ name: :asc }) }
  end

  describe '#apply_headers' do
    let(:request) { double('request', url: "http://#{Gitlab.config.gitlab.host}/api/v4/projects?per_page=3") }
    let(:params) { { per_page: 3 } }
    let(:request_context) { double('request_context', header: nil, params: params, request: request) }
    let(:cursor_for_next_page) { 'eyJuYW1lIjoiSDVicCIsImlkIjoiMjgiLCJfa2QiOiJuIn0=' }

    subject(:apply_headers) { described_class.new(request_context).apply_headers(cursor_for_next_page) }

    it 'sets Link header with same host/path as the original request' do
      orig_uri = URI.parse(request_context.request.url)

      expect(request_context).to receive(:header).once do |name, header|
        first_link, _ = /<([^>]+)>; rel="next"/.match(header).captures

        uri = URI.parse(first_link)

        expect(name).to eq('Link')
        expect(uri.host).to eq(orig_uri.host)
        expect(uri.path).to eq(orig_uri.path)
      end

      apply_headers
    end

    it 'sets Link header with a cursor to the next page' do
      orig_uri = URI.parse(request_context.request.url)

      expect(request_context).to receive(:header).once do |name, header|
        first_link, _ = /<([^>]+)>; rel="next"/.match(header).captures

        query = CGI.parse(URI.parse(first_link).query)

        expect(name).to eq('Link')
        expect(query.except('cursor')).to eq(CGI.parse(orig_uri.query).except('cursor'))
        expect(query['cursor']).to eq([cursor_for_next_page])
      end

      apply_headers
    end
  end
end