You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.9 KiB

  1. # frozen_string_literal: true
  2. require 'rails_helper'
  3. describe Request do
  4. subject { Request.new(:get, 'http://example.com') }
  5. describe '#headers' do
  6. it 'returns user agent' do
  7. expect(subject.headers['User-Agent']).to be_present
  8. end
  9. it 'returns the date header' do
  10. expect(subject.headers['Date']).to be_present
  11. end
  12. it 'returns the host header' do
  13. expect(subject.headers['Host']).to be_present
  14. end
  15. it 'does not return virtual request-target header' do
  16. expect(subject.headers['(request-target)']).to be_nil
  17. end
  18. end
  19. describe '#on_behalf_of' do
  20. it 'when used, adds signature header' do
  21. subject.on_behalf_of(Fabricate(:account))
  22. expect(subject.headers['Signature']).to be_present
  23. end
  24. end
  25. describe '#add_headers' do
  26. it 'adds headers to the request' do
  27. subject.add_headers('Test' => 'Foo')
  28. expect(subject.headers['Test']).to eq 'Foo'
  29. end
  30. end
  31. describe '#perform' do
  32. context 'with valid host' do
  33. before { stub_request(:get, 'http://example.com') }
  34. it 'executes a HTTP request' do
  35. expect { |block| subject.perform &block }.to yield_control
  36. expect(a_request(:get, 'http://example.com')).to have_been_made.once
  37. end
  38. it 'executes a HTTP request when the first address is private' do
  39. allow(Addrinfo).to receive(:foreach).with('example.com', nil, nil, :SOCK_STREAM)
  40. .and_yield(Addrinfo.new(["AF_INET", 0, "example.com", "0.0.0.0"], :PF_INET, :SOCK_STREAM))
  41. .and_yield(Addrinfo.new(["AF_INET6", 0, "example.com", "2001:4860:4860::8844"], :PF_INET6, :SOCK_STREAM))
  42. expect { |block| subject.perform &block }.to yield_control
  43. expect(a_request(:get, 'http://example.com')).to have_been_made.once
  44. end
  45. it 'sets headers' do
  46. expect { |block| subject.perform &block }.to yield_control
  47. expect(a_request(:get, 'http://example.com').with(headers: subject.headers)).to have_been_made
  48. end
  49. it 'closes underlaying connection' do
  50. expect_any_instance_of(HTTP::Client).to receive(:close)
  51. expect { |block| subject.perform &block }.to yield_control
  52. end
  53. end
  54. context 'with private host' do
  55. around do |example|
  56. WebMock.disable!
  57. example.run
  58. WebMock.enable!
  59. end
  60. it 'raises Mastodon::ValidationError' do
  61. allow(Addrinfo).to receive(:foreach).with('example.com', nil, nil, :SOCK_STREAM)
  62. .and_yield(Addrinfo.new(["AF_INET", 0, "example.com", "0.0.0.0"], :PF_INET, :SOCK_STREAM))
  63. .and_yield(Addrinfo.new(["AF_INET6", 0, "example.com", "2001:db8::face"], :PF_INET6, :SOCK_STREAM))
  64. expect{ subject.perform }.to raise_error Mastodon::ValidationError
  65. end
  66. end
  67. end
  68. end