request_pool_spec.rb 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # frozen_string_literal: true
  2. require 'rails_helper'
  3. 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. threads = Array.new(20) do |_i|
  27. Thread.new do
  28. 20.times do
  29. subject.with('http://example.com') do |http_client|
  30. http_client.get('/').flush
  31. end
  32. end
  33. end
  34. end
  35. threads.map(&:join)
  36. expect(subject.size).to be > 1
  37. end
  38. context 'with an idle connection' do
  39. before do
  40. stub_const('RequestPool::MAX_IDLE_TIME', 1) # Lower idle time limit to 1 seconds
  41. stub_const('RequestPool::REAPER_FREQUENCY', 0.1) # Run reaper every 0.1 seconds
  42. stub_request(:get, 'http://example.com/').to_return(status: 200, body: 'Hello!')
  43. end
  44. it 'closes the connections' do
  45. subject.with('http://example.com') do |http_client|
  46. http_client.get('/').flush
  47. end
  48. expect { reaper_observes_idle_timeout }.to change(subject, :size).from(1).to(0)
  49. end
  50. def reaper_observes_idle_timeout
  51. # One full idle period and 2 reaper cycles more
  52. sleep RequestPool::MAX_IDLE_TIME + (RequestPool::REAPER_FREQUENCY * 2)
  53. end
  54. end
  55. end
  56. end