summaryrefslogtreecommitdiff
path: root/spec/support/http_io/http_io_helpers.rb
blob: 42144870eb5cf3c7375e043ef5a14512536d0370 (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
module HttpIOHelpers
  def stub_remote_url_206(url, file_path)
    WebMock.stub_request(:get, url)
      .to_return { |request| remote_url_response(file_path, request, 206) }
  end

  def stub_remote_url_200(url, file_path)
    WebMock.stub_request(:get, url)
      .to_return { |request| remote_url_response(file_path, request, 200) }
  end

  def stub_remote_url_500(url)
    WebMock.stub_request(:get, url)
      .to_return(status: [500, "Internal Server Error"])
  end

  def remote_url_response(file_path, request, response_status)
    range = request.headers['Range'].match(/bytes=(\d+)-(\d+)/)

    body = File.read(file_path).force_encoding(Encoding::BINARY)
    size = body.bytesize

    {
      status: response_status,
      headers: remote_url_response_headers(response_status, range[1].to_i, range[2].to_i, size),
      body: body[range[1].to_i..range[2].to_i]
    }
  end

  def remote_url_response_headers(response_status, from, to, size)
    { 'Content-Type' => 'text/plain' }.tap do |headers|
      if response_status == 206
        headers.merge('Content-Range' => "bytes #{from}-#{to}/#{size}")
      end
    end
  end

  def set_smaller_buffer_size_than(file_size)
    blocks = (file_size / 128)
    new_size = (blocks / 2) * 128
    stub_const("Gitlab::HttpIO::BUFFER_SIZE", new_size)
  end

  def set_larger_buffer_size_than(file_size)
    blocks = (file_size / 128)
    new_size = (blocks * 2) * 128
    stub_const("Gitlab::HttpIO::BUFFER_SIZE", new_size)
  end
end