webmock 3.34.0 → 3.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +358 -0
  3. data/README.md +222 -3
  4. data/lib/webmock/api.rb +4 -0
  5. data/lib/webmock/errors.rb +1 -1
  6. data/lib/webmock/http_lib_adapters/async_http_client_adapter.rb +51 -7
  7. data/lib/webmock/http_lib_adapters/curb_adapter.rb +291 -39
  8. data/lib/webmock/http_lib_adapters/em_http_request_adapter.rb +11 -3
  9. data/lib/webmock/http_lib_adapters/excon_adapter.rb +23 -2
  10. data/lib/webmock/http_lib_adapters/http_rb/webmock.rb +33 -4
  11. data/lib/webmock/http_lib_adapters/http_rb_adapter.rb +4 -1
  12. data/lib/webmock/http_lib_adapters/httpclient_adapter.rb +132 -110
  13. data/lib/webmock/http_lib_adapters/manticore_adapter.rb +1 -1
  14. data/lib/webmock/http_lib_adapters/net_http.rb +66 -3
  15. data/lib/webmock/http_lib_adapters/net_http_response.rb +28 -2
  16. data/lib/webmock/http_lib_adapters/patron_adapter.rb +242 -40
  17. data/lib/webmock/http_lib_adapters/typhoeus_hydra_adapter.rb +65 -7
  18. data/lib/webmock/json_body_hint.rb +8 -5
  19. data/lib/webmock/request_body_diff.rb +16 -6
  20. data/lib/webmock/request_execution_verifier.rb +13 -2
  21. data/lib/webmock/request_pattern.rb +236 -36
  22. data/lib/webmock/request_registry.rb +75 -5
  23. data/lib/webmock/request_signature.rb +44 -5
  24. data/lib/webmock/request_signature_snippet.rb +23 -2
  25. data/lib/webmock/request_stub.rb +8 -4
  26. data/lib/webmock/response.rb +42 -3
  27. data/lib/webmock/stub_registry.rb +7 -6
  28. data/lib/webmock/stub_request_snippet.rb +9 -3
  29. data/lib/webmock/trailing_slash_hint.rb +55 -0
  30. data/lib/webmock/util/hash_counter.rb +27 -8
  31. data/lib/webmock/util/hash_keys_stringifier.rb +23 -1
  32. data/lib/webmock/util/headers.rb +17 -0
  33. data/lib/webmock/util/message_string.rb +28 -0
  34. data/lib/webmock/util/parsers/json.rb +33 -2
  35. data/lib/webmock/util/query_mapper.rb +56 -37
  36. data/lib/webmock/util/upload_body.rb +63 -0
  37. data/lib/webmock/util/uri.rb +21 -12
  38. data/lib/webmock/util/values_stringifier.rb +54 -0
  39. data/lib/webmock/version.rb +1 -1
  40. data/lib/webmock/webmock.rb +35 -4
  41. data/lib/webmock.rb +3 -0
  42. metadata +7 -4
data/README.md CHANGED
@@ -23,7 +23,7 @@ Supported HTTP libraries
23
23
  ------------------------
24
24
 
25
25
  * [Async::HTTP::Client](https://github.com/socketry/async-http)
26
- * [Curb](https://github.com/taf2/curb) (currently only Curb::Easy)
26
+ * [Curb](https://github.com/taf2/curb) (`Curl::Easy` and `Curl::Multi`)
27
27
  * [EM-HTTP-Request](https://github.com/igrigorik/em-http-request)
28
28
  * [Excon](https://github.com/excon/excon)
29
29
  * [HTTPClient](https://github.com/nahi/httpclient)
@@ -74,6 +74,8 @@ rake install
74
74
 
75
75
  WebMock 2.x has changed somewhat since version 1.x. Changes are listed in [CHANGELOG.md](CHANGELOG.md)
76
76
 
77
+ ## Setup
78
+
77
79
  ### Cucumber
78
80
 
79
81
  Create a file `features/support/webmock.rb` with the following contents:
@@ -106,6 +108,48 @@ Add the following code to `test/test_helper.rb`
106
108
  require 'webmock/test_unit'
107
109
  ```
108
110
 
111
+ ### What the test framework integrations do
112
+
113
+ `webmock/rspec`, `webmock/minitest`, `webmock/test_unit` and `webmock/cucumber` do three things:
114
+
115
+ * They enable WebMock. `webmock/rspec` does it in a `before(:suite)` hook and disables WebMock again in `after(:suite)`. The others enable it as soon as they are required.
116
+ * They call `WebMock.reset!` after every example, test or scenario. This removes the stubs declared with `stub_request` and the history of requests, so a stub declared in RSpec's `before(:all)` or `before(:context)`, or in a minitest-hooks `before_all`, is gone after the first example. Declare such stubs in `before(:each)` or `setup` instead, or use [global stubs](#global-stubs), which `WebMock.reset!` keeps. If you override `teardown` in Minitest, call `super`, or WebMock's reset doesn't run.
117
+ * They leave the net connect settings alone. By default WebMock blocks real requests. `WebMock.allow_net_connect!` allows them all, and `WebMock.disable_net_connect!` blocks them again, except for what its options allow, such as `allow_localhost: true`. Each setting stays in effect for every later example until you change it, and each call to `disable_net_connect!` replaces the `allow`, `allow_localhost` and `net_http_connect_on_start` options given before.
118
+
119
+ Requiring one of these files in a spec helper or in any spec file enables WebMock for the whole run, not only for that file. To use WebMock only in some examples, require `webmock` and set it up yourself, for example for RSpec examples tagged with `:webmock`:
120
+
121
+ ```ruby
122
+ require 'webmock'
123
+ require 'webmock/rspec/matchers'
124
+
125
+ WebMock::AssertionFailure.error_class = RSpec::Expectations::ExpectationNotMetError
126
+
127
+ RSpec.configure do |config|
128
+ config.include WebMock::API, :webmock
129
+ config.include WebMock::Matchers, :webmock
130
+
131
+ config.around(:each, :webmock) do |example|
132
+ WebMock.enable!
133
+ WebMock.disable_net_connect!
134
+ example.run
135
+ ensure
136
+ WebMock.reset!
137
+ WebMock.disable!
138
+ end
139
+ end
140
+ ```
141
+
142
+ Examples without the tag then make real requests. Create HTTP clients inside each example: a client created while WebMock was disabled isn't intercepted, and a Curb or HTTPClient object created in a tagged example is still intercepted after it.
143
+
144
+ Enabling WebMock and allowing real requests are separate settings. `WebMock.enable!` and `WebMock.disable!` decide whether WebMock intercepts requests at all. `WebMock.disable_net_connect!` and `WebMock.allow_net_connect!` decide what happens to an intercepted request that no stub matches. While WebMock is disabled, it doesn't intercept requests, so these settings only take effect once it is enabled again.
145
+
146
+ For HTTP clients such as Net::HTTP, HTTPClient and Curb, WebMock intercepts requests by replacing their classes while it is enabled. `webmock/rspec` enables WebMock just before the first example, after your app and spec files have loaded. A class that inherits from `Net::HTTP`, or an HTTP client object such as a `Net::HTTP` or `HTTPClient` instance, created while they load uses the original class, and its requests reach the network. A client that creates its HTTP object for each request is not affected. If your app defines such a class or creates such an object while it loads, enable WebMock right after requiring it:
147
+
148
+ ```ruby
149
+ require 'webmock/rspec'
150
+ WebMock.enable!
151
+ ```
152
+
109
153
  ### Outside a test framework
110
154
 
111
155
  You can also use WebMock outside a test framework:
@@ -335,6 +379,23 @@ RestClient.get("http://www.example.com/?a=b") # ===> Failure
335
379
  RestClient.get("http://www.example.com/?a=c") # ===> Success
336
380
  ```
337
381
 
382
+ ### Matching repeated query params
383
+
384
+ By default WebMock reads a query the way Rack and Rails do, so a key repeated without brackets keeps only its last value: `?a=1&a=2` is read as `?a=2`. To match repeated keys, switch to the `:flat_array` notation and give the query as a string:
385
+
386
+ ```ruby
387
+ WebMock::Config.instance.query_values_notation = :flat_array
388
+
389
+ stub_request(:get, "www.example.com/?a=1&a=2")
390
+ # or
391
+ stub_request(:get, "www.example.com").with(query: "a=1&a=2")
392
+
393
+ RestClient.get("http://www.example.com/?a=1&a=2") # ===> Success
394
+ RestClient.get("http://www.example.com/?a=2") # ===> Failure
395
+ ```
396
+
397
+ The notation applies to every stub and request. Hashes can't describe repeated keys, so with `:flat_array`, `hash_including`, `hash_excluding`, query hashes given with a regexp or template URI, and form bodies given as a hash don't match. Set the notation only in the tests that need it, and set it back to `:subscript` afterwards.
398
+
338
399
  ### Stubbing with custom response
339
400
 
340
401
  ```ruby
@@ -351,6 +412,12 @@ Set appropriate Content-Type for HTTParty's `parsed_response`.
351
412
  stub_request(:any, "www.example.com").to_return body: '{}', headers: {content_type: 'application/json'}
352
413
  ```
353
414
 
415
+ For JSON, `to_return_json` sets it for you:
416
+
417
+ ```ruby
418
+ stub_request(:any, "www.example.com").to_return_json(body: {})
419
+ ```
420
+
354
421
  ### Response with body specified as IO object
355
422
 
356
423
  ```ruby
@@ -372,6 +439,8 @@ stub_request(:any, "www.example.com").
372
439
  Net::HTTP.get('www.example.com', '/') # ===> "{\"foo\": \"bar\"}"
373
440
  ```
374
441
 
442
+ `to_return_json` encodes the body and sets the `Content-Type` header to `application/json`, so there is no need to call `to_json` or set the header yourself. A `Content-Type` given in `headers` takes precedence.
443
+
375
444
  A `File` or `Pathname` body is returned as it is, so it should hold JSON that is already encoded:
376
445
 
377
446
  ```ruby
@@ -501,6 +570,20 @@ stub_request(:any, 'www.example.net').to_timeout
501
570
  RestClient.post('www.example.net', 'abc') # ===> RestClient::RequestTimeout
502
571
  ```
503
572
 
573
+ ### Curb multi requests
574
+
575
+ `Curl::Multi` matches each handle against stubs when it is added. An unstubbed
576
+ handle raises `WebMock::NetConnectNotAllowedError` from `multi.add` unless its
577
+ URL is allowed by WebMock's network settings. Stubbed handles complete when
578
+ `multi.perform` runs; allowed handles still run together on curb's native multi
579
+ loop. Both kinds of requests are recorded and invoke callbacks, including
580
+ `WebMock.after_request`. Callbacks registered with `real_requests_only: true`
581
+ receive only real transfers.
582
+
583
+ This also applies to `Curl::Multi.get`, `post`, `put` and `http`, and the `Curl.get`
584
+ and `Curl.post` convenience methods. Create the multi and easy handles after
585
+ WebMock is enabled, as with `Curl::Easy` requests.
586
+
504
587
  ### Multiple responses for repeated requests
505
588
 
506
589
  ```ruby
@@ -650,6 +733,26 @@ RestClient.get('bbc.com', '/') # ===> Allowed
650
733
  RestClient.get('www.bbc.com', '/') # ===> Failure
651
734
  ```
652
735
 
736
+ ### Real requests can be allowed or disabled only within a block
737
+
738
+ Given a block, `WebMock.allow_net_connect!` and `WebMock.disable_net_connect!` apply their settings only while the block runs and return the block's value. When the block ends, even with an exception, WebMock restores the settings from before the call.
739
+
740
+ ```ruby
741
+ WebMock.disable_net_connect!
742
+
743
+ WebMock.allow_net_connect! do
744
+ Net::HTTP.get('www.something.com', '/') # ===> /.+Something.+/
745
+ end
746
+
747
+ WebMock.disable_net_connect!(allow: 'www.example.org') do
748
+ RestClient.get('www.example.org', '/') # ===> Allowed
749
+ end
750
+
751
+ Net::HTTP.get('www.something.com', '/') # ===> Failure
752
+ ```
753
+
754
+ Settings changed inside the block, for example by another call to `WebMock.disable_net_connect!`, are undone as well. The settings are global, so other threads see them while the block runs, and blocks that overlap in different threads can restore each other's settings in the wrong order. Use the block form only where tests run one at a time in each process.
755
+
653
756
  ## Connecting on Net::HTTP.start
654
757
 
655
758
  HTTP protocol has 3 steps: connect, request and response (or 4 with close). Most Ruby HTTP client libraries
@@ -726,6 +829,8 @@ assert_requested(stub_get)
726
829
  assert_not_requested(stub_post)
727
830
  ```
728
831
 
832
+ See [What an expectation on a stub counts](#what-an-expectation-on-a-stub-counts) for which requests these assertions count.
833
+
729
834
 
730
835
  ### Setting expectations in RSpec on `WebMock` module
731
836
  This style is borrowed from [fakeweb-matcher](http://github.com/pat/fakeweb-matcher)
@@ -802,9 +907,59 @@ expect(stub).to have_been_requested.once.with(body: {"a" => [4, 5, 6]})
802
907
 
803
908
  Options and a block given to `with` take the same form as in `stub_request(...).with`. The expectation then counts only the requests that match both the stub and those conditions. The stub itself does not change.
804
909
 
910
+ ### What an expectation on a stub counts
911
+
912
+ An expectation on a stub, such as `assert_requested(stub)` or `expect(stub).to have_been_requested`, counts the requests since the last `WebMock.reset!` or `WebMock.reset_executed_requests!` that match the stub's pattern. A matching request counts even if another stub answered it, if it was made before the stub was declared, or if it was made after the stub was removed with `remove_request_stub`.
913
+
914
+ ```ruby
915
+ stub_any = stub_request(:post, "www.example.com")
916
+ stub_body = stub_request(:post, "www.example.com").with(body: "abc")
917
+
918
+ Net::HTTP.post(URI("http://www.example.com"), "abc") # answered by stub_body
919
+
920
+ expect(stub_body).to have_been_requested.once # ===> Success
921
+ expect(stub_any).to have_been_requested.once # ===> Success, as its pattern matches too
922
+ ```
923
+
924
+ To make an expectation stricter, give the stub its own conditions, such as `with(body: "")` for requests without a body. In RSpec you can also add them to the expectation with `with`, as shown above. With `assert_requested`, pass the method and URL instead of the stub, for example `assert_requested(:post, "www.example.com", body: "")`. To count from zero, call `WebMock.reset_executed_requests!`.
925
+
926
+ WebMock may run a `with` block once for several identical requests and multiply the count, so keep such blocks free of side effects. To look at every request, use [`executed_requests`](#inspecting-the-requests-made).
927
+
928
+ ### Inspecting the requests made
929
+
930
+ `WebMock.executed_requests` lists every request made since the last `WebMock.reset!` or `WebMock.reset_executed_requests!`, in the order they were made, including repeats. It lets you check what your code sent with plain Ruby.
931
+
932
+ ```ruby
933
+ stub_request(:post, "www.example.com/orders")
934
+
935
+ Net::HTTP.post(URI("http://www.example.com/orders"), '{"name":"John"}', "Content-Type" => "application/json")
936
+
937
+ request = WebMock.executed_requests.last
938
+ request.method # ===> :post
939
+ request.uri.path # ===> "/orders"
940
+ request.headers["Content-Type"] # ===> "application/json"
941
+ JSON.parse(request.body) # ===> {"name" => "John"}
942
+ ```
943
+
944
+ In RSpec, Minitest and Test::Unit you can call it as `executed_requests`, and it starts empty in every test. For example, to check which requests were made and in what order:
945
+
946
+ ```ruby
947
+ expect(executed_requests.map { |request| request.uri.path }).to eq(["/orders", "/orders/1/confirm"])
948
+ ```
949
+
950
+ A few things to know:
951
+
952
+ * The URI is normalized, with the port added and the query sorted, so compare its parts, such as `uri.host` or `uri.query_values`, rather than `uri.to_s`.
953
+ * The requests are copies, so changing them doesn't change what WebMock recorded.
954
+ * When a Curb, Patron or em-http-request request uploads a file or stream, its body is the uploaded bytes. WebMock reads them without moving the stream, from regular files, tempfiles, `StringIO` and gzip readers over those. Other streams, such as pipes, are listed with the stream's `to_s`.
955
+ * Multipart fields of a Curb PUT are listed with their `name`, `content`, `content_type`, `local_file` and `remote_file`. Files in a Typhoeus body given as an array are listed as `Pathname` objects.
956
+ * With these three clients, blocks given to `stub_request(...).with` and `after_request` callbacks still receive the original file or stream, not the bytes. With other clients, such as Net::HTTP and Excon, the stream is read when the request is made, and blocks and callbacks receive the bytes.
957
+ * An expectation on a stub, such as `assert_requested(stub)`, reuses the decision the stub made when the upload happened, so a stub block that checks the stream gives the same result in the expectation. If the stub never saw the request, because another stub answered first or the stub was declared later, the expectation checks the uploaded bytes, as `a_request(...)` and conditions given to the expectation's `with` always do.
958
+ * Depending on the HTTP client, requests that WebMock blocked because real connections are disabled may be listed too.
959
+
805
960
  ## Clearing stubs and request history
806
961
 
807
- If you want to reset all current stubs and history of requests use `WebMock.reset!`
962
+ If you want to reset all current stubs and history of requests use `WebMock.reset!`. [Global stubs](#global-stubs) stay.
808
963
 
809
964
  ```ruby
810
965
  stub_request(:any, "www.example.com")
@@ -820,7 +975,7 @@ assert_not_requested :get, "www.example.com" # ===> Success
820
975
 
821
976
  ## Clearing request counters
822
977
 
823
- If you want to reset **only** the counters of the executed requests use `WebMock.reset_executed_requests!`
978
+ If you want to reset **only** the counters and the list of executed requests, and keep the stubs, use `WebMock.reset_executed_requests!`
824
979
 
825
980
  ```ruby
826
981
  stub = stub_request(:get, "www.example.com")
@@ -840,6 +995,28 @@ expect(stub).not_to have_been_requested
840
995
  expect(stub2).not_to have_been_requested
841
996
  ```
842
997
 
998
+ ## Global stubs
999
+
1000
+ `WebMock.reset!` removes the stubs declared with `stub_request`, and `webmock/rspec`, `webmock/minitest`, `webmock/test_unit` and `webmock/cucumber` call it after every test or scenario. To answer some requests in every test, for example calls to a metrics service, declare a global stub once when the test suite starts:
1001
+
1002
+ ```ruby
1003
+ WebMock.globally_stub_request do |request|
1004
+ { status: 200, body: "{}" } if request.uri.host == "metrics.example.com"
1005
+ end
1006
+ ```
1007
+
1008
+ WebMock calls the block with the request when it reaches the global stub. The block returns a response hash with the same keys as `to_return`, or `nil` to let other stubs handle the request. `WebMock.reset!` doesn't remove global stubs, and there is no way to remove only one, so declare each of them once, for example in RSpec's `before(:suite)`.
1009
+
1010
+ Global stubs are checked before the stubs declared with `stub_request`. To check a global stub after them instead, so a test can override it with its own stubs, declare it with `:after_local_stubs`:
1011
+
1012
+ ```ruby
1013
+ WebMock.globally_stub_request(:after_local_stubs) do |request|
1014
+ { status: 200, body: "{}" } if request.uri.host == "metrics.example.com"
1015
+ end
1016
+ ```
1017
+
1018
+ Requests answered by a global stub are recorded like any other, so `a_request`, `assert_requested` and `executed_requests` include them.
1019
+
843
1020
  ## Disabling and enabling WebMock or only some http client adapters
844
1021
 
845
1022
  ```ruby
@@ -877,6 +1054,8 @@ stub_request(:get, "www.example.com").to_return(body: "def")
877
1054
  Net::HTTP.get('www.example.com', '/') # ====> "def"
878
1055
  ```
879
1056
 
1057
+ [Global stubs](#global-stubs) are checked before these stubs, or after them when declared with `:after_local_stubs`.
1058
+
880
1059
  ## Matching URIs
881
1060
 
882
1061
  WebMock will match all different representations of the same URI.
@@ -981,6 +1160,16 @@ WebMock.after_request(except: [:patron],
981
1160
  end
982
1161
  ```
983
1162
 
1163
+ #### Removing callbacks
1164
+
1165
+ Callbacks stay registered after `WebMock.reset!`, so a callback added in one test keeps running in later ones. To remove all callbacks, call:
1166
+
1167
+ ```ruby
1168
+ WebMock.reset_callbacks
1169
+ ```
1170
+
1171
+ This also removes callbacks registered by other libraries, such as VCR, so prefer registering your callbacks once, for example in your test helper.
1172
+
984
1173
  ## Bugs and Issues
985
1174
 
986
1175
  Please submit them here [http://github.com/bblimke/webmock/issues](http://github.com/bblimke/webmock/issues)
@@ -1283,6 +1472,36 @@ People who submitted patches and new features or suggested improvements. Many th
1283
1472
  * Erik Berlin
1284
1473
  * Josch Bockler
1285
1474
  * Leslie Hoare
1475
+ * Chris Gunther
1476
+ * hikmetba-bit
1477
+ * Daniel Pepper
1478
+ * Christian Bruckmayer
1479
+ * Chris
1480
+ * Jan Graichen
1481
+ * Olivier Brisse
1482
+ * Henry Blyth
1483
+ * Sébastien S.
1484
+ * Euisan Kim
1485
+ * Alex
1486
+ * Andy Williams
1487
+ * Tim Mertens
1488
+ * Mike Taylor
1489
+ * James Rodovich
1490
+ * Michael Spiz
1491
+ * Tom Brammar
1492
+ * Benoit Tigeot
1493
+ * nightpool
1494
+ * Andrii Furmanets
1495
+ * thoran
1496
+ * Julik Tarkhanov
1497
+ * Bob Aman
1498
+ * AmeenKhan12345
1499
+ * Andrew K. Fader
1500
+ * Yang Bai
1501
+ * Hamza Tarar
1502
+ * John Gallagher
1503
+ * Yegor Bugayenko
1504
+ * Todd Fisher
1286
1505
 
1287
1506
  For a full list of contributors you can visit the
1288
1507
  [contributors](https://github.com/bblimke/webmock/contributors) page.
data/lib/webmock/api.rb CHANGED
@@ -72,6 +72,10 @@ module WebMock
72
72
  WebMock::RequestRegistry.instance.reset!
73
73
  end
74
74
 
75
+ def executed_requests
76
+ WebMock::RequestRegistry.instance.executed_requests
77
+ end
78
+
75
79
  private
76
80
 
77
81
  def convert_uri_method_and_options_to_request_and_options(method, uri, options, &block)
@@ -10,7 +10,7 @@ module WebMock
10
10
  request_signature_snippet.stubbing_instructions,
11
11
  request_signature_snippet.request_stubs,
12
12
  "="*60
13
- ].compact.join("\n\n")
13
+ ].compact.map { |part| Util::MessageString.utf8(part) }.join("\n\n")
14
14
  super(text)
15
15
  end
16
16
 
@@ -66,7 +66,7 @@ if defined?(Async::HTTP)
66
66
  request.authority ||= self.authority
67
67
 
68
68
  request_signature = build_request_signature(request)
69
- WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
69
+ WebMock::RequestRegistry.instance.put(request_signature)
70
70
  webmock_response = WebMock::StubRegistry.instance.response_for_request(request_signature)
71
71
  net_connect_allowed = WebMock.net_connect_allowed?(request_signature.uri)
72
72
  real_request = false
@@ -103,6 +103,23 @@ if defined?(Async::HTTP)
103
103
  @webmock_client.close
104
104
  end
105
105
 
106
+ # Some libraries, such as async-websocket, take a connection from the
107
+ # pool instead of calling #call. WebMock can't see or stub what they
108
+ # send, so hand out the real pool only when WebMock's own settings
109
+ # allow real connections to the host the pool connects to: the
110
+ # endpoint's, whatever authority the requests name, with a ws or wss
111
+ # endpoint checked as http or https. VCR can't record or replay such
112
+ # connections, so it can't allow them.
113
+ def pool
114
+ host = @endpoint.hostname
115
+ host = "[#{host}]" if host.include?(":") && !host.start_with?("[")
116
+ uri = Addressable::URI.new(scheme: @endpoint.secure? ? "https" : "http", host: host, port: @endpoint.port, path: "/")
117
+ unless WebMock.net_connect_allowed_by_settings?(uri)
118
+ raise WebMock::NetConnectNotAllowedError.new(WebMock::RequestSignature.new(:get, uri))
119
+ end
120
+ @network_client.pool
121
+ end
122
+
106
123
  private
107
124
 
108
125
  def build_request_signature(request)
@@ -129,19 +146,32 @@ if defined?(Async::HTTP)
129
146
  end
130
147
 
131
148
  def build_webmock_response(response)
132
- body = response.read
133
- response.body = ::Protocol::HTTP::Body::Buffered.wrap(body)
149
+ # async-http takes the Content-Length out of the headers of a response
150
+ # to a HEAD request and gives it a body that only holds that size.
151
+ # Keep that body, and record the size as the Content-Length sent.
152
+ if head_body?(response.body)
153
+ content_length = response.body.length
154
+ else
155
+ body = response.read
156
+ response.body = ::Protocol::HTTP::Body::Buffered.wrap(body)
157
+ end
134
158
 
135
159
  webmock_response = WebMock::Response.new
136
160
  webmock_response.status = [
137
161
  response.status,
138
162
  WebMock::HttpLibAdapters::AsyncHttpClientAdapter.status_descriptions[response.status]
139
163
  ]
140
- webmock_response.headers = build_webmock_response_headers(response)
164
+ headers = build_webmock_response_headers(response)
165
+ headers['content-length'] = [content_length.to_s] if content_length
166
+ webmock_response.headers = headers
141
167
  webmock_response.body = body
142
168
  webmock_response
143
169
  end
144
170
 
171
+ def head_body?(body)
172
+ defined?(::Protocol::HTTP::Body::Head) && body.is_a?(::Protocol::HTTP::Body::Head)
173
+ end
174
+
145
175
  def build_webmock_response_headers(response)
146
176
  response.headers.each.each_with_object({}) do |(k, v), o|
147
177
  o[k] ||= []
@@ -215,7 +245,8 @@ if defined?(Async::HTTP)
215
245
  def call(request)
216
246
  request.read
217
247
  webmock_response = get_webmock_response(request)
218
- build_response(webmock_response)
248
+ body = request.head? ? head_body(webmock_response) : webmock_response.body
249
+ build_response(webmock_response, body)
219
250
  end
220
251
 
221
252
  def add_webmock_response(request, webmock_response)
@@ -235,7 +266,7 @@ if defined?(Async::HTTP)
235
266
  @webmock_responses ||= {}
236
267
  end
237
268
 
238
- def build_response(webmock_response)
269
+ def build_response(webmock_response, body)
239
270
  headers = (webmock_response.headers || {}).each_with_object([]) do |(k, value), o|
240
271
  next if FRAMING_HEADERS.include?(k.downcase)
241
272
 
@@ -247,9 +278,22 @@ if defined?(Async::HTTP)
247
278
  ::Protocol::HTTP::Response[
248
279
  webmock_response.status[0],
249
280
  headers,
250
- webmock_response.body
281
+ body
251
282
  ]
252
283
  end
284
+
285
+ # async-http answers a HEAD request with the size of the body as the
286
+ # Content-Length, and leaves the body out. A stub's own Content-Length
287
+ # is the size of the body it stands for, so it takes precedence.
288
+ def head_body(webmock_response)
289
+ content_length = Array(webmock_response.headers&.[]('Content-Length')).first.to_s
290
+
291
+ if content_length.match?(/\A\d+\z/) && defined?(::Protocol::HTTP::Body::Head)
292
+ ::Protocol::HTTP::Body::Head.new(content_length.to_i)
293
+ else
294
+ webmock_response.body
295
+ end
296
+ end
253
297
  end
254
298
  end
255
299
  end