Неожиданное поведение с Faraday::ConnectionFailed

Я пишу клиент для API, который спасает от Faraday::ConnectionFailed и Faraday::TimeoutError, чтобы повторить один и тот же метод MAX_RETRIES раз.

Это основной метод:

def benchmark_request(path)
  retries ||= 0
  request_start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  response = yield

  total_request_seconds = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - request_start_time)
  Rails.logger.info "client request took (#{total_request_seconds}s): #{ENV['API_PATH_PREFIX']}#{path}"

  response
rescue Faraday::ConnectionFailed, Faraday::TimeoutError => e
  retries += 1
  retry if retries <= MAX_RETRIES
end

вызов метода, который:

 def get(path, params = {})
   benchmark_request(path) { token.get("#{ENV['API_PATH_PREFIX']}#{path}", params) }
 end

token.get происходит от драгоценного камня oauth2, который использует Faraday

Вот самое интересное. Я написал 2 спецификации, по 1 для каждого исключения, которое я хочу обработать.

context 'when the endpoint raises a ConnectionFailed' do
  let(:token_expires_at) { 1.hour.from_now.to_i }
  let(:response_body) { '' }
  let(:response_status) { 200 }

  before do
    allow(token).to receive(:get).and_raise(Faraday::ConnectionFailed)
    described_class.get(api_endpoint)
  end

  it 'is called MAX_RETRIES times' do
    expect(token).to have_received(:get).exactly(3).times
  end
end

context 'when the endpoint raises a TimeoutError' do
  let(:token_expires_at) { 1.hour.from_now.to_i }
  let(:response_body) { '' }
  let(:response_status) { 200 }

  before do
    allow(token).to receive(:get).and_raise(Faraday::TimeoutError)
    described_class.get(api_endpoint)
  end

  it 'is called MAX_RETRIES times' do
    expect(token).to have_received(:get).exactly(3).times
  end
end

Тестовое тестирование ConnectionFailed не выполнено, тестовое тестирование TimeoutError горит зеленым цветом. Возникшее исключение:

1) Client::Base.get when the endpoint raises a ConnectionFailed is called MAX_RETRIES times
 Failure/Error: token.get(path, params)

 ArgumentError:
   wrong number of arguments (given 0, expected 1..2)
 # /home/ngw/.rvm/gems/ruby-2.6.2/gems/faraday-0.15.4/lib/faraday/error.rb:7:in `initialize'
 # ./app/lib/client/base.rb:13:in `get'
 # ./spec/lib/client/base_spec.rb:111:in `block (4 levels) in <top (required)>'

Что, по-видимому, связано с тем, как инициализируется Exception.

У кого-нибудь есть идеи?


person ngw    schedule 04.12.2019    source источник


Ответы (1)


before do
   allow(token).to receive(:get).and_raise(Faraday::TimeoutError, 'execution expired')
  described_class.get(api_endpoint)
end

Я решил эту проблему, передав второй аргумент к методу and_raise. Я думаю, это потому, что у Фарадея немного другие классы исключений.

person MikeRogers0    schedule 30.06.2020