1
0

request_pool_spec.rb 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # frozen_string_literal: true
  2. require 'rails_helper'
  3. RSpec.describe RequestPool do
  4. subject { described_class.new }
  5. describe '#with' do
  6. it 'returns a HTTP client for a host' do
  7. subject.with('http://example.com') do |http_client|
  8. expect(http_client).to be_a HTTP::Client
  9. end
  10. end
  11. it 'returns the same instance of HTTP client within the same thread for the same host' do
  12. test_client = nil
  13. subject.with('http://example.com') { |http_client| test_client = http_client }
  14. expect(test_client).to_not be_nil
  15. subject.with('http://example.com') { |http_client| expect(http_client).to be test_client }
  16. end
  17. it 'returns different HTTP clients for different hosts' do
  18. test_client = nil
  19. subject.with('http://example.com') { |http_client| test_client = http_client }
  20. expect(test_client).to_not be_nil
  21. subject.with('http://example.org') { |http_client| expect(http_client).to_not be test_client }
  22. end
  23. it 'grows to the number of threads accessing it' do
  24. stub_request(:get, 'http://example.com/').to_return(status: 200, body: 'Hello!')
  25. subject
  26. multi_threaded_execution(5) do
  27. subject.with('http://example.com') do |http_client|
  28. http_client.get('/').flush
  29. # Nudge scheduler to yield and exercise the full pool
  30. sleep(0.01)
  31. end
  32. end
  33. expect(subject.size).to be > 1
  34. end
  35. context 'with an idle connection' do
  36. before do
  37. stub_const('RequestPool::MAX_IDLE_TIME', 1) # Lower idle time limit to 1 seconds
  38. stub_const('RequestPool::REAPER_FREQUENCY', 0.1) # Run reaper every 0.1 seconds
  39. stub_request(:get, 'http://example.com/').to_return(status: 200, body: 'Hello!')
  40. end
  41. it 'closes the connections' do
  42. subject.with('http://example.com') do |http_client|
  43. http_client.get('/').flush
  44. end
  45. expect { reaper_observes_idle_timeout }.to change(subject, :size).from(1).to(0)
  46. end
  47. def reaper_observes_idle_timeout
  48. # One full idle period and 2 reaper cycles more
  49. sleep RequestPool::MAX_IDLE_TIME + (RequestPool::REAPER_FREQUENCY * 2)
  50. end
  51. end
  52. end
  53. end