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.

63 lines
1.8 KiB

  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 = 20.times.map 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. it 'closes idle connections' do
  39. stub_request(:get, 'http://example.com/').to_return(status: 200, body: 'Hello!')
  40. subject.with('http://example.com') do |http_client|
  41. http_client.get('/').flush
  42. end
  43. expect(subject.size).to eq 1
  44. sleep RequestPool::MAX_IDLE_TIME + 30 + 1
  45. expect(subject.size).to eq 0
  46. end
  47. end
  48. end