diff --git a/.github/workflows/compat-core.yml b/.github/workflows/compat-core.yml new file mode 100644 index 00000000..4af60825 --- /dev/null +++ b/.github/workflows/compat-core.yml @@ -0,0 +1,44 @@ +name: Compatibility suite (core) + +# Runs the core V1-V4 pact-compatibility-suite features (everything except +# V4 plugins) through compatibility-suite/run-core.sh. +on: + push: + branches: + - master + pull_request: + workflow_dispatch: + inputs: + suite-ref: + description: Ref of pact-foundation/pact-compatibility-suite to run + default: main + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + PACT_DO_NOT_TRACK: 'true' + +jobs: + core: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - name: Checkout compatibility suite + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + repository: pact-foundation/pact-compatibility-suite + ref: ${{ inputs.suite-ref || 'main' }} + path: pact-compatibility-suite + - uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.4" + bundler-cache: true + - name: Run core features + run: compatibility-suite/run-core.sh + env: + PACT_COMPAT_SUITE: ${{ github.workspace }}/pact-compatibility-suite diff --git a/Gemfile b/Gemfile index a09c2ed7..1edf661f 100644 --- a/Gemfile +++ b/Gemfile @@ -26,3 +26,7 @@ if RUBY_VERSION >= '3.4' gem 'csv' gem 'mutex_m' end + +group :compatibility_suite do + gem 'cucumber', '~> 9.2' +end diff --git a/compatibility-suite/README.md b/compatibility-suite/README.md new file mode 100644 index 00000000..9c766523 --- /dev/null +++ b/compatibility-suite/README.md @@ -0,0 +1,31 @@ +# Pact compatibility suite (core) + +A Cucumber runner for the [pact-compatibility-suite](https://github.com/pact-foundation/pact-compatibility-suite) +core features: everything in V1–V4 except `V4/plugins`. The steps drive `libpact_ffi` (from the `pact-ffi` gem +pact-ruby already depends on) through the calls a client library makes, mirroring the pact-reference FFI runner. + +```bash +git clone https://github.com/pact-foundation/pact-compatibility-suite ../pact-compatibility-suite +bundle install +PACT_COMPAT_SUITE=$PWD/../pact-compatibility-suite compatibility-suite/run-core.sh +``` + +Extra arguments go to cucumber (for example `--name 'not empty matcher'`). `CUCUMBER_FORMAT` picks the formatter. + +## Features + +| Area | Features | +|---|---| +| HTTP consumer | V1, V2, V3, V4 `http_consumer` | +| HTTP provider | V1, V2, V3, V4 `http_provider` | +| Messages | V3, V4 `message_consumer` and `message_provider`, V4 `synchronous_message_consumer`, V4 `v4` | +| Generators | V3 `generators`, V3 `http_generators`, V4 `generators` | +| Matching | V3 `http_matching`, V3 and V4 `matching_rules` | + +## Not run + +- Scenarios the suite tags `@wip` (currently the V3 message provider Kafka schema registry scenario). +- `KNOWN_FAILURES` in `core/support/env.rb`: scenarios that fail because of a pact_ffi limitation. They are + skipped with the reason so they show in every run. Remove an entry once pact_ffi is fixed. + - *Supports a not empty matcher with binary data (negative case)*: the pact_ffi mock server reads a 0-byte + request body as no body, so the `notEmpty` rule never sees it. diff --git a/compatibility-suite/core/step_definitions/generators_steps.rb b/compatibility-suite/core/step_definitions/generators_steps.rb new file mode 100644 index 00000000..31f5408e --- /dev/null +++ b/compatibility-suite/core/step_definitions/generators_steps.rb @@ -0,0 +1,247 @@ +# frozen_string_literal: true + +# Steps for V3 generators.feature, V3 http_generators.feature and V4 generators.feature. +# +# pact_ffi has no call that generates a request or response, so generated values are observed the +# way a client sees them: a request by verifying a pact against a provider that records what it +# receives (with a state change server for a provider state context), and a response by sending a +# request to a mock server. The mock server URL generator needs a consumer-mode mock server context +# that an HTTP client cannot supply, so that scenario runs a V4 message's body generators through +# pactffi_generator_generate_string. + +GeneratedPart = Struct.new(:status, :path, :headers, :body) do + def header(name) = headers.find { |k, _| k.casecmp?(name) }&.last +end + +GEN_VALUE_TYPES = { + 'integer' => /\A-?\d+\z/, + 'decimal number' => /\A-?\d+\.\d+\z/, + 'hexadecimal number' => /\A[a-fA-F0-9]+\z/, + 'string from the regex' => /\A\d{1,8}\z/, + 'date' => /\A\d{4}-\d{2}-\d{2}\z/, + 'time' => /\A\d{2}:\d{2}:\d{2}\z/, + 'date-time' => /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?/, + 'boolean' => /\A(true|false)\z/ +}.merge( + ['UUID', 'simple UUID', 'lower-case-hyphenated UUID', 'upper-case-hyphenated UUID', 'URN UUID'].to_h do |k| + [k, /\A(urn:uuid:)?\h{8}-?\h{4}-?\h{4}-?\h{4}-?\h{12}\z/] + end +).freeze + +def gen_assert_value_type(kind, v) + if ['random string', 'string from the regex'].include?(kind) + raise "expected a string, got #{v.to_json}" unless v.is_a?(String) + return if kind == 'random string' + end + pattern = GEN_VALUE_TYPES.fetch(kind) { raise "unknown value type #{kind}" } + raise "expected a(n) #{kind}, got #{v.to_json}" unless json_to_string(v).match?(pattern) +end + +def gen_spec = @version == 'v4' ? 5 : 4 + +# A `| body | generators |` table: the part, and the generators as JSON text. +def gen_configure(table) + rows = table.raw + part = CompatModel::Part.new([], nil, nil) + generators = nil + rows[0].zip(rows[1]).each do |field, value| + case field + when 'body' then setup_body(value, part) + when 'generators' + generators = value.start_with?('JSON:') ? value.delete_prefix('JSON:').strip : File.read(fixture_path(value)) + end + end + [part, generators] +end + +def gen_write_pact(pact) + FileUtils.mkdir_p(@pact_dir) + rc = CompatFfi::Raw.pact_handle_write_file(pact, @pact_dir, true) + CompatFfi::Raw.free_pact_handle(pact) + raise "pact_handle_write_file failed with #{rc}" unless rc.zero? +end + +def gen_prepare_request(state) + raw = CompatFfi::Raw + pact = raw.new_pact(consumer_name, 'p') + raw.with_specification(pact, gen_spec) + i = raw.new_interaction(pact, 'a request with generators') + raw.given(i, 'a state') if state + raw.with_request(i, 'GET', '/path/one') + register_part(i, CompatFfi::REQUEST, @gen_request || CompatModel::Part.new([], nil, nil)) + raw.with_generators(i, CompatFfi::REQUEST, @gen_request_generators) if @gen_request_generators + raw.response_status(i, 200) + gen_write_pact(pact) + + provider = CompatServers::Server.new { |_req, _port| CompatServers::Response.new(200, [], nil) } + @cleanups << -> { provider.stop } + state_server = state && CompatServers::Server.new { |_req, _port| CompatServers::Response.json(200, state) } + @cleanups << -> { state_server.stop } if state_server + v = raw.verifier_new_for_application('pact-ruby-compat', Pact::VERSION) + raw.verifier_set_provider_info(v, 'p', 'http', '127.0.0.1', provider.port, '/') + raw.verifier_set_provider_state(v, state_server.url, 0, 1) if state_server + raw.verifier_add_file_source(v, pact_file) + raw.verifier_execute(v) + raw.verifier_shutdown(v) + + req = provider.requests.first or raise 'the provider received no request' + GeneratedPart.new(0, req.path, req.headers, req.body.to_s) +end + +def gen_prepare_message_body(context) + raw = CompatFfi::Raw + pact = raw.new_pact(consumer_name, 'p') + raw.with_specification(pact, 5) + i = raw.new_message_interaction(pact, 'a message with generators') + ct = @gen_request&.header('content-type') || 'application/json' + body = @gen_request&.body.to_s + raw.with_body(i, CompatFfi::REQUEST, ct, body.dup.force_encoding('UTF-8')) + raw.with_generators(i, CompatFfi::REQUEST, @gen_request_generators) if @gen_request_generators + generated = CompatFfi.async_body_generators_with_context(pact, JSON.dump(context)) + raw.free_pact_handle(pact) + + json = JSON.parse(body) + generated.each do |path, value| + raise "no value generated for #{path}" unless value + + keys = path.delete_prefix('$').split('.').reject(&:empty?) + parent = keys[0..-2].reduce(json) { |o, k| o.fetch(k) } + raise "#{path} is not in the body" unless parent.is_a?(Hash) && parent.key?(keys.last) + + parent[keys.last] = value + end + GeneratedPart.new(0, '', [], JSON.dump(json)) +end + +def gen_generated_body + g = @generated_request || @generated_response or raise 'nothing was prepared' + JSON.parse(g.body) +rescue JSON::ParserError => e + raise "generated body is not JSON (#{e.message}): #{g.body.inspect}" +end + +def gen_original_body + part = @generated_request ? @gen_request : @gen_response + JSON.parse(part&.body.to_s) +rescue JSON::ParserError + nil +end + +def gen_original_value(path) + body_value(gen_original_body, path) +rescue StandardError + :missing +end + +# `header[X-TEST]` -> ['header', 'X-TEST']; `path` -> ['path', '']. +def gen_field(name) + m = name.match(/\[(.*)\]/) + m ? [name[0...m.begin(0)], m[1]] : [name, ''] +end + +def gen_request_field(g, name) + f, key = gen_field(name) + case f + when 'path' then g.path.split('?').first + when 'header' then g.header(key) || raise("no #{key} header in #{g.headers}") + when 'queryParameter' + pair = parse_query(g.path.split('?', 2)[1]).find { |k, _| k == key } + pair ? pair.last : raise("no #{key} query parameter in #{g.path}") + else raise "unknown request field #{f}" + end +end + +def gen_response_field(g, name) + f, key = gen_field(name) + case f + when 'status' then g.status.to_s + when 'header' then g.header(key) || raise("no #{key} header in #{g.headers}") + else raise "unknown response field #{f}" + end +end + +Given('a request configured with the following generators:') do |table| + @gen_request, @gen_request_generators = gen_configure(table) +end + +Given('a response configured with the following generators:') do |table| + @gen_response, @gen_response_generators = gen_configure(table) +end + +Given('the generator test mode is set as {string}') do |mode| + @gen_mode = mode +end + +When('the request is prepared for use') do + @generated_request = gen_prepare_request(nil) +end + +When('the request is prepared for use with a {string} context:') do |kind, table| + context = JSON.parse(table.raw[0][0]) + @generated_request = + case kind + when 'providerState' then gen_prepare_request(context) + when 'mockServer' + href = context['href'] + gen_prepare_message_body({ 'mockServer' => { 'url' => href, 'href' => href } }) + else raise "unknown context #{kind}" + end +end + +When('the response is prepared for use') do + raw = CompatFfi::Raw + pact = raw.new_pact(consumer_name, 'p') + raw.with_specification(pact, gen_spec) + i = raw.new_interaction(pact, 'a response with generators') + raw.with_request(i, 'GET', '/path/one') + raw.response_status(i, 200) + register_part(i, CompatFfi::RESPONSE, @gen_response || CompatModel::Part.new([], nil, nil)) + raw.with_generators(i, CompatFfi::RESPONSE, @gen_response_generators) if @gen_response_generators + port = raw.create_mock_server_for_transport(pact, '127.0.0.1', 0, 'http', nil) + if port.negative? + raw.free_pact_handle(pact) + raise "create_mock_server_for_transport failed with #{port}" + end + begin + res = http_request(port, 'GET', '/path/one', [], nil) + ensure + raw.cleanup_mock_server(port) + raw.free_pact_handle(pact) + end + @generated_response = GeneratedPart.new(res.status, '', res.headers, res.body.to_s) +end + +Then(/^the body value for "([^"]*)" will have been replaced with an? "([^"]*)"$/) do |path, kind| + value = body_value(gen_generated_body, path) + raise "#{path} was not replaced: #{value.to_json}" if value == gen_original_value(path) + + gen_assert_value_type(kind, value) +end + +Then(/^the body value for "([^"]*)" will have been replaced with "([^"]*)"$/) do |path, expected| + value = body_value(gen_generated_body, path) + raise "#{path} was not replaced: #{value.to_json}" if value == gen_original_value(path) + raise "expected #{path} to be #{expected.inspect}, got #{value.to_json}" unless json_to_string(value) == expected +end + +Then('the request {string} will be set as {string}') do |name, expected| + actual = gen_request_field(@generated_request || raise('the request was not prepared'), name) + raise "expected request #{name} to be #{expected.inspect}, got #{actual.inspect}" unless actual == expected +end + +Then('the request {string} will match {string}') do |name, pattern| + actual = gen_request_field(@generated_request || raise('the request was not prepared'), name) + raise "expected request #{name} to match #{pattern.inspect}, got #{actual.inspect}" \ + unless actual.match?(/\A(?:#{pattern})\z/) +end + +Then('the response {string} will not be {string}') do |name, value| + actual = gen_response_field(@generated_response || raise('the response was not prepared'), name) + raise "expected response #{name} not to be #{value.inspect}" if actual == value +end + +Then('the response {string} will match {string}') do |name, pattern| + actual = gen_response_field(@generated_response || raise('the response was not prepared'), name) + raise "expected response #{name} to match #{pattern.inspect}, got #{actual.inspect}" \ + unless actual.match?(/\A(?:#{pattern})\z/) +end diff --git a/compatibility-suite/core/step_definitions/http_consumer_steps.rb b/compatibility-suite/core/step_definitions/http_consumer_steps.rb new file mode 100644 index 00000000..5bfde5a4 --- /dev/null +++ b/compatibility-suite/core/step_definitions/http_consumer_steps.rb @@ -0,0 +1,275 @@ +# frozen_string_literal: true + +# V1 to V4 HTTP consumer features: a mock server built through the FFI and driven over HTTP. +# Mirrors tests/consumer.rs in the pact-reference FFI runner. + +def start_mock_server(interactions) + @pact = new_pact(http_spec(@version)) + interactions.each { |i| register(@pact, i) } + port = CompatFfi::Raw.create_mock_server_for_transport(@pact, '127.0.0.1', 0, 'http', nil) + raise "pactffi_create_mock_server_for_transport failed with #{port}: #{CompatFfi.last_error}" if port.negative? + + @port = port + @cleanups << -> { CompatFfi::Raw.cleanup_mock_server(port) } +end + +def mock_mismatches + return @mismatches if @mismatches + raise 'mock server not started' unless @port + + JSON.parse(CompatFfi::Raw.mock_server_mismatches(@port) || '[]') +end + +def request_mismatches + mock_mismatches.select { |m| m['type'] == 'request-mismatch' }.flat_map { |m| m['mismatches'] || [] } +end + +# Applies a `| method | path | query | headers | body | ... |` changes table. `raw headers` are +# added on top of `headers` rather than replacing them, to send repeated headers. +def apply_changes(i, rows) + raw_headers = [] + rows[0].zip(rows[1]).each do |field, value| + case field + when 'method' then i.method = value + when 'path' then i.path = value + when 'query' then i.query = value + when 'headers' then i.request.headers = parse_headers(value) + when 'body' then setup_body(value, i.request) + when 'raw headers' then raw_headers = parse_headers(value) + when 'matching rules' then i.request.matching_rules = matching_rules(value) + end + end + i.request.headers.concat(raw_headers) +end + +def send_to_mock_server(i) + path = i.query.to_s.empty? ? i.path : "#{i.path}?#{i.query}" + @response = http_request(@port, i.method, path, i.request.headers, i.request.body) +end + +def mismatch_matches?(m, kind, error) + t = m['type'].to_s + right_type = t == 'BodyTypeMismatch' ? kind == 'body-content-type' : t.downcase.start_with?(kind) + right_type && m['mismatch'].to_s.include?(error) +end + +Given('the following HTTP interactions have been defined:') do |table| + @interactions = setup_common_interactions(table.raw) +end + +When('the mock server is started with interaction {int}') do |n| + start_mock_server([interaction_n(n)]) +end + +When('the mock server is started with interaction {int} but with the following changes:') do |n, table| + i = interaction_n(n) + apply_changes(i, table.raw) + start_mock_server([i]) +end + +When('the mock server is started with interactions {string}') do |list| + start_mock_server(list.split(',').map { |n| interaction_n(n.strip) }) +end + +When('request {int} is made to the mock server') do |n| + send_to_mock_server(interaction_n(n)) +end + +When('request {int} is made to the mock server with the following changes:') do |n, table| + i = interaction_n(n) + apply_changes(i, table.raw) + send_to_mock_server(i) +end + +Then(/^a (\d+) (success|error) response is returned$/) do |status, kind| + next if @response.status == status.to_i + + raise "Expected #{kind == 'success' ? 'a success' : 'an error'} response of #{status} " \ + "but got #{@response.status}: #{@response.body}" +end + +Then('the payload will contain the {string} JSON document') do |name| + # pactffi_with_body parses JSON bodies, so only the JSON value survives, not the fixture's formatting. + expected = File.binread(fixture_path("#{name}.json")) + same = @response.body == expected || + (JSON.parse(@response.body) == JSON.parse(expected) rescue false) # rubocop:disable Style/RescueModifier + raise "Expected payload #{expected} but got #{@response.body}" unless same +end + +Then('the content type will be set as {string}') do |expected| + actual = @response.header('content-type') + raise 'Response does not contain a content-type header' unless actual + raise "Expected response content-type of '#{expected}' but was '#{actual}'" unless actual == expected +end + +When('the pact test is done') do + raise 'mock server not started' unless @port + + mismatches = mock_mismatches + CompatFfi::Raw.mock_server_matched(@port) + if mismatches.empty? + rc = CompatFfi::Raw.write_pact_file(@port, @pact_dir, true) + raise "pactffi_write_pact_file failed with #{rc}" unless rc.zero? + end + @mismatches = mismatches + CompatFfi::Raw.cleanup_mock_server(@port) +end + +Then(/^the mock server will write out a Pact file for the interactions? when done$/) do + load_pact_json + expected = @version == 'v2' ? '2.0.0' : '1.0.0' + actual = @pact_json.dig('metadata', 'pactSpecification', 'version') + raise "Expected a #{expected} pact file but metadata.pactSpecification.version was #{actual}" unless actual == expected +end + +Then(/^the mock server will NOT write out a Pact file for the interactions? when done$/) do + raise "Expected no pact file, but found #{pact_file}" if File.exist?(pact_file) +end + +Then('the mock server status will be OK') do + m = mock_mismatches + raise "Mock server has #{m.size} mismatches: #{m.to_json}" unless m.empty? +end + +Then(/^the mock server status will (?:NOT be OK|be mismatches)$/) do + raise 'Mock server has no mismatches' if mock_mismatches.empty? +end + +Then(/^the pact file will contain \{(\d+)\} interactions?$/) do |n| + count = (@pact_json['interactions'] || []).size + raise "Expected the pact file to contain #{n} interaction(s), but had #{count}" unless count == n.to_i +end + +Then(/^the \{(first|second|third)\} interaction request will be for a "(\w+)"$/) do |nth, method| + actual = pact_interaction(nth).dig('request', 'method') + raise "Expected request method #{method} but was #{actual}" unless actual.to_s.casecmp?(method) +end + +Then(/^the \{(first|second|third)\} interaction request query parameters will be "(.*)"$/) do |nth, query| + actual = pact_interaction(nth).dig('request', 'query') + raise "Expected query #{query} but was #{actual.inspect}" unless pact_query(actual) == query_map(parse_query(query)) +end + +Then(/^the \{(first|second|third)\} interaction request will contain the header "(.*)" with value "(.*)"$/) do |nth, name, value| + actual = pact_header(pact_interaction(nth)['request'], name) + raise "Expected header #{name}: #{value} but was #{actual.inspect}" unless actual == value +end + +Then(/^the \{(first|second|third)\} interaction request content type will be "(.*)"$/) do |nth, ct| + request = pact_interaction(nth)['request'] + actual = pact_header(request, 'content-type') || + (request['body'].is_a?(Hash) || request['body'].is_a?(Array) ? 'application/json' : nil) + raise "Expected request content type #{ct} but was #{actual.inspect}" unless actual == ct +end + +Then(/^the \{(first|second|third)\} interaction (request|response) will contain the "(.*)" document$/) do |nth, part, fixture| + compare_fixture_body(pact_interaction(nth)[part]['body'], fixture) +end + +Then('the mismatches will contain a {string} mismatch with error {string}') do |kind, error| + all = request_mismatches + raise "Did not find a #{kind} mismatch with error #{error.inspect} in #{all.to_json}" unless + all.any? { |m| mismatch_matches?(m, kind, error) } +end + +Then('the mismatches will contain a {string} mismatch with path {string} with error {string}') do |kind, path, error| + all = request_mismatches + found = all.any? do |m| + actual = { 'QueryMismatch' => m['parameter'], 'HeaderMismatch' => m['key'], 'BodyMismatch' => m['path'] }[m['type']] + mismatch_matches?(m, kind, error) && actual == path + end + raise "Did not find a #{kind} mismatch at #{path} with error #{error.inspect} in #{all.to_json}" unless found +end + +Then(/^the mock server status will be an unexpected "(\w+)" request received error for interaction \{(\d+)\}$/) do |method, n| + i = interaction_n(n) + expected_query = query_map(parse_query(i.query)) + all = mock_mismatches + found = all.any? do |m| + m['type'] == 'request-not-found' && m['method'] == method && m['path'] == i.path && + pact_query(m.dig('request', 'query')) == expected_query + end + raise "Did not find an unexpected #{method} request for interaction #{n} in #{all.to_json}" unless found +end + +Then(/^the mock server status will be an unexpected "(\w+)" request received error for path "(.*)"$/) do |method, path| + all = mock_mismatches + raise "Did not find an unexpected #{method} request for #{path} in #{all.to_json}" unless + all.any? { |m| m['type'] == 'request-not-found' && m['method'] == method && m['path'] == path } +end + +Then(/^the mock server status will be an expected but not received error for interaction \{(\d+)\}$/) do |n| + i = interaction_n(n) + all = mock_mismatches + raise "Did not find a missing request for interaction #{n} in #{all.to_json}" unless + all.any? { |m| m['type'] == 'missing-request' && m['method'] == i.method && m['path'] == i.path } +end + +# V3 and V4: interactions defined without a mock server, then written straight from the pact handle. + +Given(/^an (integration|HTTP interaction) is being defined for a consumer test$/) do |_kind| + @mode = :http + @pact ||= new_pact(http_spec(@version)) # v4.feature mixes HTTP and message interactions in one pact + @interaction = CompatFfi::Raw.new_interaction(@pact, 'interaction for a consumer test') + CompatFfi::Raw.with_request(@interaction, 'GET', '/') +end + +Given(/^a provider state "(.*)" (?:for the (?:synchronous )?message )?is specified$/) do |state| + raise "pactffi_given failed: #{CompatFfi.last_error}" unless CompatFfi::Raw.given(@interaction, state) +end + +Given(/^a provider state "(.*)" (?:for the (?:synchronous )?message )?is specified with the following data:$/) do |state, table| + rc = CompatFfi::Raw.given_with_params(@interaction, state, json_params(table.raw).to_json) + raise "pactffi_given_with_params failed with #{rc}" unless rc.zero? +end + +Given(/^a key of "(.*)" is specified for the (?:HTTP|message|synchronous message) interaction$/) do |key| + raise 'pactffi_set_key failed' unless CompatFfi::Raw.set_key(@interaction, key) +end + +Given(/^the (?:HTTP|message|synchronous message) interaction is marked as pending$/) do + raise 'pactffi_set_pending failed' unless CompatFfi::Raw.set_pending(@interaction, true) +end + +Given(/^a comment "(.*)" is added to the (?:HTTP|message|synchronous message) interaction$/) do |comment| + raise 'pactffi_add_text_comment failed' unless CompatFfi::Raw.add_text_comment(@interaction, comment) +end + +When('the Pact file for the test is generated') do + raise 'no pact is being defined' unless @pact + + write_pact_from_handle(@pact) +end + +def first_provider_states + pact_interaction('first')['providerStates'] || [] +end + +Then(/^the (?:interaction|first message) in the Pact file will contain (\d+) provider states?$/i) do |n| + states = first_provider_states + raise "Expected #{n} provider states but found #{states.to_json}" unless states.size == n.to_i +end + +Then(/^the (?:interaction|first message) in the Pact file will contain provider state "(.*)"$/i) do |state| + states = first_provider_states + raise "No provider state '#{state}' in #{states.to_json}" unless states.any? { |s| s['name'] == state } +end + +Then(/^the provider state "(.*)" (?:in the Pact file|for the message) will contain the following parameters:$/) do |state, table| + expected = JSON.parse(table.raw[1][0]) + states = first_provider_states + s = states.find { |x| x['name'] == state } or raise "No provider state '#{state}' in #{states.to_json}" + raise "Expected parameters #{expected.to_json} but were #{s['params'].to_json}" unless s['params'] == expected +end + +Then('the first interaction in the Pact file will have a type of {string}') do |expected| + actual = pact_interaction('first')['type'] + raise "Expected type '#{expected}' but was #{actual.inspect}" unless actual == expected +end + +# The expected value is JSON in single quotes. +Then(/^the first interaction in the Pact file will have "([^"]+)" = '(.*)'$/) do |name, value| + expected = JSON.parse(value) + actual = pact_interaction('first')[name] + raise "Expected #{name} = #{expected.to_json} but was #{actual.to_json}" unless actual == expected +end diff --git a/compatibility-suite/core/step_definitions/http_provider_steps.rb b/compatibility-suite/core/step_definitions/http_provider_steps.rb new file mode 100644 index 00000000..639290fc --- /dev/null +++ b/compatibility-suite/core/step_definitions/http_provider_steps.rb @@ -0,0 +1,435 @@ +# frozen_string_literal: true + +# V1 to V4 HTTP provider and V3/V4 message provider features, verified through the pact_ffi +# verifier functions. Mirrors tests/provider.rs in the pact-reference FFI runner. +# +# Pact files are written through the FFI; the provider, the provider state callback and the Pact +# broker are small local servers (support/servers.rb) that record what they receive. A message +# provider answers the verifier's POST with the message: the body, its content type, and the +# metadata as base64 JSON in the `pact-message-metadata` header. + +def provider_spec = http_spec(@version) + +# Serves each interaction's response to a request with the same method and path; anything else is a 500. +def start_provider(interactions) + @provider = CompatServers::Server.new do |req, _port| + i = interactions.find { |x| x.method.casecmp?(req.method) && x.path == req.path_only } + if i + CompatServers::Response.new(i.status, i.response.headers, i.response.body || '') + else + CompatServers::Response.new(500, [], 'no matching interaction') + end + end + server = @provider + @cleanups << -> { server.stop } +end + +def provider_dir = File.join(@tmp, 'provider-pacts') + +def write_provider_pact(consumer) + pact = CompatFfi::Raw.new_pact(consumer, 'p') + CompatFfi::Raw.with_specification(pact, provider_spec) + yield pact + rc = CompatFfi::Raw.pact_handle_write_file(pact, provider_dir, false) + CompatFfi::Raw.free_pact_handle(pact) + raise "pactffi_pact_handle_write_file failed with #{rc}: #{CompatFfi.last_error}" unless rc.zero? + + File.join(provider_dir, "#{consumer}-p.json") +end + +# A one-interaction pact, as a consumer test would have written it; the block adds states, comments etc. +def write_interaction_pact(n) + interaction = interaction_n(n) + write_provider_pact("c_#{n}") do |pact| + i = register(pact, interaction) + yield i if block_given? + end +end + +def push_interaction_pact(n, &block) + (@pact_files ||= []) << write_interaction_pact(n, &block) +end + +# A one-message pact whose description is the message name, which the message provider looks it up by. +def push_message_pact(name) + file = write_provider_pact("c_#{name}") do |pact| + yield CompatFfi::Raw.new_message_interaction(pact, name) + end + (@pact_files ||= []) << file +end + +# Cucumber regex captures keep `\"`; `{string}` would have unescaped it. +def unescape(s) = s.gsub('\\"', '"') + +def message_part(cell) + part = CompatModel::Part.new + setup_body(unescape(cell), part) + part +end + +def message_body(i, cell, rules = nil) + part = message_part(cell) + part.matching_rules = rules + register_part(i, CompatFfi::REQUEST, part) +end + +def metadata_value(value) + v = value.strip + v.start_with?('JSON:') ? JSON.parse(v.delete_prefix('JSON:').strip) : value +end + +# pactffi_with_metadata parses the value as JSON and falls back to a string. +def add_message_metadata(i, key, value) + v = value.strip.start_with?('JSON:') ? value.strip.delete_prefix('JSON:').strip : value + raise "pactffi_with_metadata failed for #{key}" unless CompatFfi::Raw.with_metadata(i, key, v, CompatFfi::REQUEST) +end + +def add_comments(i, rows) + rows.drop(1).each do |text, kind| + case kind + when 'text' then CompatFfi::Raw.add_text_comment(i, text) + when 'testname' then CompatFfi::Raw.set_comment(i, 'testname', JSON.dump(text)) + else raise "unknown comment type #{kind}" + end + end +end + +def add_provider_message(name, body, metadata = {}) + (@messages ||= []) << [name, message_part(body), metadata] +end + +# Serves every message the scenario defined; the verifier POSTs `{"description": ...}` for each one. +def start_message_provider + messages = @messages + @provider = CompatServers::Server.new do |req, _port| + description = (JSON.parse(req.body)['description'] rescue nil).to_s + name, part, metadata = messages.find { |n, _, _| n == description } + if name + ct = part.header('content-type') || 'text/plain' + meta = { 'contentType' => ct }.merge(metadata) + CompatServers::Response.new(200, [['Content-Type', ct], ['pact-message-metadata', Base64.strict_encode64(JSON.dump(meta))]], + part.body || '') + else + CompatServers::Response.json(404, { 'error' => "no message '#{description}'" }) + end + end + server = @provider + @cleanups << -> { server.stop } +end + +def start_state_callback(fail) + @state_callback = CompatServers::Server.new do |_req, _port| + fail ? CompatServers::Response.json(500, { 'error' => 'state change failed' }) : CompatServers::Response.json(200, {}) + end + server = @state_callback + @cleanups << -> { server.stop } +end + +def state_calls + (@state_callback&.requests || []).filter_map { |r| JSON.parse(r.body) rescue nil } +end + +def state_called?(action, state = nil, params = {}) + state_calls.any? do |c| + c['action'] == action && (state.nil? || c['state'] == state) && + params.all? { |k, v| (c['params'] || {})[k] == v } + end +end + +def published(n) + (@brokers || []).select { |i, _| i == n }.flat_map { |_, b| b.requests } + .select { |r| r.method == 'POST' && r.path_only.end_with?('/verification-results') } + .filter_map { |r| JSON.parse(r.body) rescue nil } +end + +# Maps the suite's error wording onto the verifier's JSON report. +def verifier_error?(entries, error) + types = Array(entries).flat_map { |r| r.dig('mismatch', 'mismatches') || [] }.map { |m| m['type'] } + has = ->(*t) { types.intersect?(t) } + case error + when 'Response status did not match' then has.('StatusMismatch') + when 'Headers had differences' then has.('HeaderMismatch') + when 'Body had differences' then has.('BodyMismatch', 'BodyTypeMismatch') + when 'Body type had differences' then has.('BodyTypeMismatch') + when 'Metadata had differences' then has.('MetadataMismatch') + when 'State change request failed' then JSON.dump(entries).include?('state change handlers has failed') + else raise "unknown error #{error}" + end +end + +def published_with(n, success) + pub = published(n) + raise "no verification result with success = #{success} for interaction #{n}: #{pub}" \ + unless pub.any? { |r| r['success'] == success } +end + +Given('a provider is started that returns the response from interaction {int}') do |n| + start_provider([interaction_n(n)]) +end + +Given('a provider is started that returns the response from interaction {int}, with the following changes:') do |n, table| + i = interaction_n(n) + rows = table.raw + rows[0].zip(rows[1]).each do |col, value| + case col + when 'response' then i.status = value.to_i + when 'response headers' then i.response.headers.concat(parse_headers(value)) + when 'response body' then setup_body(value, i.response) + else raise "unsupported change column #{col}" + end + end + start_provider([i]) +end + +Given('a provider is started that returns the responses from interactions {string}') do |ids| + start_provider(ids.split(',').map { |id| interaction_n(id.strip.to_i) }) +end + +Given(/^a Pact file for interaction (\d+) is to be verified$/) do |n| + push_interaction_pact(n) +end + +Given(/^a Pact file for interaction (\d+) is to be verified with a provider state "(.*)" defined$/) do |n, state| + push_interaction_pact(n) { |i| CompatFfi::Raw.given(i, state) } +end + +Given(/^a Pact file for interaction (\d+) is to be verified with the following provider states defined:$/) do |n, table| + rows = table.raw + params_col = rows[0].index('Parameters') + push_interaction_pact(n) do |i| + rows.drop(1).each do |row| + params = params_col && row[params_col].to_s.strip + if params.nil? || params.empty? + CompatFfi::Raw.given(i, row[0]) + else + rc = CompatFfi::Raw.given_with_params(i, row[0], params) + raise "pactffi_given_with_params failed with #{rc}" unless rc.zero? + end + end + end +end + +Given(/^a Pact file for interaction (\d+) is to be verified, but is marked pending$/) do |n| + push_interaction_pact(n) { |i| CompatFfi::Raw.set_pending(i, true) } +end + +Given(/^a Pact file for interaction (\d+) is to be verified with the following comments:$/) do |n, table| + push_interaction_pact(n) { |i| add_comments(i, table.raw) } +end + +Given(/^a provider is started that can generate the "(.*)" message with "(.*)"$/) do |name, body| + add_provider_message(name, body) +end + +Given(/^a provider is started that can generate the "(.*)" message with "(.*)" and the following metadata:$/) do |name, body, table| + add_provider_message(name, body, table.raw.drop(1).to_h { |k, v| [k, metadata_value(v)] }) +end + +Given(/^a Pact file for "([^"]*)":"(.*)" is to be verified$/) do |name, body| + push_message_pact(name) { |i| message_body(i, body) } +end + +Given(/^a Pact file for "([^"]*)":"(.*)" is to be verified with provider state "(.*)"$/) do |name, body, state| + push_message_pact(name) do |i| + CompatFfi::Raw.given(i, state) + message_body(i, body) + end +end + +Given(/^a Pact file for "([^"]*)":"(.*)" is to be verified, but is marked pending$/) do |name, body| + push_message_pact(name) do |i| + message_body(i, body) + CompatFfi::Raw.set_pending(i, true) + end +end + +Given(/^a Pact file for "([^"]*)":"(.*)" is to be verified with the following comments:$/) do |name, body, table| + push_message_pact(name) do |i| + message_body(i, body) + add_comments(i, table.raw) + end +end + +Given(/^a Pact file for "([^"]*)":"(.*)" is to be verified with the following metadata:$/) do |name, body, table| + push_message_pact(name) do |i| + message_body(i, body) + table.raw.drop(1).each { |k, v| add_message_metadata(i, k, v) } + end +end + +# Rows of `body`, `matching rules` (a fixture or `JSON:`) and `metadata` (`key=value; ...`). +Given(/^a Pact file for "([^"]*)" is to be verified with the following:$/) do |name, table| + rows = table.raw.to_h { |k, v| [k, v] } + push_message_pact(name) do |i| + message_body(i, rows['body'].to_s, matching_rules(rows['matching rules'])) + rows['metadata'].to_s.split(';').reject { |e| e.strip.empty? }.each do |entry| + key, value = entry.strip.split('=', 2) + raise "bad metadata #{entry}" unless value + + add_message_metadata(i, key, value) + end + end +end + +# The broker serves the pacts-for-verification flow for one pact and accepts verification results. +Given(/^a Pact file for interaction (\d+) is to be verified from a Pact broker$/) do |n| + n = n.to_i + pact = JSON.parse(File.read(write_interaction_pact(n))) + broker = CompatServers::Server.new do |req, port| + base = "http://127.0.0.1:#{port}" + pact_path = "/pacts/provider/p/consumer/c_#{n}" + pact_url = base + pact_path + for_verification = "#{base}/pacts/provider/p/for-verification" + case [req.method, req.path_only] + in ['GET', '/'] + CompatServers::Response.json(200, { '_links' => { 'pb:provider-pacts-for-verification' => { + 'href' => "#{base}/pacts/provider/{provider}/for-verification", 'templated' => true + } } }) + in ['GET', '/pacts/provider/p/for-verification'] + CompatServers::Response.json(200, { '_links' => { 'self' => { 'href' => for_verification } } }) + in ['POST', '/pacts/provider/p/for-verification'] + CompatServers::Response.json(200, { + '_embedded' => { 'pacts' => [{ + '_links' => { 'self' => { 'href' => pact_url, 'name' => "Pact between c_#{n} and p" } }, + 'shortDescription' => 'latest' + }] }, + '_links' => { 'self' => { 'href' => for_verification } } + }) + in ['GET', ^pact_path] + CompatServers::Response.json(200, pact.merge('_links' => { + 'self' => { 'href' => pact_url }, + 'pb:publish-verification-results' => { 'href' => "#{pact_url}/verification-results" } + })) + in ['POST', String => path] if path.end_with?('/verification-results') + CompatServers::Response.json(201, {}) + else + CompatServers::Response.json(404, { 'error' => 'not found' }) + end + end + @cleanups << -> { broker.stop } + (@brokers ||= []) << [n, broker] +end + +Given('publishing of verification results is enabled') do + @publish = true +end + +Given('a provider state callback is configured') do + start_state_callback(false) +end + +Given('a provider state callback is configured, but will return a failure') do + start_state_callback(true) +end + +# pact_ffi has no request filter callback, only custom headers. +Given('a request filter is configured to make the following changes:') do |table| + rows = table.raw + rows[0].zip(rows[1]).each do |col, value| + raise "pact_ffi has no request filter for #{col}; only pactffi_verifier_add_custom_header exists" unless col == 'headers' + + (@custom_headers ||= []).concat(parse_headers(value)) + end +end + +When('the verification is run') do + start_message_provider if @messages&.any? + raise 'no provider started' unless @provider + + raw = CompatFfi::Raw + v = raw.verifier_new_for_application('pact-ruby-compat', Pact::VERSION) + raw.verifier_set_provider_info(v, 'p', 'http', '127.0.0.1', @provider.port, '/') + raw.verifier_set_provider_state(v, @state_callback.url, 1, 1) if @state_callback + raw.verifier_set_publish_options(v, '1.2.3', nil, nil, 0, nil) if @publish + (@custom_headers || []).each { |k, val| raw.verifier_add_custom_header(v, k, val) } + (@pact_files || []).each { |f| raw.verifier_add_file_source(v, f) } + (@brokers || []).each do |_, b| + raw.verifier_broker_source_with_selectors(v, b.url, nil, nil, nil, 0, nil, nil, 0, nil, nil, 0, nil, 0) + end + @exit = raw.verifier_execute(v) + @output = CompatFfi.take_string(raw.verifier_output(v, 1)).to_s + json = CompatFfi.take_string(raw.verifier_json(v)) + @results = json ? JSON.parse(json) : {} + raw.verifier_shutdown(v) +end + +Then('the verification will be successful') do + raise "verification failed (exit #{@exit}):\n#{@output}" unless @exit.zero? && @results['result'] == true +end + +Then('the verification will NOT be successful') do + raise "verification passed (exit #{@exit})" if @exit.zero? || @results['result'] != false +end + +Then('the verification results will contain a {string} error') do |error| + raise "no \"#{error}\" error in the verification results: #{@results}" \ + unless verifier_error?(@results['interactionResults'], error) +end + +Then('there will be a pending {string} error') do |error| + raise "no pending \"#{error}\" error in the verification results: #{@results}" \ + unless verifier_error?(@results['pendingErrors'], error) +end + +Then(/^the comment "(.*)" will have been printed to the console$/) do |comment| + raise "comment '#{comment}' not in the verifier output:\n#{@output}" unless @output.include?(comment) +end + +Then(/^the "(.*)" will displayed as the original test name$/) do |name| + raise "test name '#{name}' not in the verifier output:\n#{@output}" unless @output.include?("Test Name: #{name}") +end + +Then(/^the provider state callback will receive a setup call with "(.*)" and the following parameters:$/) do |state, table| + params = json_params(table.raw) + raise "no setup call for '#{state}' with #{params}: #{state_calls}" unless state_called?('setup', state, params) +end + +Then(/^the provider state callback will receive a teardown call "(.*)" and the following parameters:$/) do |state, table| + params = json_params(table.raw) + raise "no teardown call for '#{state}' with #{params}: #{state_calls}" unless state_called?('teardown', state, params) +end + +Then('a verification result will NOT be published back') do + pub = (@brokers || []).flat_map { |n, _| published(n) } + raise "verification results were published: #{pub}" unless pub.empty? +end + +Then(/^a successful verification result will be published back for interaction \{(\d+)\}$/) do |n| + published_with(n.to_i, true) +end + +Then(/^a failed verification result will be published back for the interaction \{(\d+)\}$/) do |n| + published_with(n.to_i, false) +end + +Then('the provider state callback will be called before the verification is run') do + raise "provider state callback was not called for setup: #{state_calls}" unless state_called?('setup') +end + +Then(/^the provider state callback will receive a setup call with "(.*)" as the provider state parameter$/) do |state| + raise "no setup call for '#{state}': #{state_calls}" unless state_called?('setup', state) +end + +Then('the provider state callback will be called after the verification is run') do + raise "provider state callback was not called for teardown: #{state_calls}" unless state_called?('teardown') +end + +Then(/^the provider state callback will receive a teardown call "(.*)" as the provider state parameter$/) do |state| + raise "no teardown call for '#{state}': #{state_calls}" unless state_called?('teardown', state) +end + +Then('the provider state callback will NOT receive a teardown call') do + raise "provider state callback received a teardown call: #{state_calls}" if state_called?('teardown') +end + +# The reference suite does not check this either: the warning only goes to the log. +Then(/^a warning will be displayed that there was no provider state callback configured for provider state "(.*)"$/) do |_state| + nil +end + +Then(/^the request to the provider will contain the header "(.*)"$/) do |header| + name, value = header.split(':', 2).map(&:strip) + reqs = @provider.requests + raise "not every provider request had #{name}: #{value}: #{reqs}" \ + if reqs.empty? || !reqs.all? { |r| r.header(name) == value } +end diff --git a/compatibility-suite/core/step_definitions/matching_steps.rb b/compatibility-suite/core/step_definitions/matching_steps.rb new file mode 100644 index 00000000..5c53c304 --- /dev/null +++ b/compatibility-suite/core/step_definitions/matching_steps.rb @@ -0,0 +1,175 @@ +# frozen_string_literal: true + +# Steps for V3 http_matching.feature and V3/V4 matching_rules.feature. pact_ffi has no request +# comparison call, so each received request is sent to a mock server holding the expected one and +# the mock server's mismatches are read back. + +def expected_match_interaction + @expected ||= CompatModel::Interaction.new( + 'expected request', 'GET', '/', '', CompatModel::Part.new([], nil, nil), 200, + CompatModel::Part.new([], nil, nil) + ) +end + +def received_reqs = (@received_reqs ||= []) + +def new_received_req = { query: '', part: CompatModel::Part.new([], nil, nil) } + +# Fills a part and its query from one row of a `| body | content type | query | headers | ... |` table. +def match_apply_row(fields, values, target) + get = ->(name) { (n = fields.index(name)) && values[n] } + headers = get.('headers') + target[:part].headers = parse_headers(headers) if headers && !headers.empty? + if (body = get.('body')) + ct = get.('content type') + setup_body(body, target[:part], ct.nil? || ct.empty? ? nil : ct) + end + target[:query] = get.('query') if get.('query') + target[:part].matching_rules = matching_rules(get.('matching rules')) if get.('matching rules') +end + +def match_spec = @version == 'v4' ? 5 : 4 + +def compare_received(req) + raw = CompatFfi::Raw + pact = raw.new_pact(consumer_name, 'p') + raw.with_specification(pact, match_spec) + register(pact, expected_match_interaction) + port = raw.create_mock_server_for_transport(pact, '127.0.0.1', 0, 'http', nil) + if port.negative? + raw.free_pact_handle(pact) + raise "create_mock_server_for_transport failed with #{port}" + end + begin + path = req[:query].empty? ? '/' : "/?#{req[:query]}" + http_request(port, 'GET', path, req[:part].headers, req[:part].body) + mismatches = JSON.parse(raw.mock_server_mismatches(port) || "[]") + ensure + raw.cleanup_mock_server(port) + raw.free_pact_handle(pact) + end + mismatches.flat_map { |m| m['type'] == 'request-mismatch' ? (m['mismatches'] || []) : [m] } +end + +def match_mismatch_path(m) + field = case m['type'] + when 'QueryMismatch' then 'parameter' + when 'HeaderMismatch', 'MetadataMismatch' then 'key' + when 'BodyMismatch' then 'path' + end + field && m[field] +end + +def match_description?(description, error) + error = error.gsub('\\"', '"') + description.include?(error) || (Regexp.new(error).match?(description) rescue false) +end + +Given(/^an expected request with an? "([^"]*)" header of "([^"]*)"$/) do |name, value| + expected_match_interaction.request.set_header(name, value) +end + +Given(/^a request is received with an? "([^"]*)" header of "([^"]*)"$/) do |name, value| + r = new_received_req + r[:part].set_header(name, value) + received_reqs << r +end + +Given('an expected request configured with the following:') do |table| + rows = table.raw + target = { query: expected_match_interaction.query, part: expected_match_interaction.request } + match_apply_row(rows[0], rows[1], target) + expected_match_interaction.query = target[:query] +end + +Given('a request is received with the following:') do |table| + rows = table.raw + r = new_received_req + match_apply_row(rows[0], rows[1], r) + received_reqs << r +end + +Given('the following requests are received:') do |table| + rows = table.raw + rows[1..].each do |values| + r = new_received_req + match_apply_row(rows[0], values, r) + received_reqs << r + end +end + +When(/^the requests? (?:is|are) compared to the expected one$/) do + @match_results = received_reqs.map { |r| compare_received(r) } +end + +Then('the comparison should be OK') do + bad = @match_results.find(&:any?) + raise "Expected all requests to match, got mismatches #{JSON.dump(bad)}" if bad +end + +Then('the comparison should NOT be OK') do + raise 'All requests matched' if @match_results.all?(&:empty?) +end + +Then(/^the mismatches will contain a mismatch with error "(.*)" -> "(.*)"$/) do |path, error| + all = @match_results.flatten + found = all.any? { |m| match_mismatch_path(m) == path && match_description?(m['mismatch'].to_s, error) } + raise "Did not find a mismatch at #{path} with error #{error.inspect} in #{JSON.dump(all)}" unless found +end + +Given('an expected response configured with the following:') do |table| + rows = table.raw + rows[0].zip(rows[1]).each do |field, value| + case field + when 'status' then @expected_status = value.to_i + when 'matching rules' then @response_rules = matching_rules(value) + else raise "unsupported response field #{field}" + end + end +end + +Given('a status {int} response is received') do |status| + @received_status = status +end + +# pact_ffi has no response comparison call, so verify a one-interaction pact against a provider +# returning the received status. +When('the response is compared to the expected one') do + raw = CompatFfi::Raw + pact = raw.new_pact(consumer_name, 'p') + raw.with_specification(pact, match_spec) + i = raw.new_interaction(pact, 'expected response') + raw.with_request(i, 'GET', '/') + raw.response_status(i, @expected_status) + raw.with_matching_rules(i, CompatFfi::RESPONSE, @response_rules) if @response_rules + FileUtils.mkdir_p(@pact_dir) + rc = raw.pact_handle_write_file(pact, @pact_dir, true) + raw.free_pact_handle(pact) + raise "pact_handle_write_file failed with #{rc}" unless rc.zero? + + status = @received_status + provider = CompatServers::Server.new { |_req, _port| CompatServers::Response.new(status, [], nil) } + @cleanups << -> { provider.stop } + v = raw.verifier_new_for_application('pact-ruby-compat', Pact::VERSION) + raw.verifier_set_provider_info(v, 'p', 'http', '127.0.0.1', provider.port, '/') + raw.verifier_add_file_source(v, pact_file) + raw.verifier_execute(v) + json = CompatFfi.take_string(raw.verifier_json(v)) + raw.verifier_shutdown(v) + results = json ? JSON.parse(json) : {} + @response_mismatches = Array(results['errors']).flat_map { |e| e.dig('mismatch', 'mismatches') || [] } +end + +Then('the response comparison should be OK') do + raise "Expected the response to match, got #{JSON.dump(@response_mismatches)}" unless @response_mismatches.empty? +end + +Then('the response comparison should NOT be OK') do + raise 'The response matched' if @response_mismatches.empty? +end + +Then('the response mismatches will contain a {string} mismatch with error {string}') do |type, error| + want = { 'status' => 'StatusMismatch', 'header' => 'HeaderMismatch', 'body' => 'BodyMismatch' }.fetch(type) + found = @response_mismatches.any? { |m| m['type'] == want && m['mismatch'].to_s.include?(error) } + raise "No #{want} with error #{error.inspect} in #{JSON.dump(@response_mismatches)}" unless found +end diff --git a/compatibility-suite/core/step_definitions/message_steps.rb b/compatibility-suite/core/step_definitions/message_steps.rb new file mode 100644 index 00000000..64820254 --- /dev/null +++ b/compatibility-suite/core/step_definitions/message_steps.rb @@ -0,0 +1,316 @@ +# frozen_string_literal: true + +# V3/V4 message consumer, V4 synchronous message consumer and V4 general features. +# A port of the pact-reference FFI runner's message.rs. Provider state, key, pending, +# comment, "the Pact file for the test is generated" and the interaction attribute steps +# are shared with the HTTP consumer steps. + +def ffi_message_part(which) = which.to_s.strip == 'response' ? CompatFfi::RESPONSE : CompatFfi::REQUEST + +def defined_interaction = @interaction || raise('no message is being defined') + +# Metadata values come back from the FFI as text: strings bare, everything else as JSON. +def contents_metadata(contents, key) + pair = contents.metadata.find { |k, _| k == key } or raise "no metadata #{key} in #{contents.metadata.inspect}" + JSON.parse(pair[1]) +rescue JSON::ParserError + pair[1] +end + +# `JSON: {...}` is a JSON value (the feature escapes its quotes); anything else is a string. +def expected_value(s) + s.start_with?('JSON:') ? JSON.parse(s.delete_prefix('JSON:').strip.gsub('\\"', '"')) : s +end + +def json_to_string(v) = v.is_a?(String) ? v : JSON.generate(v) + +def body_value(body, path) + keys = path.delete_prefix('$').split('.').reject(&:empty?) + keys.reduce(body) do |v, k| + raise "#{path} is not in the body #{body.to_json}" unless v.is_a?(Hash) && v.key?(k) + + v[k] + end +end + +VALUE_TYPES = { 'integer' => /\A-?\d+\z/, 'decimal number' => /\A-?\d+\.\d+\z/, 'boolean' => /\A(true|false)\z/ }.freeze + +def assert_value_type(kind, v) + pattern = VALUE_TYPES.fetch(kind) { raise "unknown value type #{kind}" } + raise "expected a(n) #{kind}, got #{v.to_json}" unless json_to_string(v).match?(pattern) +end + +# Sets a message body the way a client would; returns the body as a JSON value when it is one. +def add_message_body(i, p, cell) + part = CompatModel::Part.new + setup_body(cell, part) + body = part.body || ''.b + ct = part.header('content-type') || 'text/plain' + ok = if binary?(ct, body) + CompatFfi.with_binary_body(i, p, ct, body) + else + CompatFfi::Raw.with_body(i, p, ct, body.dup.force_encoding('UTF-8')) + end + raise "pactffi_with_body failed: #{CompatFfi.last_error}" unless ok + + JSON.parse(body) +rescue JSON::ParserError + nil +end + +def add_message_metadata_value(which, key, value) + ok = CompatFfi::Raw.with_metadata(defined_interaction, key, JSON.generate(value), ffi_message_part(which)) + raise "pactffi_with_metadata failed for #{key}" unless ok + + (which == 'response' ? @response_metadata : @request_metadata)[key] = value +end + +def document_value(cell) + cell = "file: #{cell}" unless cell.include?(':') + part = CompatModel::Part.new + setup_body(cell, part) + body = (part.body || '').dup.force_encoding('UTF-8') + JSON.parse(body) +rescue JSON::ParserError + body +end + +def compare_document(actual, cell) + expected = document_value(cell) + if actual.is_a?(String) && !expected.is_a?(String) + actual = begin + JSON.parse(actual) + rescue JSON::ParserError + actual + end + end + raise "Expected document #{expected.to_json} but was #{actual.to_json}" unless actual == expected +end + +def contents_body_value(contents) + s = contents.body_str || '' + JSON.parse(s) +rescue JSON::ParserError + s +end + +def received(which) + if @sync + request, responses = @received_sync.first || raise('no synchronous message was received') + which == 'request' ? request : (responses.first || raise('the message has no response')) + else + @received.first || raise('no message was received') + end +end + +def first_message + (@pact_json['messages'] || @pact_json['interactions'] || []).first || raise('no messages in the pact file') +end + +def first_pact_interaction + (@pact_json['interactions'] || []).first || raise('no interactions in the pact file') +end + +# A V4 message part's `contents` is `{content, contentType, encoded}`. +def v4_content(contents) + content = contents['content'] + return content unless contents['encoded'].to_s.casecmp?('base64') && content.is_a?(String) + + Base64.decode64(content).force_encoding('UTF-8') +end + +def start_message(sync) + @pact ||= new_pact(message_spec(@version)) + @sync = sync + @received = [] + @received_sync = [] + @request_metadata = {} + @response_metadata = {} + @interaction = if sync + CompatFfi::Raw.new_sync_message_interaction(@pact, 'a synchronous message') + else + CompatFfi::Raw.new_message_interaction(@pact, 'a message') + end +end + +# ---- Defining the interaction ---- + +Given(/^a message (?:integration|interaction) is being defined for a consumer test$/) do + start_message(false) +end + +Given('a synchronous message interaction is being defined for a consumer test') do + start_message(true) +end + +Given('a message is defined') do + defined_interaction +end + +Given(/^the message (request |)payload contains the "([^"]+)" JSON document$/) do |_request, name| + @request_body = add_message_body(defined_interaction, CompatFfi::REQUEST, "file: #{name}.json") +end + +Given(/^the message response payload contains the "([^"]+)" document$/) do |cell| + @response_body = add_message_body(defined_interaction, CompatFfi::RESPONSE, cell) +end + +Given(/^the message (request |)contains the following metadata:$/) do |_request, table| + table.raw.drop(1).each { |key, value| add_message_metadata_value('request', key, expected_value(value)) } +end + +# `| body | generators | metadata |`, any of them. Generators are inline `JSON:` or a fixture file. +Given(/^the message (request |response |)is configured with the following:$/) do |which, table| + which = which.strip + i = defined_interaction + p = ffi_message_part(which) + cells = table.raw[0].zip(table.raw[1]).to_h + if cells['body'] + value = add_message_body(i, p, cells['body']) + which == 'response' ? @response_body = value : @request_body = value + elsif @sync && which == 'response' + # Sync response metadata and generators only apply to responses that exist; only a body adds one. + raise 'pactffi_with_body failed' unless CompatFfi::Raw.with_body(i, p, 'text/plain', '') + end + JSON.parse(cells['metadata']).each { |k, v| add_message_metadata_value(which, k, v) } if cells['metadata'] + if (generators = cells['generators']) + json = if generators.start_with?('JSON:') + generators.delete_prefix('JSON:').strip + else + File.read(fixture_path(generators)) + end + raise "pactffi_with_generators failed: #{CompatFfi.last_error}" unless CompatFfi::Raw.with_generators(i, p, json) + end +end + +# ---- Processing ---- + +When('the message is successfully processed') do + raise 'no pact is being defined' unless @pact + + if @sync + @received_sync = CompatFfi.sync_messages(@pact) + else + @received = CompatFfi.async_messages(@pact) + end + write_pact_from_handle(@pact) +end + +When('the message is NOT successfully processed with a {string} exception') do |error| + raise 'no pact is being defined' unless @pact + + @received = CompatFfi.async_messages(@pact) + @failed = error +end + +Then('the consumer test will have passed') do + raise "the consumer test failed with #{@failed}" if @failed +end + +Then('the consumer test will have failed') do + raise 'the consumer test passed' unless @failed +end + +Then('the consumer test error will be {string}') do |error| + raise "Expected error #{error.inspect} but was #{@failed.inspect}" unless @failed == error +end + +# ---- What the consumer received ---- + +Then(/^the received message payload will contain the "([^"]+)" (?:JSON )?document$/) do |cell| + cell = "#{cell}.json" unless cell.include?(':') + compare_document(contents_body_value(received('')), cell) +end + +Then('the received message content type will be {string}') do |expected| + actual = contents_metadata(received(''), 'contentType') + raise "Expected content type #{expected} but was #{actual.inspect}" unless actual == expected +end + +Then(/^the received message (request |response |)metadata will contain "([^"]+)" == "(.*)"$/) do |which, key, value| + actual = contents_metadata(received(which.strip), key) + expected = expected_value(value) + raise "Expected metadata #{key} = #{expected.to_json} but was #{actual.to_json}" unless actual == expected +end + +Then(/^the received message (request |response |)metadata will contain "([^"]+)" replaced with an? "([^"]+)"$/) do |which, key, kind| + which = which.strip + actual = contents_metadata(received(which), key) + originals = which == 'response' ? @response_metadata : @request_metadata + raise "metadata #{key} was not replaced: #{actual.to_json}" if originals.key?(key) && originals[key] == actual + + assert_value_type(kind, actual) +end + +Then(/^the message (request |response |)contents for "([^"]+)" will have been replaced with an? "([^"]+)"$/) do |which, path, kind| + which = which.strip + value = body_value(contents_body_value(received(which)), path) + original = which == 'response' ? @response_body : @request_body + original_value = begin + original && body_value(original, path) + rescue StandardError + nil + end + raise "#{path} was not replaced: #{value.to_json}" if !original_value.nil? && original_value == value + + assert_value_type(kind, value) +end + +# ---- The pact file ---- + +Then(/^a Pact file for the message interaction will (NOT )?have been written$/) do |negated| + exists = File.exist?(pact_file) + raise "#{pact_file} was not written" if !negated && !exists + raise "#{pact_file} was written" if negated && exists +end + +Then(/^the pact file will contain (\d+) (message )?interactions?$/) do |n, message| + key = message.nil? || @version == 'v4' ? 'interactions' : 'messages' + actual = (@pact_json[key] || []).size + raise "Expected #{n} #{key} but found #{actual}" unless actual == n.to_i +end + +Then('the first message in the pact file will contain the {string} document') do |fixture| + compare_document(first_message['contents'], fixture) +end + +Then('the first message in the pact file content type will be {string}') do |expected| + actual = (first_message['metadata'] || {})['contentType'] + raise "Expected content type #{expected} but was #{actual.inspect}" unless actual == expected +end + +Then(/^the first message in the pact file will contain the (request |)message metadata "([^"]+)" == "(.*)"$/) do |request, key, value| + message = first_message + metadata = (request.to_s.empty? ? message['metadata'] : message.dig('request', 'metadata')) || {} + expected = expected_value(value) + raise "Expected metadata #{key} = #{expected.to_json} but was #{metadata[key].to_json}" unless metadata[key] == expected +end + +Then(/^the first interaction in the pact file will contain the "([^"]+)" document as (the request|a response|the first response message|the second response message)$/) do |cell, which| + i = first_pact_interaction + contents = case which + when 'the request' then i.dig('request', 'contents') + when 'the second response message' then i.dig('response', 1, 'contents') + else i.dig('response', 0, 'contents') + end + raise "No #{which} contents in #{i.to_json}" unless contents + + compare_document(v4_content(contents), cell) +end + +Then(/^the first interaction in the pact file (request|response) content type will be "([^"]+)"$/) do |which, expected| + i = first_pact_interaction + part = which == 'request' ? i['request'] : i.dig('response', 0) + actual = part&.dig('contents', 'contentType') + raise "Expected #{which} content type #{expected} but was #{actual.inspect} in #{part.to_json}" unless actual == expected +end + +Then(/^the first interaction in the pact file will contain (\d+) response messages?$/) do |n| + actual = (first_pact_interaction['response'] || []).size + raise "Expected #{n} response messages but found #{actual}" unless actual == n.to_i +end + +Then('there will be an interaction in the Pact file with a type of {string}') do |expected| + interactions = @pact_json['interactions'] || [] + raise "No interaction of type '#{expected}' in #{interactions.to_json}" unless interactions.any? { |i| i['type'] == expected } +end diff --git a/compatibility-suite/core/support/env.rb b/compatibility-suite/core/support/env.rb new file mode 100644 index 00000000..d3364486 --- /dev/null +++ b/compatibility-suite/core/support/env.rb @@ -0,0 +1,252 @@ +# frozen_string_literal: true + +# Pact compatibility suite runner for the core (non-plugin) V1-V4 features. +# +# Run with compatibility-suite/run-core.sh (needs PACT_COMPAT_SUITE). +# The steps drive libpact_ffi (loaded the same way pact-ruby loads it) through +# the calls a client library makes, mirroring the pact-reference FFI runner. + +require 'json' +require 'base64' +require 'fileutils' +require 'tmpdir' +require 'socket' +require 'timeout' +require 'rspec/expectations' +require 'pact' +require 'pact/ffi' + +SUITE_DIR = ENV.fetch('PACT_COMPAT_SUITE', '') +FIXTURES_DIR = File.join(SUITE_DIR, 'fixtures') + +# libpact_ffi functions with pointer-friendly signatures. +module CompatFfi + REQUEST = 0 + RESPONSE = 1 + GENERATOR_BODY = 4 + + class MetadataPair < FFI::Struct + layout :key, :pointer, :value, :pointer + end + + class GeneratorPair < FFI::Struct + layout :path, :pointer, :generator, :pointer + end + + module Raw + extend FFI::Library + ffi_lib DetectOS.get_bin_path + + { + get_error_message: [%i[pointer int32], :int32], + new_pact: [%i[string string], :uint16], + with_specification: [%i[uint16 int], :bool], + new_interaction: [%i[uint16 string], :uint32], + new_message_interaction: [%i[uint16 string], :uint32], + new_sync_message_interaction: [%i[uint16 string], :uint32], + with_request: [%i[uint32 string string], :bool], + with_query_parameter_v2: [%i[uint32 string size_t string], :bool], + with_header_v2: [%i[uint32 int string size_t string], :bool], + with_matching_rules: [%i[uint32 int string], :bool], + with_generators: [%i[uint32 int string], :bool], + response_status: [%i[uint32 uint16], :bool], + with_body: [%i[uint32 int string string], :bool], + with_binary_body: [%i[uint32 int string pointer size_t], :bool], + with_metadata: [%i[uint32 string string int], :bool], + create_mock_server_for_transport: [%i[uint16 string uint16 string pointer], :int32], + mock_server_matched: [%i[int32], :bool], + mock_server_mismatches: [%i[int32], :string], + write_pact_file: [%i[int32 string bool], :int32], + cleanup_mock_server: [%i[int32], :bool], + free_pact_handle: [%i[uint16], :uint32], + given: [%i[uint32 string], :bool], + given_with_params: [%i[uint32 string string], :int32], + pact_handle_write_file: [%i[uint16 string bool], :int32], + set_pending: [%i[uint32 bool], :bool], + set_key: [%i[uint32 string], :bool], + set_comment: [%i[uint32 string string], :bool], + add_text_comment: [%i[uint32 string], :bool], + string_delete: [%i[pointer], :void], + verifier_new_for_application: [%i[string string], :pointer], + verifier_set_provider_info: [%i[pointer string string string uint16 string], :void], + verifier_set_provider_state: [%i[pointer string uint8 uint8], :void], + verifier_set_publish_options: [%i[pointer string pointer pointer int pointer], :int32], + verifier_add_custom_header: [%i[pointer string string], :void], + verifier_add_file_source: [%i[pointer string], :void], + verifier_broker_source_with_selectors: [ + %i[pointer string pointer pointer pointer uint8 pointer pointer uint16 pointer pointer uint16 pointer uint16], + :int32 + ], + verifier_execute: [%i[pointer], :int32], + verifier_json: [%i[pointer], :pointer], + verifier_output: [%i[pointer uint8], :pointer], + verifier_shutdown: [%i[pointer], :void], + message_contents_get_contents_length: [%i[pointer], :size_t], + message_contents_get_contents_bin: [%i[pointer], :pointer], + message_contents_get_metadata_iter: [%i[pointer], :pointer], + message_metadata_iter_next: [%i[pointer], :pointer], + message_metadata_pair_delete: [%i[pointer], :void], + message_metadata_iter_delete: [%i[pointer], :void], + message_contents_delete: [%i[pointer], :void], + message_contents_get_generators_iter: [%i[pointer int], :pointer], + generators_iter_next: [%i[pointer], :pointer], + generators_iter_pair_delete: [%i[pointer], :void], + generators_iter_delete: [%i[pointer], :void], + generator_generate_string: [%i[pointer string], :pointer], + pact_handle_get_async_message_iter: [%i[uint16], :pointer], + pact_async_message_iter_next: [%i[pointer], :pointer], + pact_async_message_iter_delete: [%i[pointer], :void], + async_message_generate_contents: [%i[pointer], :pointer], + async_message_get_contents: [%i[pointer], :pointer], + pact_handle_get_sync_message_iter: [%i[uint16], :pointer], + pact_sync_message_iter_next: [%i[pointer], :pointer], + pact_sync_message_iter_delete: [%i[pointer], :void], + sync_message_generate_request_contents: [%i[pointer], :pointer], + sync_message_get_number_responses: [%i[pointer], :size_t], + sync_message_generate_response_contents: [%i[pointer size_t], :pointer] + }.each do |name, (args, ret)| + # The verifier calls back into servers running on Ruby threads, so it must release the GVL. + attach_function name, :"pactffi_#{name}", args, ret, blocking: name == :verifier_execute + end + end + + # Message contents read back from the FFI: body bytes and metadata pairs. + Contents = Struct.new(:body, :metadata) do + def body_str = body&.dup&.force_encoding('UTF-8') + end + + module_function + + def last_error + buf = FFI::MemoryPointer.new(:char, 4096) + len = Raw.get_error_message(buf, 4096) + len.positive? ? buf.read_string : '' + end + + def take_string(ptr) + return nil if ptr.null? + + s = ptr.read_string.force_encoding('UTF-8') + Raw.string_delete(ptr) + s + end + + def with_binary_body(i, part, content_type, bytes) + buf = FFI::MemoryPointer.new(:uint8, [bytes.bytesize, 1].max) + buf.put_bytes(0, bytes) + Raw.with_binary_body(i, part, content_type, buf, bytes.bytesize) + end + + def read_contents(contents) + out = Contents.new(nil, []) + return out if contents.null? + + len = Raw.message_contents_get_contents_length(contents) + if len.positive? + p = Raw.message_contents_get_contents_bin(contents) + out.body = p.read_bytes(len) unless p.null? + end + iter = Raw.message_contents_get_metadata_iter(contents) + unless iter.null? + loop do + pair = Raw.message_metadata_iter_next(iter) + break if pair.null? + + s = MetadataPair.new(pair) + out.metadata << [s[:key].read_string.force_encoding('UTF-8'), s[:value].read_string.force_encoding('UTF-8')] + Raw.message_metadata_pair_delete(pair) + end + Raw.message_metadata_iter_delete(iter) + end + Raw.message_contents_delete(contents) + out + end + + def async_messages(pact) + iter = Raw.pact_handle_get_async_message_iter(pact) + return [] if iter.null? + + out = [] + loop do + m = Raw.pact_async_message_iter_next(iter) + break if m.null? + + out << read_contents(Raw.async_message_generate_contents(m)) + end + Raw.pact_async_message_iter_delete(iter) + out + end + + def sync_messages(pact) + iter = Raw.pact_handle_get_sync_message_iter(pact) + return [] if iter.null? + + out = [] + loop do + m = Raw.pact_sync_message_iter_next(iter) + break if m.null? + + request = read_contents(Raw.sync_message_generate_request_contents(m)) + n = Raw.sync_message_get_number_responses(m) + responses = (0...n).map { |idx| read_contents(Raw.sync_message_generate_response_contents(m, idx)) } + out << [request, responses] + end + Raw.pact_sync_message_iter_delete(iter) + out + end + + # Generates each body generator of the first async message with a context. + def async_body_generators_with_context(pact, context) + iter = Raw.pact_handle_get_async_message_iter(pact) + return [] if iter.null? + + out = [] + m = Raw.pact_async_message_iter_next(iter) + unless m.null? + contents = Raw.async_message_get_contents(m) + gens = Raw.message_contents_get_generators_iter(contents, GENERATOR_BODY) + unless gens.null? + loop do + pair = Raw.generators_iter_next(gens) + break if pair.null? + + s = GeneratorPair.new(pair) + path = s[:path].read_string + value = take_string(Raw.generator_generate_string(s[:generator], context)) + Raw.generators_iter_pair_delete(pair) + out << [path, value] + end + Raw.generators_iter_delete(gens) + end + end + Raw.pact_async_message_iter_delete(iter) + out + end +end + +# Scenarios that fail because of a pact_ffi limitation, not this runner. Each is skipped with the +# reason so it shows in the run instead of failing it; remove an entry once pact_ffi fixes it. +KNOWN_FAILURES = { + "Supports a not empty matcher with binary data (negative case)" => + "pact_ffi mock server reads a 0-byte request body as no body, so the notEmpty rule never sees it" +}.freeze + +Before do |scenario| + skip_this_scenario('PACT_COMPAT_SUITE is not set or has no features') if SUITE_DIR.empty? || !Dir.exist?(FIXTURES_DIR) + @version = File.basename(File.dirname(scenario.location.file)).downcase + @tmp = Dir.mktmpdir('pact-compat-') + @pact_dir = File.join(@tmp, 'pacts') + FileUtils.mkdir_p(@pact_dir) + @cleanups = [] + reason = KNOWN_FAILURES[scenario.name] + skip_this_scenario("known pact_ffi failure: #{reason}") if reason +end + +After do + @cleanups&.reverse_each do |c| + c.call + rescue StandardError + nil + end + FileUtils.rm_rf(@tmp) if @tmp +end diff --git a/compatibility-suite/core/support/helpers.rb b/compatibility-suite/core/support/helpers.rb new file mode 100644 index 00000000..33fa4e2d --- /dev/null +++ b/compatibility-suite/core/support/helpers.rb @@ -0,0 +1,67 @@ +# frozen_string_literal: true + +# State and lookups shared by the consumer, provider, message, matching and generator steps. +module CompatHelpers + ORDINALS = { 'first' => 0, 'second' => 1, 'third' => 2 }.freeze + + def consumer_name = "#{@version}-compatibility-suite-c" + def pact_file = File.join(@pact_dir, "#{consumer_name}-p.json") + + def load_pact_json + raise "No pact file found: #{pact_file}" unless File.exist?(pact_file) + + @pact_json = JSON.parse(File.read(pact_file)) + end + + def pact_interaction(nth = 'first') + list = @pact_json['interactions'] || @pact_json['messages'] || [] + list[ORDINALS.fetch(nth)] || raise("No #{nth} interaction in the pact file") + end + + def interaction_n(n) = @interactions.fetch(n.to_i - 1).deep_dup + + # A pact header lookup; values may be a string or (V4) an array of strings. + def pact_header(part, name) + v = (part['headers'] || {}).find { |k, _| k.casecmp?(name) }&.last + v.is_a?(Array) ? v.join(', ') : v + end + + # A V1 pact stores the query as a string; later formats use a map of name to values. + def pact_query(query) + case query + when String then query_map(parse_query(query)) + when Hash then query.transform_values { |v| Array(v).map(&:to_s) } + else {} + end + end + + def compare_fixture_body(body, fixture) + path = fixture_path(fixture) + if fixture.end_with?('.json') + expected = JSON.parse(File.read(path)) + raise "Expected body #{expected.to_json} but was #{body.to_json}" unless body == expected + else + expected = File.read(path) + raise "Expected body #{expected.inspect} but was #{body.inspect}" unless body == expected + end + end + + # Cells in a provider state data table are JSON values. + def json_params(rows) = rows[0].zip(rows[1]).to_h { |k, v| [k, JSON.parse(v)] } + + def new_pact(spec) + pact = CompatFfi::Raw.new_pact(consumer_name, 'p') + CompatFfi::Raw.with_specification(pact, spec) + @cleanups << -> { CompatFfi::Raw.free_pact_handle(pact) } + pact + end + + def write_pact_from_handle(pact) + rc = CompatFfi::Raw.pact_handle_write_file(pact, @pact_dir, true) + raise "pactffi_pact_handle_write_file failed with #{rc}: #{CompatFfi.last_error}" unless rc.zero? + + load_pact_json + end +end + +World(CompatHelpers, CompatServers) diff --git a/compatibility-suite/core/support/model.rb b/compatibility-suite/core/support/model.rb new file mode 100644 index 00000000..ac2defb3 --- /dev/null +++ b/compatibility-suite/core/support/model.rb @@ -0,0 +1,173 @@ +# frozen_string_literal: true + +require 'uri' +require 'rexml/document' + +# The suite's interaction tables as plain data, and how they are registered through the FFI. +# Mirrors setup_common_interactions / setup_body in the pact-reference compatibility suite. +module CompatModel + Part = Struct.new(:headers, :body, :matching_rules) do + def initialize(headers = [], body = nil, matching_rules = nil) = super + + def header(name) + headers.find { |k, _| k.casecmp?(name) }&.last + end + + def set_header(name, value) + headers.reject! { |k, _| k.casecmp?(name) } + headers << [name, value] + end + + def deep_dup = Part.new(headers.map(&:dup), body&.dup, matching_rules&.dup) + end + + Interaction = Struct.new(:description, :method, :path, :query, :request, :status, :response) do + def deep_dup = Interaction.new(description, method, path, query, request.deep_dup, status, response.deep_dup) + end + + module_function + + def fixture_path(name) = File.join(FIXTURES_DIR, name) + + # Builds interactions from a Gherkin table (array of rows) whose first row names the columns. + def setup_common_interactions(rows) + cols = rows[0].each_with_index.to_h + rows.drop(1).each_with_index.map do |values, row| + get = ->(name) { cols[name] ? (values[cols[name]] || '') : '' } + status = get.('response') + interaction = Interaction.new("Interaction #{row}", get.('method'), get.('path'), get.('query'), + Part.new, status.match?(/\A\d+\z/) ? status.to_i : 200, Part.new) + interaction.request.headers = parse_headers(get.('headers')) + setup_body(get.('body'), interaction.request) + interaction.response.headers = parse_headers(get.('response headers')) + setup_body(get.('response body'), interaction.response) + interaction.request.matching_rules = matching_rules(get.('matching rules')) + interaction.response.matching_rules = matching_rules(get.('response matching rules')) + interaction + end + end + + # A matching rules cell: a fixture file name or inline `JSON: {...}`. + def matching_rules(cell) + return nil if cell.nil? || cell.empty? + return cell.delete_prefix('JSON:').strip if cell.start_with?('JSON:') + + File.read(fixture_path(cell.strip)) + end + + # Parses `'Name: value', 'Other: value'` cells. + def parse_headers(cell) + return [] if cell.nil? || cell.empty? + + cell.split(',').filter_map do |h| + h = h.strip.delete_prefix("'").delete_suffix("'") + k, v = h.split(':', 2) + [k.strip, v.strip] if v + end + end + + # Query string to ordered [name, value] pairs, percent-decoded. + def parse_query(query) + return [] if query.nil? || query.empty? + + URI.decode_www_form(query) + end + + def query_map(pairs) + pairs.each_with_object({}) { |(k, v), map| (map[k] ||= []) << v } + end + + def setup_body(cell, part, content_type_override = nil) + return if cell.nil? || cell.empty? + + content_type, body = + if cell.start_with?('JSON:') + ['application/json', cell.delete_prefix('JSON:').strip] + elsif cell.start_with?('XML:') + ['application/xml', cell.delete_prefix('XML:').strip] + elsif cell.start_with?('file:') + file = cell.delete_prefix('file:').strip + if file.end_with?('-body.xml') + body_fixture(file) + else + [determine_content_type(file, part), File.binread(fixture_path(file))] + end + else + body = cell == 'EMPTY' ? '' : cell + [determine_content_type(body, part), body] + end + part.set_header('content-type', content_type_override || content_type) + part.body = body.b + end + + def determine_content_type(body, part) + if body.end_with?('.json') then 'application/json' + elsif body.end_with?('.xml') then 'application/xml' + elsif body.end_with?('.jpg') then 'image/jpeg' + elsif body.end_with?('.pdf') then 'application/pdf' + else part.header('content-type') || 'text/plain' + end + end + + # Reads a `*-body.xml` fixture: . + def body_fixture(file) + doc = REXML::Document.new(File.read(fixture_path(file))) + text = lambda do |name| + el = doc.root.elements[name] + next nil unless el + + s = el.texts.map { |t| t.value.strip }.join + el.attributes['eol'] == 'CRLF' ? s.gsub("\r\n", "\n").gsub("\n", "\r\n") : s + end + [text.('contentType') || 'text/plain', text.('contents') || ''] + end + + def binary?(content_type, body) + ct = content_type.downcase + ct.start_with?('image/', 'application/pdf', 'application/octet-stream') || + !body.dup.force_encoding('UTF-8').valid_encoding? + end + + def register_part(i, p, part) + index = Hash.new(0) + part.headers.each do |k, v| + # The content type travels with the body; pactffi_with_body sets the header from it. + next if part.body && k.casecmp?('content-type') + + key = k.downcase + CompatFfi::Raw.with_header_v2(i, p, k, index[key], v) + index[key] += 1 + end + if part.body + ct = part.header('content-type') || 'text/plain' + if binary?(ct, part.body) + CompatFfi.with_binary_body(i, p, ct, part.body) + else + CompatFfi::Raw.with_body(i, p, ct, part.body.dup.force_encoding('UTF-8')) + end + end + CompatFfi::Raw.with_matching_rules(i, p, part.matching_rules) if part.matching_rules + end + + # Adds one HTTP interaction to the pact with the calls a client library would make. + def register(pact, interaction) + i = CompatFfi::Raw.new_interaction(pact, interaction.description) + CompatFfi::Raw.with_request(i, interaction.method, interaction.path) + index = Hash.new(0) + parse_query(interaction.query).each do |k, v| + CompatFfi::Raw.with_query_parameter_v2(i, k, index[k], v) + index[k] += 1 + end + register_part(i, CompatFfi::REQUEST, interaction.request) + CompatFfi::Raw.response_status(i, interaction.status) + register_part(i, CompatFfi::RESPONSE, interaction.response) + i + end + + HTTP_SPEC = { 'v1' => 1, 'v2' => 3, 'v3' => 4, 'v4' => 5 }.freeze + + def http_spec(version) = HTTP_SPEC.fetch(version) + def message_spec(version) = version == 'v4' ? 5 : 4 +end + +World(CompatModel) diff --git a/compatibility-suite/core/support/servers.rb b/compatibility-suite/core/support/servers.rb new file mode 100644 index 00000000..2e99bc76 --- /dev/null +++ b/compatibility-suite/core/support/servers.rb @@ -0,0 +1,130 @@ +# frozen_string_literal: true + +require 'net/http' + +# A minimal recording HTTP/1.1 server, used as the provider under test, the provider state +# callback and a stand-in Pact broker. Each connection serves one request and closes. Written +# on a raw socket (not WEBrick) so responses carry exactly the headers and bytes the steps set. +module CompatServers + Request = Struct.new(:method, :path, :headers, :body) do + def header(name) = headers.find { |k, _| k.casecmp?(name) }&.last + def path_only = path.split('?').first + end + + Response = Struct.new(:status, :headers, :body) do + def self.json(status, value) + new(status, [%w[Content-Type application/json]], JSON.dump(value)) + end + end + + class Server + attr_reader :port + + # The handler gets (request, port) and returns a Response. + def initialize(&handler) + @server = TCPServer.new('127.0.0.1', 0) + @port = @server.addr[1] + @requests = [] + @lock = Mutex.new + @thread = Thread.new do + loop do + client = @server.accept + Thread.new(client) { |c| serve(c, handler) } + end + rescue IOError, SystemCallError + nil + end + end + + def url = "http://127.0.0.1:#{@port}" + def requests = @lock.synchronize { @requests.dup } + + def stop + @server.close + @thread.kill + end + + private + + def serve(client, handler) + req = read_request(client) + return unless req + + res = begin + handler.call(req, @port) + rescue StandardError => e + Response.new(500, [], "#{e.class}: #{e.message}") + end + @lock.synchronize { @requests << req } + client.write(encode(res)) + rescue IOError, SystemCallError + nil + ensure + client.close + end + + def read_request(client) + line = client.gets("\r\n") or return nil + method, path = line.split(' ') + headers = [] + while (l = client.gets("\r\n")) && l != "\r\n" + k, v = l.chomp("\r\n").split(':', 2) + headers << [k.strip, v.to_s.strip] + end + len = headers.find { |k, _| k.casecmp?('content-length') }&.last.to_i + body = len.positive? ? client.read(len) : +'' + Request.new(method, path, headers, body.b) + end + + def encode(res) + out = +"HTTP/1.1 #{res.status} X\r\n" + res.headers.each { |k, v| out << "#{k}: #{v}\r\n" } + body = (res.body || '').b + out << "Content-Length: #{body.bytesize}\r\nConnection: close\r\n\r\n" + out.b + body + end + end + + module_function + + ClientResponse = Struct.new(:status, :headers, :body) do + def header(name) = headers.find { |k, _| k.casecmp?(name) }&.last + end + + # Sends a request with exactly the given headers ([name, value] pairs) over a raw socket: + # Net::HTTP would add Accept, User-Agent and a default Content-Type the scenarios do not expect. + def http_request(port, method, path, headers, body) + Socket.tcp('127.0.0.1', port, connect_timeout: 5) do |sock| + out = +"#{method.upcase} #{path} HTTP/1.1\r\nHost: 127.0.0.1:#{port}\r\n" + headers.each { |k, v| out << "#{k}: #{v}\r\n" } + out << "Content-Length: #{body.bytesize}\r\n" if body + out << "Connection: close\r\n\r\n" + sock.write(out.b + (body || '').b) + Timeout.timeout(10) { read_response(sock) } + end + end + + def read_response(sock) + status = sock.gets("\r\n").split(' ')[1].to_i + headers = [] + while (l = sock.gets("\r\n")) && l != "\r\n" + k, v = l.chomp("\r\n").split(':', 2) + headers << [k.strip, v.to_s.strip] + end + find = ->(n) { headers.find { |k, _| k.casecmp?(n) }&.last } + body = + if find.('transfer-encoding')&.casecmp?('chunked') + buf = +'' + while (size = sock.gets("\r\n").to_i(16)).positive? + buf << sock.read(size) + sock.read(2) + end + buf + elsif find.('content-length') + sock.read(find.('content-length').to_i) + else + sock.read + end + ClientResponse.new(status, headers, (body || '').b) + end +end diff --git a/compatibility-suite/run-core.sh b/compatibility-suite/run-core.sh new file mode 100755 index 00000000..f8e6a8d0 --- /dev/null +++ b/compatibility-suite/run-core.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# Runs the core (non-plugin) pact-compatibility-suite V1-V4 features against pact-ruby. +# +# PACT_COMPAT_SUITE=/path/to/pact-compatibility-suite compatibility-suite/run-core.sh [cucumber args] +# +# CUCUMBER_FORMAT (default: progress) picks the formatter. +# Skips (exit 0) when PACT_COMPAT_SUITE is unset or has no features. +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +SUITE="${PACT_COMPAT_SUITE:-}" + +if [[ -z "$SUITE" || ! -d "$SUITE/features/V1" ]]; then + echo "Skipping core compatibility suite: PACT_COMPAT_SUITE is unset or has no features" + exit 0 +fi + +FEATURES=( + V1/http_consumer V1/http_provider + V2/http_consumer V2/http_provider + V3/http_consumer V3/http_provider V3/message_consumer V3/message_provider + V3/generators V3/http_generators V3/http_matching V3/matching_rules + V4/http_consumer V4/http_provider V4/message_consumer V4/message_provider + V4/synchronous_message_consumer V4/generators V4/matching_rules V4/v4 +) +PATHS=() +for f in "${FEATURES[@]}"; do + [[ -f "$SUITE/features/$f.feature" ]] && PATHS+=("$SUITE/features/$f.feature") +done + +cd "$ROOT" +export CUCUMBER_PUBLISH_QUIET=true +exec bundle exec cucumber "${PATHS[@]}" \ + --require compatibility-suite/core \ + --tags 'not @wip' \ + --format "${CUCUMBER_FORMAT:-progress}" \ + "$@"