Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ jobs:
with:
ruby-version: ${{ matrix.ruby_version }}
bundler-cache: true
# TEMP: load libpact_ffi 0.5.13-or.1 (YOU54F/pact-reference fork prerelease),
# fetched by the YOU54F/pact-ruby-ffi PR branch's download script, through
# pact-ffi's DEBUG_TARGET override (revert before merge)
- name: Use pact_ffi 0.5.13-or.1 from YOU54F/pact-ruby-ffi
shell: bash
run: |
git clone --depth 1 --branch feat/or-matcher https://github.com/YOU54F/pact-ruby-ffi.git ../pact-ruby-ffi
cd ../pact-ruby-ffi
ruby script/download_libs.rb
echo "DEBUG_TARGET=$(ruby -r ./lib/pact/detect_os -e 'print File.expand_path(DetectOS.get_bin_path)')" >> "$GITHUB_ENV"
- name: Check loaded pact_ffi version
shell: bash
run: bundle exec ruby -e 'require "pact/ffi"; v = PactFfi.version; puts "DEBUG_TARGET=#{ENV["DEBUG_TARGET"]} pact_ffi=#{v}"; abort "expected pact_ffi 0.5.13-or.1" unless v == "0.5.13-or.1"'
- uses: pact-foundation/pact-cli@main
- run: pact plugin install --yes https://github.com/mefellows/pact-matt-plugin/releases/tag/v0.1.1
- name: Test Pact-Ruby Specs
Expand Down Expand Up @@ -52,6 +65,19 @@ jobs:
with:
ruby-version: ${{ matrix.ruby_version }}
bundler-cache: true
# TEMP: load libpact_ffi 0.5.13-or.1 (YOU54F/pact-reference fork prerelease),
# fetched by the YOU54F/pact-ruby-ffi PR branch's download script, through
# pact-ffi's DEBUG_TARGET override (revert before merge)
- name: Use pact_ffi 0.5.13-or.1 from YOU54F/pact-ruby-ffi
shell: bash
run: |
git clone --depth 1 --branch feat/or-matcher https://github.com/YOU54F/pact-ruby-ffi.git ../pact-ruby-ffi
cd ../pact-ruby-ffi
ruby script/download_libs.rb
echo "DEBUG_TARGET=$(ruby -r ./lib/pact/detect_os -e 'print File.expand_path(DetectOS.get_bin_path)')" >> "$GITHUB_ENV"
- name: Check loaded pact_ffi version
shell: bash
run: bundle exec ruby -e 'require "pact/ffi"; v = PactFfi.version; puts "DEBUG_TARGET=#{ENV["DEBUG_TARGET"]} pact_ffi=#{v}"; abort "expected pact_ffi 0.5.13-or.1" unless v == "0.5.13-or.1"'
- uses: pact-foundation/pact-cli@main
- run: pact plugin install --yes https://github.com/mefellows/pact-matt-plugin/releases/tag/v0.1.1
- run: "bundle exec appraisal install"
Expand Down
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,53 @@ For details of the implementation, see [matchers.rb](../lib/pact/matchers.rb)

See the different uses of the matchers in [matchers_spec.rb](../spec/pact/matchers_spec.rb)

#### Combining matchers (OR / AND)

> Requires a pact_ffi version with `pact:matcher:combine` support ([pact-foundation/pact-reference#601](https://github.com/pact-foundation/pact-reference/pull/601)): pact_ffi TODO(version).

- `match_or(*matchers, sample:)` - the value must match at least one of the matchers
- `match_and(*matchers, sample:)` - the value must match all of the matchers
- `match_null` - match a JSON `null` (mostly useful inside `match_or`)
- `*_or_nil` helpers - shorthand for `match_or(<matcher>, match_null, sample: sample)`:
`match_any_string_or_nil`, `match_any_integer_or_nil`, `match_any_decimal_or_nil`, `match_any_number_or_nil`,
`match_any_boolean_or_nil`, `match_any_uuid_or_nil`, `match_regex_or_nil`, `match_datetime_or_nil`,
`match_iso8601_or_nil`, `match_date_or_nil`, `match_time_or_nil`

Combined matchers can be used in request/response bodies, headers and query parameters:

```ruby
.with_request(
method: :post,
path: '/pets',
query: { limit: match_or(match_regex(/^\d+$/, '10'), match_regex(/^all$/, 'all'), sample: '10') },
headers: { 'X-Request-Id' => match_or(match_regex(/^\d+$/, '123'), match_uuid, sample: '123') },
body: {
name: match_any_string_or_nil('Rex'),
# null, or an object whose `age` is an integer
owner: match_or(
match_type_of({}), match_null,
sample: { name: 'Bob', age: match_any_integer(30) }
)
}
)
```

Each matcher is sent to pact_ffi without its own example; `sample:` is the one example value used for the path.
Matchers nested inside an object `sample` (like `age` above) still apply to its children whenever the value is not
`null`. Put every alternative in the one `match_or`/`match_and` call; combined matchers cannot be nested inside each
other, and are not supported in plugin (`matching(...)`) contents.

The Pact file gets a rule list combined with `OR`/`AND`, which Pact specification V3 and V4 support:

```json
"$.owner": { "combine": "OR", "matchers": [{ "match": "type" }, { "match": "null" }] }
```

**Caveat:** only the `sample` is exercised in the consumer test. In a response, the mock server always returns the
sample, so your consumer code is never run against the other alternatives (e.g. `null`); the provider verification
checks that the real response matches one of them. Add a separate interaction (e.g. with a `null` sample) if your
consumer must be tested against each case.

### Generators

Generators are helper methods that allow you to specify dynamic values in your contract tests. These values are generated at runtime, making your contracts more flexible and robust. Below are the available generator methods:
Expand Down
62 changes: 16 additions & 46 deletions lib/pact/consumer/http_interaction_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -83,24 +83,7 @@ def with_request(method: nil, path: nil, query: {}, headers: {}, body: nil)
end

if body
contents = InteractionContents.basic(body)

PactFfi.with_body(
pact_interaction,
interaction_part,
"application/json",
format_value(contents.value)
)

if contents.matching_rules.any?
PactFfi.with_matching_rules(
pact_interaction,
interaction_part,
JSON.dump(
"body" => contents.matching_rules
)
)
end
PactFfi.with_body(pact_interaction, interaction_part, "application/json", format_value(InteractionContents.basic(body).value))
end

self
Expand All @@ -123,24 +106,7 @@ def will_respond_with(status: nil, headers: {}, body: nil)
end

if body
contents = InteractionContents.basic(body)

PactFfi.with_body(
pact_interaction,
interaction_part,
"application/json",
format_value(contents.value)
)

if contents.matching_rules.any?
PactFfi.with_matching_rules(
pact_interaction,
interaction_part,
JSON.dump(
"body" => contents.matching_rules
)
)
end
PactFfi.with_body(pact_interaction, interaction_part, "application/json", format_value(InteractionContents.basic(body).value))
end

self
Expand All @@ -160,17 +126,21 @@ def execute(&block)
yield(mock_server)

ensure
if mock_server.matched?
mock_server.write_pacts!(pact_config.pact_dir)
else
msg = mismatches_error_msg(mock_server)
raise InteractionMismatchesError.new(msg)
begin
if mock_server&.matched?
mock_server.write_pacts!(pact_config.pact_dir)
elsif mock_server
msg = mismatches_error_msg(mock_server)
raise InteractionMismatchesError.new(msg)
end
ensure
# Always release the mock server port, even when there are mismatches
@used = true
mock_server&.cleanup
# Reset the pact handle to allow for a new interaction to be built
# without previous interactions being included
@pact_config.reset_pact
end
@used = true
mock_server&.cleanup
# Reset the pact handle to allow for a new interaction to be built
# without previous interactions being included
@pact_config.reset_pact
end

private
Expand Down
42 changes: 20 additions & 22 deletions lib/pact/consumer/interaction_contents.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class InteractionContents < Hash
BASIC_FORMAT = :basic
PLUGIN_FORMAT = :plugin

attr_reader :format, :matching_rules
attr_reader :format

def self.basic(contents_hash)
new(contents_hash, BASIC_FORMAT)
Expand All @@ -17,15 +17,14 @@ def self.plugin(contents_hash)
end

def initialize(contents_hash, format)
@matching_rules = {}
serialized = serialize(contents_hash.deep_dup, format, '$')

serialized = init_hash(contents_hash, format)
# A scalar body (plain string, integer, etc.) serializes to a non-Hash
# value that cannot be merged pair by pair; expose it via #value instead.
if serialized.is_a?(Hash)
serialized.each_pair { |k, v| self[k] = v }
else
@value = serialized
end

@format = format
end

Expand All @@ -35,29 +34,28 @@ def value

private

def serialize(value, format, path)
if value.is_a?(Pact::Matchers::Combined)
@matching_rules[path] = value.as_matching_rule
return value.template
def serialize(hash, format)
# serialize recursively
if hash.is_a?(Pact::Matchers::Base) || hash.is_a?(Pact::Generators::Base)
return hash.as_basic if format == :basic
return hash.as_plugin if format == :plugin
end

if value.is_a?(Pact::Matchers::Base) ||
value.is_a?(Pact::Generators::Base)
return value.as_basic if format == :basic
return value.as_plugin if format == :plugin
end
return hash.map { |value| serialize(value, format) } if hash.is_a?(Array)

if value.is_a?(Array)
return value.each_with_index.map do |item, index|
serialize(item, format, "#{path}[#{index}]")
end
# A value that is not a collection or a matcher/generator has nothing to
# recurse into, so return it unchanged (string, integer, boolean, nil, ...).
return hash unless hash.is_a?(Hash)

hash.each_pair do |key, value|
hash[key] = serialize(value, format)
end

return value unless value.is_a?(Hash)
hash
end

value.each_with_object({}) do |(key, child), result|
result[key] = serialize(child, format, "#{path}.#{key}")
end
def init_hash(hash, format)
serialize(hash.deep_dup, format)
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion lib/pact/matchers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def match_null
def match_or(*matchers, sample:)
Combined.new(matchers, combine: :or, template: sample)
end

def match_and(*matchers, sample:)
Combined.new(matchers, combine: :and, template: sample)
end
Expand Down
6 changes: 0 additions & 6 deletions lib/pact/matchers/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,6 @@ def as_plugin
"matching(#{@kind}, #{value})"
end

def as_matching_rule
{
"match" => serialize!(@kind.deep_dup, :basic)
}.merge(serialize!(@opts.deep_dup, :basic))
end

private

def serialize!(data, format)
Expand Down
46 changes: 33 additions & 13 deletions lib/pact/matchers/combined.rb
Original file line number Diff line number Diff line change
@@ -1,32 +1,52 @@
# frozen_string_literal: true

module Pact
module Matchers
class Combined
# Applies several matchers to the same path, combined with AND or OR logic.
#
# Serialises to pact_ffi integration JSON, with every matcher (without its
# example value) in the `pact:matcher:type` array and the sample as the
# single `value`:
#
# {
# "pact:matcher:type": [{"pact:matcher:type": "type"}, {"pact:matcher:type": "null"}],
# "pact:matcher:combine": "OR",
# "value": "Fred"
# }
#
# Requires a pact_ffi version that supports `pact:matcher:combine`
# (pact-foundation/pact-reference#601).
class Combined < Base
VALID_COMBINATIONS = %i[and or].freeze

attr_reader :matchers, :combine, :template
attr_reader :matchers, :combine

def initialize(matchers, combine:, template:)
raise ArgumentError, "At least two matchers are required" if matchers.size < 2
raise ArgumentError, 'At least two matchers are required' if matchers.size < 2

unless matchers.all?(Pact::Matchers::Base)
raise ArgumentError, "All values must be Pact matchers"
unless matchers.all? { |m| m.is_a?(Pact::Matchers::Base) && !m.is_a?(Combined) }
raise ArgumentError, 'All values must be Pact matchers'
end

unless VALID_COMBINATIONS.include?(combine)
raise ArgumentError, "combine must be :and or :or"
end
raise ArgumentError, 'combine must be :and or :or' unless VALID_COMBINATIONS.include?(combine)

@matchers = matchers
@combine = combine
@template = template
super(spec_version: Pact::Matchers::PACT_SPEC_V3, kind: matchers.map(&:kind), template: template)
end

def as_matching_rule
def as_basic
{
"combine" => combine.to_s.upcase,
"matchers" => matchers.map(&:as_matching_rule)
'pact:matcher:type' => matchers.map { |m| m.as_basic.except('value') },
'pact:matcher:combine' => combine.to_s.upcase,
'value' => serialize!(template.deep_dup, :basic)
}
end

def as_plugin
raise MatcherInitializationError,
"#{self.class}: combined (match_#{combine}) matchers are not supported in plugin contents"
end
end
end
end
end
22 changes: 22 additions & 0 deletions spec/lib/consumer/interaction_contents_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,26 @@
expect(described_class.basic({ some_array: [42] }).to_json).to eq('{"some_array":[42]}')
end
end

context 'with combined (OR) matchers' do
it 'serializes them inline as integration JSON at any depth' do
contents = { pet: { name: match_any_string_or_nil('Rex'), tags: [match_any_integer_or_nil(1)] } }
or_rule = lambda do |rule, value|
{ 'pact:matcher:type' => [rule, { 'pact:matcher:type' => 'null' }], 'pact:matcher:combine' => 'OR',
'value' => value }
end

expect(JSON.parse(described_class.basic(contents).to_json)).to eq(
'pet' => {
'name' => or_rule.call({ 'pact:matcher:type' => 'regex', 'regex' => '(?-mix:.*)' }, 'Rex'),
'tags' => [or_rule.call({ 'pact:matcher:type' => 'integer' }, 1)]
}
)
end

it 'serializes a top-level combined matcher (e.g. a header value)' do
expect(described_class.basic({ 'X-Id' => match_or(match_regex(/\d+/, '1'), match_null, sample: '1') })['X-Id'])
.to include('pact:matcher:combine' => 'OR', 'value' => '1')
end
end
end
Loading