From 87aa036068233438c716be1c0e67b67b039513bc Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Thu, 29 Oct 2026 18:25:12 +0000 Subject: [PATCH 1/2] test: add compatibility suite runner for V4 plugin features Runs the pact-compatibility-suite features/V4/plugins scenarios with cucumber via compatibility-suite/run-plugins.sh (skips when PACT_COMPAT_SUITE is unset). Each scenario uses the pact-ruby DSL where it can express the scenario and falls back to the FFI bindings otherwise; per-feature DSL/FFI counts are printed at the end. Co-Authored-By: Claude Opus 5.5 --- Gemfile | 4 + .../plugins/step_definitions/plugin_steps.rb | 400 ++++++++++++++++++ compatibility-suite/plugins/support/env.rb | 91 ++++ .../plugins/support/servers.rb | 164 +++++++ compatibility-suite/plugins/support/world.rb | 238 +++++++++++ compatibility-suite/run-plugins.sh | 25 ++ 6 files changed, 922 insertions(+) create mode 100644 compatibility-suite/plugins/step_definitions/plugin_steps.rb create mode 100644 compatibility-suite/plugins/support/env.rb create mode 100644 compatibility-suite/plugins/support/servers.rb create mode 100644 compatibility-suite/plugins/support/world.rb create mode 100755 compatibility-suite/run-plugins.sh 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/plugins/step_definitions/plugin_steps.rb b/compatibility-suite/plugins/step_definitions/plugin_steps.rb new file mode 100644 index 00000000..d0436f21 --- /dev/null +++ b/compatibility-suite/plugins/step_definitions/plugin_steps.rb @@ -0,0 +1,400 @@ +# frozen_string_literal: true + +# ---- plugin installation / lifecycle --------------------------------------- + +Given('the {string} plugin version {string} is installed') do |name, version| + dir = File.join(PLUGIN_DIR, "#{name}-#{version}") + raise "plugin #{name} #{version} is not installed in #{PLUGIN_DIR}" unless Dir.exist?(dir) + + installed[name] = version +end + +Given('the {string} plugin is not installed') do |name| + expect(Dir.glob(File.join(PLUGIN_DIR, "#{name}-*"))).to be_empty +end + +When('the {string} plugin is loaded for the test') do |name| + load_plugin(name, nil) +end + +When('the {string} plugin version {string} is loaded for the test') do |name, version| + load_plugin(name, version) +end + +# The DSL can't express a version-less plugin and masks PluginInitError behind a +# NoMethodError in its ensure block, so plugin loading goes through the FFI. +def load_plugin(name, version) + @path = :ffi + handle = ffi_new_pact + @load_rc = begin + PactFfi::PluginConsumer.using_plugin(handle, name, version) + rescue StandardError => e + @load_panic = e + -1 + end + @load_error = "#{CompatFfi.last_error} (rc=#{@load_rc})" +end + +Then('loading the plugin will fail with an error that mentions {string}') do |text| + expect(@load_rc).not_to eq(0) + expect(@load_error).to include(text) +end + +Then('the test will not have panicked') do + expect(@load_panic).to be_nil + expect(@load_error.downcase).not_to include('panic') +end + +When('the plugins are cleaned up') do + PactFfi::PluginConsumer.cleanup_plugins(@pact_handle) +end + +Then('no {string} plugin process will still be running') do |name| + pattern = File.join(PLUGIN_DIR, "#{name}-") + deadline = Time.now + 10 + running = true + while Time.now < deadline + # Only plugin processes started by this runner (its children) count. + running = !`pgrep -P #{Process.pid} -f #{pattern.shellescape}`.strip.empty? + break unless running + + sleep 0.2 + end + expect(running).to be(false) +end + +# ---- consumer: defining interactions --------------------------------------- + +Given('an HTTP interaction is being defined for a consumer test') do + interactions << { kind: :http, plugins: [] } +end + +Given('another HTTP interaction is being defined for the same consumer test') do + interactions << { kind: :http, plugins: [] } +end + +Given('a message interaction is being defined for a consumer test') do + interactions << { kind: :message, plugins: [] } +end + +Given('a synchronous message interaction is being defined for a consumer test') do + interactions << { kind: :sync, plugins: [] } +end + +Given('the HTTP request is {string} {string}') do |method, path| + current[:method] = method + current[:path] = path +end + +Given('the HTTP request body is set with the {string} plugin for {string} with:') do |plugin, ct, text| + current[:plugins] << plugin + current[:request_plugin] = { name: plugin, content_type: ct, contents: plugin_contents(text) } +end + +Given('the HTTP response body is set with the {string} plugin for {string} with:') do |plugin, ct, text| + current[:plugins] << plugin + current[:response_plugin] = { name: plugin, content_type: ct, contents: plugin_contents(text) } +end + +Given('the HTTP response body is {string} with content type {string}') do |body, ct| + current[:response_body] = body_cell(body) + current[:response_content_type] = ct +end + +Given(/^the (?:synchronous )?message contents are set with the "([^"]*)" plugin for "([^"]*)" with:$/) do |plugin, ct, text| + current[:plugins] << plugin + current[:contents_plugin] = { name: plugin, content_type: ct, contents: plugin_contents(text) } +end + +# ---- consumer: generating the pact ----------------------------------------- + +When('the Pact file for the test is generated') do + spec = current + if interactions.size == 1 && spec[:kind] == :message + # DSL: MessageInteractionBuilder#with_plugin / #with_plugin_contents + @path = :dsl + c = spec[:contents_plugin] + config = Pact::Consumer::PactConfig.new(:message, consumer_name: PluginWorld::CONSUMER, + provider_name: PluginWorld::PROVIDER, opts: { pact_dir: @tmp }) + config.new_interaction('plugin message') + .with_plugin(c[:name], plugin_version(c[:name])) + .with_plugin_contents(c[:content_type], JSON.parse(c[:contents])) + .execute { |_payload, _meta| nil } + else + # FFI: the HTTP / sync DSL builders always start a mock server and can't just write a pact. + @path = :ffi + @pact_handle = ffi_build_pact + contents_ok!(PactFfi.pact_handle_write_file(@pact_handle, @tmp, false), 'pact_handle_write_file') + end +end + +When('the mock server is started with the plugin interaction') do + spec = current + req = spec[:request_plugin] + res = spec[:response_plugin] + if req && res + # DSL: PluginHttpInteractionBuilder (needs plugin bodies on both request and response). + @path = :dsl + config = Pact::Consumer::PactConfig.new(:plugin_http, consumer_name: PluginWorld::CONSUMER, + provider_name: PluginWorld::PROVIDER, opts: { pact_dir: @tmp, mock_port: CompatServers.fresh_mock_port }) + builder = config.new_interaction('plugin interaction 1') + .with_plugin(req[:name], plugin_version(req[:name])) + .with_request(method: spec[:method], path: spec[:path], + headers: { 'content-type' => req[:content_type] }, body: req[:contents]) + .will_respond_with(status: 200, headers: { 'content-type' => res[:content_type] }, + body: res[:contents]) + dsl_start(builder) + else + # FFI: the DSL can't build a response-only plugin body. + @path = :ffi + ffi_start_mock(ffi_build_pact, 'http') + end +end + +When('the mock server is started with all the interactions') do + # FFI: the DSL builders hold a single interaction per pact handle. + @path = :ffi + ffi_start_mock(ffi_build_pact, 'http') +end + +When('a mock server is started for the {string} transport') do |transport| + # DSL: PluginSyncMessageInteractionBuilder#with_transport + @path = :dsl + c = current[:contents_plugin] + contents = JSON.parse(c[:contents]) + request = contents.delete('request') + response = contents.delete('response') + config = Pact::Consumer::PactConfig.new(:plugin_sync_message, consumer_name: PluginWorld::CONSUMER, + provider_name: PluginWorld::PROVIDER, + opts: { pact_dir: @tmp, mock_port: CompatServers.fresh_mock_port }) + builder = config.new_interaction('plugin interaction 1') + .with_plugin(c[:name], plugin_version(c[:name])) + .with_content_type(c[:content_type]) + .with_request(request) + .will_respond_with(response) + .with_transport(transport) + builder.with_plugin_metadata(contents) unless contents.empty? + dsl_start(builder) +end + +When(/^a "([^"]*)" request is made to "([^"]*)"(?: with content type "([^"]*)" and body "([^"]*)")?$/) do |method, path, ct, body| + @response = CompatServers.http_request(@mock_port, method, path, ct, body && body_cell(body)) +end + +Then('a 200 success response is returned') do + expect(@response.code).to eq('200') +end + +Then('the response body will be {string}') do |expected| + want = body_cell(expected) + got = @response.body.to_s + if got.b == want.b + expect(got.b).to eq(want.b) + else + expect(JSON.parse(got)).to eq(JSON.parse(want)) + end +end + +When('the line {string} is sent to the mock server over TCP') do |line| + @tcp_reply = CompatServers.tcp_line(@mock_port, line) +end + +Then('the line {string} will be received from the mock server') do |line| + expect(@tcp_reply).to eq(line) +end + +When('the gRPC method {string} is called on the mock server with {string}') do |method, body| + @grpc_result = CompatServers.grpc_call(@mock_port, method, body_cell(body)) +end + +When('the gRPC method {string} is called on the mock server with an empty message') do |method| + @grpc_result = CompatServers.grpc_call(@mock_port, method, '') +end + +Then('the gRPC call will return {string}') do |expected| + status, reply = @grpc_result + expect(status).to eq(:ok), "gRPC call failed: #{reply.inspect}" + expect(reply.b).to eq(body_cell(expected).b) +end + +Then('the gRPC call will fail with status {string}') do |code| + status, error = @grpc_result + expect(status).to eq(:error) + expect(GRPC::Core::StatusCodes.constants.find { |c| GRPC::Core::StatusCodes.const_get(c) == error.code }.to_s) + .to eq(code) +end + +When('the pact test is done') do + pact_test_done +end + +Then('the mock server status will be OK') do + expect(@matched).to be(true), "mismatches: #{@mismatches}" +end + +Then('the mock server status will be mismatches') do + expect(@matched).to be(false) +end + +Then('the mismatches will contain a mismatch with error {string}') do |error| + parsed = begin + JSON.parse(@mismatches.to_s) + rescue JSON::ParserError + @mismatches.to_s + end + expect(contains_text?(parsed, error)).to be(true), "#{error.inspect} not found in #{@mismatches}" +end + +Then('the mock server will write out a Pact file for the interaction when done') do + expect(File.exist?(pact_file)).to be(true), "no pact written (matched=#{@matched}, reply=#{@tcp_reply.inspect}, mismatches=#{@mismatches})" +end + +# ---- consumer: pact file checks -------------------------------------------- + +Then(/^the Pact file metadata will list the "([^"]*)" plugin with version "([^"]*)"$/) do |name, version| + plugins = pact_json.dig('metadata', 'plugins') || [] + expect(plugins.any? { |p| p['name'] == name && p['version'] == version }).to be(true), plugins.inspect +end + +Then('the first interaction in the Pact file will have a type of {string}') do |type| + expect(first_interaction['type']).to eq(type) +end + +Then(/^the first interaction in the pact file (request |response |contents |)content type will be "([^"]*)"$/) do |part, ct| + part = part.strip.empty? ? 'contents' : part.strip + expect(part_contents(part_of(first_interaction, part))['contentType']).to eq(ct) +end + +Then(/^the first interaction in the pact file (request |response |contents |)contents will be "([^"]*)"$/) do |part, text| + part = part.strip.empty? ? 'contents' : part.strip + expect(decoded_content(part_contents(part_of(first_interaction, part)))).to eq(text) +end + +Then(/^the first interaction (request|response|contents) in the pact file will have a matching rule for "([^"]*)" of type "([^"]*)"$/) do |part, key, type| + rules = part_of(first_interaction, part).dig('matchingRules', 'body', key, 'matchers') || [] + expect(rules.map { |m| m['match'] }).to include(type) +end + +Then('the first interaction in the pact file will have plugin configuration for {string}') do |name| + expect(first_interaction['pluginConfiguration'] || {}).to have_key(name) +end + +Then('the second interaction in the pact file will not have plugin configuration') do + expect(pact_json['interactions'][1]['pluginConfiguration'] || {}).to be_empty +end + +Then('the pact file will contain {int} interactions') do |count| + expect(pact_json['interactions'].size).to eq(count) +end + +Then('the first interaction in the pact file will contain {int} response message') do |count| + expect(first_interaction['response'].size).to eq(count) +end + +Then(/^the first interaction in the Pact file will have "([^"]*)" = '(.*)'$/) do |key, json| + value = first_interaction[key] + value = value.split('/').last if key == 'transport' && value.is_a?(String) + expect(value).to eq(JSON.parse(json)) +end + +# ---- provider verification ------------------------------------------------- + +Given('a Pact file with an HTTP {string} {string} interaction with plugin contents:') do |method, path, table| + write_provider_pact(:http, table.hashes.first, method: method, path: path) + @provider_kind = :http +end + +Given('a Pact file with a {string} message interaction with plugin contents:') do |name, table| + write_provider_pact(:message, table.hashes.first, description: name) + @provider_kind = :message +end + +Given('a Pact file with a {string} synchronous message interaction with plugin contents:') do |name, table| + write_provider_pact(:sync, table.hashes.first, description: name) + @provider_kind = :message +end + +Given('a Pact file with a {string} synchronous message interaction over the {string} transport with plugin contents:') do |name, transport, table| + write_provider_pact(:sync, table.hashes.first, description: name, transport: transport) + @provider_kind = :transport +end + +Given('a provider is started that returns {string} with content type {string}') do |body, ct| + @provider_body = body_cell(body) + @provider_ct = ct +end + +Given('a provider is started that can generate the {string} message with {string} and content type {string}') do |name, body, ct| + server, @provider_port = CompatServers.message_provider(name, body_cell(body), ct) + @cleanups << -> { server.shutdown } +end + +Given('a TCP provider is started that replies to {string} with {string}') do |expected, reply| + server, thread, @provider_port = CompatServers.tcp_provider(expected, reply) + @cleanups << lambda { + server.close + thread.kill + } +end + +Given('a gRPC provider is started that answers {string} with {string}') do |method, body| + server, @provider_port = CompatServers.grpc_provider(method, body_cell(body)) + @cleanups << -> { server.stop } +end + +Given('no provider is listening') do + @provider_port = CompatServers.free_port +end + +When('the verification is run') do + if @provider_kind == :http + run_http_verification + else + @path = :ffi # the message verifier DSL only serves JSON from Ruby handlers and hides output + ffi_verify(@provider_port) + end +end + +# DSL: HttpVerifier with a Rack app. It only reports pass/fail (no output or JSON +# results), so a failing run is repeated through the FFI verifier for diagnostics. +def run_http_verification + config = Pact::Provider::PactConfig.new( + :http, provider_name: PluginWorld::PROVIDER, + opts: { http_port: CompatServers.free_port, provider_setup_port: CompatServers.free_port, + app: CompatServers.rack_provider(@provider_body, @provider_ct), pact_uri: @provider_pact, + consumer_name: PluginWorld::CONSUMER, log_level: :error } + ) + config.new_verifier.verify! + @path = :dsl + @verified = true +rescue Pact::Provider::BaseVerifier::VerificationError + @path = :ffi + server, port = CompatServers.http_provider(@provider_body, @provider_ct) + @cleanups << -> { server.shutdown } + ffi_verify(port) +end + +When('the verification is run with the {string} transport') do |transport| + # FFI: the provider DSL has no generic plugin-transport verifier. + @path = :ffi + ffi_verify(@provider_port, transport, @provider_port) +end + +Then('the verification will be successful') do + expect(@verified).to be(true), "verification failed:\n#{@verify_output}" +end + +Then('the verification will NOT be successful') do + expect(@verified).to be(false) +end + +Then('the verification results will contain a {string} error') do |error| + types = { 'Body had differences' => %w[BodyMismatch BodyTypeMismatch], + 'Metadata had differences' => %w[MetadataMismatch] }.fetch(error) + found = collect_values(@verify_results, 'type') + expect(found & types).not_to be_empty, "mismatch types #{found.uniq.inspect}" +end + +Then('the verification output will contain {string}') do |text| + expect(@verify_output).to include(text) +end diff --git a/compatibility-suite/plugins/support/env.rb b/compatibility-suite/plugins/support/env.rb new file mode 100644 index 00000000..d72aaf36 --- /dev/null +++ b/compatibility-suite/plugins/support/env.rb @@ -0,0 +1,91 @@ +# frozen_string_literal: true + +# Pact compatibility suite runner for the V4 plugin features. +# +# Run with compatibility-suite/run-plugins.sh (needs PACT_COMPAT_SUITE). +# Each scenario records whether its main action went through the pact-ruby DSL +# or fell back to the raw FFI bindings; a summary is printed at the end. + +require 'json' +require 'base64' +require 'fileutils' +require 'tmpdir' +require 'shellwords' +require 'socket' +require 'timeout' +require 'rspec/expectations' +require 'pact' +require 'pact/ffi' +require 'grpc' + +# The plugin builders name the failing RSpec example in mismatch errors; outside +# rspec-core there is no current example, so provide a nil one. +module RSpec + def self.current_example = nil +end unless RSpec.respond_to?(:current_example) + +SUITE_DIR = ENV.fetch('PACT_COMPAT_SUITE', '') +FIXTURES_DIR = File.join(SUITE_DIR, 'fixtures') +PLUGIN_DIR = ENV['PACT_PLUGIN_DIR'] || File.join(Dir.home, '.pact', 'plugins') + +# FFI functions the runner needs with pointer-friendly signatures. +module CompatFfi + module Raw + extend FFI::Library + ffi_lib DetectOS.get_bin_path + attach_function :get_error_message, :pactffi_get_error_message, %i[pointer int32], :int32 + end +end + +module CompatFfi + def self.last_error + buf = FFI::MemoryPointer.new(:char, 4096) + len = Raw.get_error_message(buf, 4096) + len.positive? ? buf.read_string : '' + end +end + +# Tracks which path (DSL or FFI) each scenario took. +module PathTracker + RESULTS = Hash.new { |h, k| h[k] = Hash.new(0) } + NOTES = [] + + def self.record(feature, path) + RESULTS[feature][path] += 1 + end + + def self.report + return if RESULTS.empty? + + lines = ['', 'DSL vs FFI per feature file:'] + RESULTS.sort.each do |feature, counts| + lines << format(' %-28s DSL=%-3d FFI=%-3d', feature, counts[:dsl], counts[:ffi]) + end + lines << format(' %-28s DSL=%-3d FFI=%-3d', 'TOTAL', RESULTS.values.sum { |c| c[:dsl] }, + RESULTS.values.sum { |c| c[:ffi] }) + puts lines.join("\n") + File.write(ENV['PACT_COMPAT_PATH_REPORT'], JSON.pretty_generate(RESULTS)) if ENV['PACT_COMPAT_PATH_REPORT'] + end +end + +at_exit { PathTracker.report } + +Before do |scenario| + if SUITE_DIR.empty? || !Dir.exist?(File.join(SUITE_DIR, 'features', 'V4', 'plugins')) + skip_this_scenario('PACT_COMPAT_SUITE is not set or has no features/V4/plugins') + end + @feature = File.basename(scenario.location.file, '.feature') + @tmp = Dir.mktmpdir('pact-compat-') + @path = nil + @cleanups = [] +end + +After do |scenario| + @cleanups&.reverse_each do |c| + c.call + rescue StandardError + nil + end + FileUtils.rm_rf(@tmp) if @tmp + PathTracker.record(@feature, @path || :ffi) unless scenario.status == :skipped +end diff --git a/compatibility-suite/plugins/support/servers.rb b/compatibility-suite/plugins/support/servers.rb new file mode 100644 index 00000000..cf967a76 --- /dev/null +++ b/compatibility-suite/plugins/support/servers.rb @@ -0,0 +1,164 @@ +# frozen_string_literal: true + +require 'webrick' +require 'net/http' +require 'logger' + +# Test providers and clients used by the plugin steps. +module CompatServers + module_function + + def free_port + s = TCPServer.new('127.0.0.1', 0) + port = s.addr[1] + s.close + port + end + + USED_MOCK_PORTS = [] + + # A free port no earlier mock server in this run has used. The matt plugin keeps + # per-port mock server state after cleanup, so a reused port inherits old mismatches. + def fresh_mock_port + port = free_port + port = free_port while USED_MOCK_PORTS.include?(port) + USED_MOCK_PORTS << port + port + end + + def quiet_webrick(port = 0) + WEBrick::HTTPServer.new(BindAddress: '127.0.0.1', Port: port, Logger: WEBrick::Log.new(File::NULL), + AccessLog: []) + end + + def start_webrick(server) + Thread.new { server.start } + [server, server.listeners.first.addr[1]] + end + + # HTTP provider that returns a fixed body for any request. + def http_provider(body, content_type) + server = quiet_webrick + server.mount_proc('/') do |_req, res| + res.status = 200 + res['Content-Type'] = content_type + res.body = body + end + start_webrick(server) + end + + # Rack app equivalent of http_provider, for the DSL HttpVerifier. + def rack_provider(body, content_type) + ->(_env) { [200, { 'content-type' => content_type }, [body]] } + end + + # Message provider: answers the verifier's POST for the named message. + def message_provider(name, body, content_type) + server = quiet_webrick + server.mount_proc('/') do |req, res| + desc = begin + JSON.parse(req.body || '{}')['description'] + rescue JSON::ParserError + nil + end + if req.request_method == 'POST' && desc == name + res.status = 200 + res['Content-Type'] = content_type + res['Pact-Message-Metadata'] = Base64.strict_encode64(JSON.dump({ 'contentType' => content_type })) + res.body = body + else + res.status = 404 + end + end + start_webrick(server) + end + + # Line-based TCP provider for the matt transport. + def tcp_provider(expected, reply) + server = TCPServer.new('127.0.0.1', 0) + thread = Thread.new do + loop do + client = server.accept + Thread.new(client) do |c| + while (line = c.gets) + c.write("#{line.chomp == expected ? reply : 'MATTerrorMATT'}\n") + end + rescue IOError, SystemCallError + nil + ensure + c.close + end + end + rescue IOError, SystemCallError + nil + end + [server, thread, server.addr[1]] + end + + # Passes raw protobuf bytes through the grpc gem untouched. + class RawBytes + attr_reader :data + + def initialize(data) = @data = data + def self.encode(obj) = obj.is_a?(RawBytes) ? obj.data : obj + def self.decode(bytes) = bytes + def self.marshal(obj) = encode(obj) + def self.unmarshal(bytes) = bytes + end + + # gRPC provider answering a single unary method with fixed bytes. + def grpc_provider(method_path, reply) + service_name, rpc_name = method_path.delete_prefix('/').split('/') + handler = rpc_name.gsub(/([a-z])([A-Z])/, '\1_\2').downcase + service = Class.new do + include GRPC::GenericService + + self.service_name = service_name + rpc rpc_name.to_sym, CompatServers::RawBytes, CompatServers::RawBytes + define_method(handler) { |_req, _call| CompatServers::RawBytes.new(reply) } + end + server = GRPC::RpcServer.new(pool_size: 2) + port = server.add_http2_port('127.0.0.1:0', :this_port_is_insecure) + server.handle(service) + Thread.new { server.run } + server.wait_till_running(10) + [server, port] + end + + # The pact gRPC mock server listens on ::1 only; prefer 127.0.0.1 if reachable. + def local_host_for(port) + TCPSocket.new('127.0.0.1', port).close + '127.0.0.1' + rescue SystemCallError + '[::1]' + end + + def grpc_call(port, method_path, request) + stub = GRPC::ClientStub.new("#{local_host_for(port)}:#{port}", :this_channel_is_insecure) + reply = stub.request_response(method_path, request, RawBytes.method(:encode), RawBytes.method(:decode), + deadline: Time.now + 10) + [:ok, reply] + rescue GRPC::BadStatus => e + [:error, e] + end + + def tcp_line(port, line) + host = local_host_for(port).delete('[]') + Socket.tcp(host, port, connect_timeout: 5) do |sock| + sock.write("#{line}\n") + sock.close_write + Timeout.timeout(10) { sock.gets&.chomp } + end + end + + def http_request(port, method, path, content_type = nil, body = nil) + Net::HTTP.start('127.0.0.1', port, read_timeout: 10) do |http| + req = Net::HTTPGenericRequest.new(method, !body.nil?, true, path) + if body + req['Content-Type'] = content_type if content_type + req.body = body + end + http.request(req) + end + end +end diff --git a/compatibility-suite/plugins/support/world.rb b/compatibility-suite/plugins/support/world.rb new file mode 100644 index 00000000..be9ec50d --- /dev/null +++ b/compatibility-suite/plugins/support/world.rb @@ -0,0 +1,238 @@ +# frozen_string_literal: true + +# Scenario state and helpers shared by the plugin step definitions. +module PluginWorld + CONSUMER = 'c' + PROVIDER = 'p' + V4 = PactFfi::FfiSpecificationVersion['SPECIFICATION_VERSION_V4'] + + def installed + @installed ||= {} + end + + def interactions + @interactions ||= [] + end + + def current + interactions.last + end + + def body_cell(value) + value.start_with?('file: ') ? File.binread(File.join(FIXTURES_DIR, value.delete_prefix('file: '))) : value + end + + def plugin_contents(text) + text.gsub('"fixture:', "\"#{FIXTURES_DIR}/") + end + + def plugin_version(name) + installed.fetch(name) { raise "plugin #{name} has not been declared as installed" } + end + + def pact_file + File.join(@tmp, "#{CONSUMER}-#{PROVIDER}.json") + end + + def pact_json + @pact_json ||= JSON.parse(File.read(pact_file)) + end + + def first_interaction + pact_json['interactions'][0] + end + + def part_of(interaction, part) + value = part == 'contents' ? interaction : interaction[part] + value.is_a?(Array) ? value[0] : value + end + + def part_contents(part) + part['contents'] || part['body'] + end + + def decoded_content(contents) + contents['encoded'] == 'base64' ? Base64.decode64(contents['content']) : contents['content'] + end + + def contains_text?(value, text) + case value + when String then value.include?(text) + when Array then value.any? { |v| contains_text?(v, text) } + when Hash then value.any? { |k, v| contains_text?(k, text) || contains_text?(v, text) } + else false + end + end + + def collect_values(value, key, acc = []) + case value + when Array then value.each { |v| collect_values(v, key, acc) } + when Hash + value.each do |k, v| + acc << v if k == key && v.is_a?(String) + collect_values(v, key, acc) + end + end + acc + end + + def check_ffi(ok, what) + raise "#{what} failed: #{CompatFfi.last_error}" unless ok + end + + def contents_ok!(rc, what) + raise "#{what} failed (#{rc}): #{CompatFfi.last_error}" unless rc.zero? + end + + # ---- FFI pact building ------------------------------------------------- + + def ffi_new_pact + handle = PactFfi.new_pact(CONSUMER, PROVIDER) + PactFfi.with_specification(handle, V4) + @cleanups << lambda { + PactFfi::PluginConsumer.cleanup_plugins(handle) + PactFfi.free_pact_handle(handle) + } + handle + end + + def ffi_use_plugins(handle, names) + names.uniq.each do |name| + rc = PactFfi::PluginConsumer.using_plugin(handle, name, plugin_version(name)) + contents_ok!(rc, "using_plugin(#{name})") + end + end + + def ffi_add_interaction(handle, spec, index) + desc = spec[:description] || "plugin interaction #{index + 1}" + case spec[:kind] + when :http + i = PactFfi.new_interaction(handle, desc) + check_ffi(PactFfi.with_request(i, spec[:method] || 'GET', spec[:path] || '/'), 'with_request') + if (req = spec[:request_plugin]) + contents_ok!(PactFfi::PluginConsumer.interaction_contents(i, 0, req[:content_type], req[:contents]), + 'request interaction_contents') + end + if (res = spec[:response_plugin]) + contents_ok!(PactFfi::PluginConsumer.interaction_contents(i, 1, res[:content_type], res[:contents]), + 'response interaction_contents') + elsif spec[:response_body] + check_ffi(PactFfi.with_body(i, 1, spec[:response_content_type], spec[:response_body]), 'with_body') + end + when :message, :sync + i = spec[:kind] == :message ? PactFfi.new_message_interaction(handle, desc) : PactFfi.new_sync_message_interaction(handle, desc) + c = spec[:contents_plugin] + contents_ok!(PactFfi::PluginConsumer.interaction_contents(i, 0, c[:content_type], c[:contents]), + 'interaction_contents') + end + i + end + + def ffi_build_pact + handle = ffi_new_pact + ffi_use_plugins(handle, interactions.flat_map { |s| s[:plugins] }) + interactions.each_with_index { |spec, idx| ffi_add_interaction(handle, spec, idx) } + handle + end + + # ---- consumer mock servers --------------------------------------------- + + # DSL: the builder's execute block spans several steps, so run it in a Fiber. + def dsl_start(builder) + @fiber = Fiber.new do + builder.execute { |*args| Fiber.yield(args.last) } + :done + end + @dsl_mock = @fiber.resume + @mock_port = @dsl_mock.port + @cleanups << -> { finish_dsl_mock } + end + + def finish_dsl_mock + return unless @fiber&.alive? + + @fiber.resume + rescue Pact::Consumer::PluginHttpInteractionBuilder::InteractionMismatchesError, + Pact::Consumer::PluginSyncMessageInteractionBuilder::InteractionMismatchesError => e + @dsl_error = e + # The DSL raises before cleaning up on mismatches, so release what it left behind. + # MockServer#cleanup_plugins/#free_pact_handle pass the mock server port rather than + # the pact handle, so use the pact handle directly. + @dsl_mock.cleanup + pact = @dsl_mock.instance_variable_get(:@pact) + PactFfi::PluginConsumer.cleanup_plugins(pact) + PactFfi.free_pact_handle(pact) + end + + def ffi_start_mock(handle, transport) + port = PactFfi::MockServer.create_for_transport(handle, '127.0.0.1', CompatServers.fresh_mock_port, transport, nil) + raise "create_mock_server_for_transport failed (#{port}): #{CompatFfi.last_error}" unless port.positive? + + @ffi_mock = port + @mock_port = port + @cleanups << -> { PactFfi::MockServer.cleanup(port) } + end + + def pact_test_done + if @dsl_mock + @matched = @dsl_mock.matched? + @mismatches = @dsl_mock.mismatches + finish_dsl_mock + elsif @ffi_mock + @matched = PactFfi::MockServer.matched(@ffi_mock) + @mismatches = PactFfi::MockServer.mismatches(@ffi_mock) + PactFfi::MockServer.write_pact_file(@ffi_mock, @tmp, false) if @matched + else + raise 'no mock server was started' + end + end + + # ---- provider verification --------------------------------------------- + + def write_provider_pact(kind, row, description: nil, method: nil, path: nil, transport: nil) + dir = File.join(@tmp, 'pacts') + FileUtils.mkdir_p(dir) + handle = PactFfi.new_pact(CONSUMER, PROVIDER) + PactFfi.with_specification(handle, V4) + ffi_use_plugins(handle, [row['plugin']]) + spec = { kind: kind, description: description, method: method, path: path } + ct = row['content type'] + if kind == :http + spec[:request_plugin] = { content_type: ct, contents: plugin_contents(row['request']) } if row['request'] + spec[:response_plugin] = { content_type: ct, contents: plugin_contents(row['response']) } if row['response'] + else + spec[:contents_plugin] = { content_type: ct, contents: plugin_contents(row['contents']) } + end + ffi_add_interaction(handle, spec, 0) + contents_ok!(PactFfi.pact_handle_write_file(handle, dir, false), 'pact_handle_write_file') + PactFfi::PluginConsumer.cleanup_plugins(handle) + PactFfi.free_pact_handle(handle) + file = File.join(dir, "#{CONSUMER}-#{PROVIDER}.json") + if transport + json = JSON.parse(File.read(file)) + json['interactions'][0]['transport'] = transport + File.write(file, JSON.dump(json)) + end + @provider_pact = file + end + + def ffi_verify(port, transport = nil, transport_port = nil) + handle = PactFfi::Verifier.new_for_application('pact-ruby-compat', PactFfi.version) + PactFfi::Verifier.set_provider_info(handle, PROVIDER, 'http', '127.0.0.1', port, '/') + if transport + PactFfi::Verifier.add_provider_transport(handle, transport, transport_port, '/', + transport == 'grpc' ? 'http' : 'tcp') + end + PactFfi::Verifier.add_file_source(handle, @provider_pact) + rc = Pact::Native::BlockingVerifier.execute(handle) + @verify_rc = rc + @verify_output = PactFfi::Verifier.output(handle, 0).to_s.gsub(/\e\[[0-9;]*m/, '') + json = PactFfi::Verifier.json(handle) + @verify_results = json && !json.empty? ? JSON.parse(json) : {} + @verified = rc.zero? && @verify_results['result'] == true + ensure + PactFfi::Verifier.shutdown(handle) if handle + end +end + +World(PluginWorld) diff --git a/compatibility-suite/run-plugins.sh b/compatibility-suite/run-plugins.sh new file mode 100755 index 00000000..8476de62 --- /dev/null +++ b/compatibility-suite/run-plugins.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Runs the pact-compatibility-suite V4 plugin features against pact-ruby. +# +# PACT_COMPAT_SUITE=/path/to/pact-compatibility-suite compatibility-suite/run-plugins.sh [cucumber args] +# +# CUCUMBER_FORMAT (default: progress) picks the formatter. PACT_COMPAT_PATH_REPORT= +# writes the per-feature DSL/FFI path counts as JSON. +# Skips (exit 0) when PACT_COMPAT_SUITE is unset or has no features/V4/plugins. +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +FEATURES="${PACT_COMPAT_SUITE:-}/features/V4/plugins" + +if [[ -z "${PACT_COMPAT_SUITE:-}" || ! -d "$FEATURES" ]]; then + echo "Skipping plugin compatibility suite: PACT_COMPAT_SUITE is unset or has no features/V4/plugins" + exit 0 +fi + +cd "$ROOT" +export CUCUMBER_PUBLISH_QUIET=true +exec bundle exec cucumber "$FEATURES" \ + --require compatibility-suite/plugins \ + --tags 'not @wip' \ + --format "${CUCUMBER_FORMAT:-progress}" \ + "$@" From a1529b957da5098b6b14483db6753b51d924b8d6 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Thu, 29 Oct 2026 19:32:47 +0000 Subject: [PATCH 2/2] ci: run the V4 plugin compatibility features Adds a workflow that checks out the suite branch with features/V4/plugins (YOU54F/pact-compatibility-suite#1), installs the matt, csv, avro and protobuf plugins with the Pact CLI, and runs compatibility-suite/run-plugins.sh. It runs on PRs to any base. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/compat-plugins.yml | 56 ++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 .github/workflows/compat-plugins.yml diff --git a/.github/workflows/compat-plugins.yml b/.github/workflows/compat-plugins.yml new file mode 100644 index 00000000..03df0a4e --- /dev/null +++ b/.github/workflows/compat-plugins.yml @@ -0,0 +1,56 @@ +name: Compatibility suite (V4 plugins) + +# The V4 plugin features are not in a released suite yet, so this checks out +# the suite branch that adds them and runs compatibility-suite/run-plugins.sh +# against it. It runs on PRs to any base, unlike test.yml. +on: + push: + branches: + - master + pull_request: + workflow_dispatch: + inputs: + suite-repository: + description: pact-compatibility-suite repository with features/V4/plugins + default: YOU54F/pact-compatibility-suite + suite-ref: + description: Ref of that repository to run + default: feat/plugin-features + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + PACT_DO_NOT_TRACK: 'true' + SUITE_REPOSITORY: ${{ inputs.suite-repository || 'YOU54F/pact-compatibility-suite' }} + SUITE_REF: ${{ inputs.suite-ref || 'feat/plugin-features' }} + +jobs: + plugins: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - name: Checkout plugin suite + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + repository: ${{ env.SUITE_REPOSITORY }} + ref: ${{ env.SUITE_REF }} + path: pact-compatibility-suite-plugins + - uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.4" + bundler-cache: true + - uses: pact-foundation/pact-cli@575a793b515ad65718cfb81198b3a4634dc8f72d # main + # matt is not in the plugin repository index, so it is installed from its release. + - run: pact plugin install --yes https://github.com/mefellows/pact-matt-plugin/releases/tag/v0.1.1 + - run: pact plugin install --yes csv --version 0.0.6 + - run: pact plugin install --yes avro --version 0.1.3 + - run: pact plugin install --yes protobuf --version 0.8.0 + - name: Run plugin features + run: compatibility-suite/run-plugins.sh + env: + PACT_COMPAT_SUITE: ${{ github.workspace }}/pact-compatibility-suite-plugins