From ef566e82a2ebf378a4033e401838625c1adebc8c Mon Sep 17 00:00:00 2001 From: Bartosz Blimke Date: Mon, 14 Aug 2023 00:58:53 +0200 Subject: [PATCH] Do not alter real (non-stubbed) request headers when handling em-http-request requests. --- .../em_http_request_adapter.rb | 18 ++++++++++++------ .../em_http_request/em_http_request_spec.rb | 12 ++++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/lib/webmock/http_lib_adapters/em_http_request_adapter.rb b/lib/webmock/http_lib_adapters/em_http_request_adapter.rb index fc410e09..b13d4ce8 100644 --- a/lib/webmock/http_lib_adapters/em_http_request_adapter.rb +++ b/lib/webmock/http_lib_adapters/em_http_request_adapter.rb @@ -101,7 +101,7 @@ def setup(response, uri, error = nil) def connection_completed @state = :response_header - send_request(request_signature.headers, request_signature.body) + send_request(*headers_and_body_processed_by_middleware) end def send_request(head, body) @@ -168,12 +168,18 @@ def build_webmock_response webmock_response end - def build_request_signature - headers, body = build_request, @req.body - - @conn.middleware.select {|m| m.respond_to?(:request) }.each do |m| - headers, body = m.request(self, headers, body) + def headers_and_body_processed_by_middleware + @headers_and_body_processed_by_middleware ||= begin + head, body = build_request, @req.body + @conn.middleware.each do |m| + head, body = m.request(self, head, body) if m.respond_to?(:request) + end + [head, body] end + end + + def build_request_signature + headers, body = headers_and_body_processed_by_middleware method = @req.method uri = @req.uri.clone diff --git a/spec/acceptance/em_http_request/em_http_request_spec.rb b/spec/acceptance/em_http_request/em_http_request_spec.rb index a1574d94..04b4320a 100644 --- a/spec/acceptance/em_http_request/em_http_request_spec.rb +++ b/spec/acceptance/em_http_request/em_http_request_spec.rb @@ -149,6 +149,18 @@ def response(resp) before { WebMock.allow_net_connect! } include_examples "em-http-request middleware/after_request hook integration" + it "doesn't modify headers" do + EM.run do + conn = EventMachine::HttpRequest.new(webmock_server_url) + http = conn.post(head: { 'content-length' => '4' }, body: 'test') + expect(conn).to receive(:send_data).with(/POST \/ HTTP\/1.1\r\nContent-Length: 4\r\nConnection: close\r\nHost: localhost:\d+\r\nUser-Agent: EventMachine HttpClient\r\nAccept-Encoding: gzip, compressed\r\n\r\n/).and_call_original + expect(conn).to receive(:send_data).with('test') + http.callback do + EM.stop + end + end + end + it "only calls request middleware once" do middleware = Class.new do def self.called!