webmock 4.0.0 → 4.1.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4c4c96d7db983ae7dfbdf251c8d0a146a64761b0716cd8b1f2cde3ba5d523146
4
- data.tar.gz: 685b2118f07a46a1bcd2f02cb96d24d035087cae2504f45a7927b6673d27ccfd
3
+ metadata.gz: 4919cd5204cf89c2d30230526f0dd658326182c16ea82174c88bfb0adce3748e
4
+ data.tar.gz: aaddb1abbddaf3f9c6fff1ee15a30c4eddf0bd4eafe6a370b1dc2ec7509b4339
5
5
  SHA512:
6
- metadata.gz: cb1a375f97aab7f5d298dedbcb12561537b82e9484d0bf4f64338e768142cbeb6f90f21b29ac6323a283a788294c126702ba6e4e5d20a4973540ab1a8a07a808
7
- data.tar.gz: 2e42da579d5100fbcb2633838726795cccf41e1459d96d4cba4e6da566d876c0583cfa364e579b54bf2858ef363b8871c1f60bdba7493863760c716b76f84040
6
+ metadata.gz: cd641f8e94aac2eb9fb0e5305a1f375c871e78138c33f711a508bd07016571adb4b112e4d05c193524d0081d459273aca4153a47b1396ff9b53a6b7197d43b0d
7
+ data.tar.gz: 94816f0976ab5d05b283b081b77734c566ea5b4f42ac221893493a0012a0bcafcfa0c9493220f319ff305079df352a9bced0efd9d3347c5d34e73d2b26c690eb
data/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ # 4.1.0
4
+
5
+ * Match request headers with `hash_including` and `hash_excluding` (#942)
6
+
7
+ `with(headers: hash_including("Authorization"))` now matches any request with an Authorization header. Use `hash_excluding("Authorization")` to match requests without that header. Both WebMock's and RSpec's matchers work here. Previously, using either matcher raised `NoMethodError`.
8
+
9
+ Header names follow the same rules as in a plain header hash. Ordinary values such as strings and numbers compare as text. You can also match a value with a regexp, for example `hash_including("Authorization" => /^Bearer /)`, or with another matcher that implements `===`.
10
+
11
+ For repeated headers, supply an array of strings. Combining a header matcher with `basic_auth` raises `ArgumentError`. To match basic authentication, include the expected Authorization header value in `hash_including`.
12
+
13
+ * Match raw multipart request bodies (#623)
14
+
15
+ You can now match an uploaded filename with `with(body: /filename="report\.pdf"/)`, even when the file contains binary data. A regexp can match part of the raw multipart body. A string matches the entire body byte for byte. A lambda receives the raw body.
16
+
17
+ WebMock still doesn't parse multipart form fields, so using a hash, an array, `hash_including` or `hash_excluding` as a multipart body pattern raises `ArgumentError`.
18
+
19
+ Net::HTTP forms sent with `set_form` are recorded without a body, so any body pattern raises `ArgumentError` for those requests. Typhoeus and Curb pass WebMock the form fields, so patterns that expect the raw multipart body won't match.
20
+
3
21
  # 4.0.0
4
22
 
5
23
  4.0 requires Ruby 3.0 or later. Its other changes fix behaviour that was wrong in 3.x, so a spec fails only if it passed because of one of them. A typical test suite needs no changes: a stub such as `stub_request(:get, url).to_return(body: "ok")` works as before, a request that sends `{id: 1}.to_json` still matches `with(body: {id: 1})`, and VCR records and replays as before.
data/README.md CHANGED
@@ -275,6 +275,18 @@ req.add_field('Accept', 'image/jpeg')
275
275
  Net::HTTP.start("www.example.com") {|http| http.request(req) } # ===> Success
276
276
  ```
277
277
 
278
+ ### Matching headers with hash_including or hash_excluding
279
+
280
+ A header given without a value matches any value.
281
+
282
+ ```ruby
283
+ stub_request(:get, "www.example.com").
284
+ with(headers: hash_including("Authorization"))
285
+
286
+ stub_request(:get, "www.example.com").
287
+ with(headers: hash_excluding("Authorization")) # requests without an Authorization header
288
+ ```
289
+
278
290
  ### Matching requests against provided block
279
291
 
280
292
  ```ruby
@@ -25,6 +25,11 @@ module WebMock
25
25
  rspec_argument_matcher_name(matcher) =~ /R?Spec::Mocks::ArgumentMatchers::Array(In|Ex)cludingMatcher/
26
26
  end
27
27
 
28
+ # WebMock's anything or RSpec's.
29
+ def any_arg_matcher?(matcher)
30
+ WebMock::Matchers::AnyArgMatcher === matcher || rSpecAnyArgMatcher?(matcher)
31
+ end
32
+
28
33
  # The class name of a possible RSpec matcher, or nil for values that
29
34
  # can't be one, which are most values in a pattern. A custom matcher can
30
35
  # be a BasicObject, which has no #class.
@@ -114,8 +119,12 @@ module WebMock
114
119
  def set_basic_auth_as_headers!(options)
115
120
  if basic_auth = options.delete('basic_auth')
116
121
  validate_basic_auth!(basic_auth)
117
- options['headers'] ||= {}
118
- options['headers']['Authorization'] = WebMock::Util::Headers.basic_auth_header(basic_auth[0],basic_auth[1])
122
+ headers = (options['headers'] ||= {})
123
+ if WebMock::Matchers::HashArgumentMatcher === headers || RSpecMatcherDetector.rSpecHashMatcher?(headers)
124
+ raise ArgumentError, "basic_auth can't be combined with headers given as hash_including or " \
125
+ "hash_excluding. With hash_including, put the Authorization header in it instead."
126
+ end
127
+ headers['Authorization'] = WebMock::Util::Headers.basic_auth_header(basic_auth[0],basic_auth[1])
119
128
  end
120
129
  end
121
130
 
@@ -431,10 +440,6 @@ module WebMock
431
440
  end
432
441
 
433
442
  def matches?(body, content_type = "", serialized_body = nil)
434
- # Checked on the raw value, so body patterns used with mixed case
435
- # multipart content types keep working as in earlier versions.
436
- assert_non_multipart_body(content_type)
437
-
438
443
  if serialized_body
439
444
  case @pattern
440
445
  when String, Regexp, Hash, Array, WebMock::Matchers::HashArgumentMatcher, nil
@@ -442,6 +447,12 @@ module WebMock
442
447
  end
443
448
  end
444
449
 
450
+ # WebMock can't parse a multipart body yet, or match one recorded
451
+ # without its content, as Net::HTTP's set_form is. Other patterns get
452
+ # the raw body. The check is on the raw content type, so hash patterns
453
+ # still match mixed case multipart content types, as before.
454
+ assert_non_multipart_body(content_type) if parses_body? || NilClass === body
455
+
445
456
  if (@pattern).is_a?(Hash)
446
457
  return true if @pattern.empty?
447
458
  matching_body_hashes?(body_as_hash(body, content_type), @pattern, content_type)
@@ -452,7 +463,8 @@ module WebMock
452
463
  else
453
464
  empty_string?(@pattern) && empty_string?(body) ||
454
465
  @pattern == body ||
455
- @pattern === body
466
+ multipart_bytes_equal?(body, content_type) ||
467
+ pattern_matches?(body)
456
468
  end
457
469
  end
458
470
 
@@ -462,6 +474,34 @@ module WebMock
462
474
 
463
475
  private
464
476
 
477
+ # A multipart body can hold a binary file, and its encoding can differ
478
+ # from the pattern's, so a string is compared with it as bytes. Multipart
479
+ # bodies didn't match any pattern before, so other bodies are compared
480
+ # as they were.
481
+ def multipart_bytes_equal?(body, content_type)
482
+ String === @pattern && String === body && multipart?(content_type) && @pattern.b == body.b
483
+ end
484
+
485
+ # Ruby can't match a regexp against a body that isn't valid in its
486
+ # encoding, or a regexp with non ASCII text against binary bytes, as in
487
+ # a multipart upload of a binary file. Such a body is matched as bytes
488
+ # by a regexp for bytes, and otherwise as UTF-8 text with the invalid
489
+ # bytes replaced, which keeps the text around them, such as a filename.
490
+ def pattern_matches?(body)
491
+ @pattern === body
492
+ rescue ArgumentError, Encoding::CompatibilityError
493
+ raise unless Regexp === @pattern && String === body &&
494
+ (!body.valid_encoding? || body.encoding == Encoding::BINARY)
495
+
496
+ text = body.b
497
+ text = text.force_encoding(Encoding::UTF_8).scrub unless @pattern.encoding == Encoding::BINARY
498
+ begin
499
+ @pattern === text
500
+ rescue Encoding::CompatibilityError
501
+ false
502
+ end
503
+ end
504
+
465
505
  def body_as_hash(body, content_type)
466
506
  return if body.nil?
467
507
 
@@ -480,8 +520,14 @@ module WebMock
480
520
  nil
481
521
  end
482
522
 
523
+ # Checked on the raw value, as in earlier versions, so mixed case
524
+ # content types aren't multipart here.
525
+ def multipart?(content_type)
526
+ content_type =~ %r{^multipart/form-data}
527
+ end
528
+
483
529
  def assert_non_multipart_body(content_type)
484
- if content_type =~ %r{^multipart/form-data}
530
+ if multipart?(content_type)
485
531
  raise ArgumentError.new("WebMock does not support matching body for multipart/form-data requests yet :(")
486
532
  end
487
533
  end
@@ -549,11 +595,23 @@ module WebMock
549
595
  end
550
596
 
551
597
  class HeadersPattern
598
+ include RSpecMatcherDetector
599
+
600
+ PLAIN_VALUES = [String, Symbol, Numeric, NilClass, TrueClass, FalseClass].freeze
601
+ private_constant :PLAIN_VALUES
602
+
552
603
  def initialize(pattern)
553
- @pattern = WebMock::Util::Headers.normalize_headers(pattern) || {}
604
+ matcher = webmock_hash_matcher(pattern)
605
+ @pattern = if WebMock::Matchers::HashArgumentMatcher === matcher
606
+ matcher.class.new(normalize_matcher_headers(matcher))
607
+ else
608
+ WebMock::Util::Headers.normalize_headers(pattern) || {}
609
+ end
554
610
  end
555
611
 
556
612
  def matches?(headers)
613
+ return @pattern == (headers || {}) if hash_matcher?
614
+
557
615
  if empty_headers?(@pattern)
558
616
  empty_headers?(headers)
559
617
  else
@@ -566,15 +624,87 @@ module WebMock
566
624
  end
567
625
 
568
626
  def to_s
627
+ return matcher_to_s if hash_matcher?
628
+
569
629
  WebMock::Util::Headers.sorted_headers_string(@pattern)
570
630
  end
571
631
 
572
632
  def pp_to_s
633
+ return matcher_to_s if hash_matcher?
634
+
573
635
  WebMock::Util::Headers.pp_headers_string(@pattern)
574
636
  end
575
637
 
576
638
  private
577
639
 
640
+ def hash_matcher?
641
+ WebMock::Matchers::HashArgumentMatcher === @pattern
642
+ end
643
+
644
+ def expected_headers(matcher)
645
+ matcher.instance_variable_get(:@expected)
646
+ end
647
+
648
+ # The expected headers of hash_including or hash_excluding, with names
649
+ # normalized as for a plain hash, so they compare with the request's
650
+ # headers. Values compared as text are normalized as in a plain hash.
651
+ def normalize_matcher_headers(matcher)
652
+ expected_headers(matcher).each_with_object({}) do |(name, value), headers|
653
+ if Array === value && !value.all? { |element| text_value?(element) }
654
+ raise ArgumentError, "Headers given as hash_including or hash_excluding can't have " \
655
+ "matchers in an array of values, as given for #{name}"
656
+ elsif Array === value || text_value?(value)
657
+ headers.update(WebMock::Util::Headers.normalize_headers(name => value))
658
+ else
659
+ headers[WebMock::Util::Headers.normalize_name(name)] = value
660
+ end
661
+ end
662
+ end
663
+
664
+ # Strings, symbols and numbers are compared as text, as in a plain hash,
665
+ # and so is any value that doesn't define its own ===, such as a URI or
666
+ # a Time. A regexp, a class, a range, a lambda or a matcher, which
667
+ # define ===, are compared with ===. A BasicObject can only be a custom
668
+ # matcher.
669
+ def text_value?(value)
670
+ return false unless ::Kernel === value
671
+ return true if PLAIN_VALUES.any? { |type| type === value }
672
+ return false if any_arg_matcher?(value)
673
+
674
+ ::Kernel.instance_method(:method).bind_call(value, :===).owner == ::Kernel
675
+ end
676
+
677
+ # A header given without a value is listed by name, as hash_including
678
+ # takes it. A matcher is shown by its description, or by inspect only
679
+ # for types whose inspect shows no state, since a matcher's inspect can
680
+ # include a value it saw in an earlier request, such as an
681
+ # Authorization header.
682
+ def matcher_to_s
683
+ name = WebMock::Matchers::HashIncludingMatcher === @pattern ? "hash_including" : "hash_excluding"
684
+ without_value, with_value = expected_headers(@pattern).partition { |_header, value| any_arg_matcher?(value) }
685
+ arguments = without_value.map { |header, _value| header.inspect }
686
+ if with_value.any? || without_value.empty?
687
+ arguments << "{#{with_value.map { |header, value| "#{header.inspect} => #{value_to_s(value)}" }.join(", ")}}"
688
+ end
689
+ "#{name}(#{arguments.join(", ")})"
690
+ end
691
+
692
+ def value_to_s(value)
693
+ return "a custom matcher" unless ::Kernel === value
694
+
695
+ described = begin
696
+ value.description if value.respond_to?(:description)
697
+ rescue StandardError, NotImplementedError
698
+ nil
699
+ end
700
+ return described if String === described
701
+
702
+ case value
703
+ when String, Array, Regexp, Module, Range, Proc then value.inspect
704
+ else "#<#{value.class.name || "custom matcher"}>"
705
+ end
706
+ end
707
+
578
708
  def empty_headers?(headers)
579
709
  headers.nil? || headers == {}
580
710
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module WebMock
4
- VERSION = '4.0.0' unless defined?(::WebMock::VERSION)
4
+ VERSION = '4.1.0' unless defined?(::WebMock::VERSION)
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: webmock
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.0.0
4
+ version: 4.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Bartosz Blimke
@@ -363,9 +363,9 @@ licenses:
363
363
  - MIT
364
364
  metadata:
365
365
  bug_tracker_uri: https://github.com/bblimke/webmock/issues
366
- changelog_uri: https://github.com/bblimke/webmock/blob/v4.0.0/CHANGELOG.md
367
- documentation_uri: https://www.rubydoc.info/gems/webmock/4.0.0
368
- source_code_uri: https://github.com/bblimke/webmock/tree/v4.0.0
366
+ changelog_uri: https://github.com/bblimke/webmock/blob/v4.1.0/CHANGELOG.md
367
+ documentation_uri: https://www.rubydoc.info/gems/webmock/4.1.0
368
+ source_code_uri: https://github.com/bblimke/webmock/tree/v4.1.0
369
369
  wiki_uri: https://github.com/bblimke/webmock/wiki
370
370
  rdoc_options: []
371
371
  require_paths: