From 08161882a24edd8ec1165a210d41d9ae9314c3e6 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Fri, 16 Oct 2026 16:46:08 +0100 Subject: [PATCH 01/15] chore(ffi): upgrade to libpact_ffi 0.5.12 Update native library downloads and refresh Rust version metadata in integration fixtures and the Orders API sample pact. Retain existing repeated-header expectations and pact representations. --- build/download-native-libs.sh | 2 +- .../Consumer.Tests/pacts/Fulfilment API-Orders API.json | 4 ++-- tests/PactNet.Tests/data/v2-consumer-integration.json | 4 ++-- tests/PactNet.Tests/data/v3-consumer-integration.json | 4 ++-- tests/PactNet.Tests/data/v3-message-consumer-integration.json | 4 ++-- tests/PactNet.Tests/data/v3-message-integration.json | 4 ++-- tests/PactNet.Tests/data/v3-server-integration.json | 4 ++-- tests/PactNet.Tests/data/v4-combined-integration.json | 4 ++-- tests/PactNet.Tests/data/v4-consumer-integration.json | 4 ++-- tests/PactNet.Tests/data/v4-message-consumer-integration.json | 4 ++-- 10 files changed, 19 insertions(+), 19 deletions(-) diff --git a/build/download-native-libs.sh b/build/download-native-libs.sh index c3ace891..0e3f275a 100755 --- a/build/download-native-libs.sh +++ b/build/download-native-libs.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -FFI_VERSION="0.4.27" +FFI_VERSION="0.5.12" FFI_BASE_URL="https://github.com/pact-foundation/pact-reference/releases/download/libpact_ffi-v$FFI_VERSION" GREEN="\e[32m" diff --git a/samples/OrdersApi/Consumer.Tests/pacts/Fulfilment API-Orders API.json b/samples/OrdersApi/Consumer.Tests/pacts/Fulfilment API-Orders API.json index b6f1a702..d65ccb80 100644 --- a/samples/OrdersApi/Consumer.Tests/pacts/Fulfilment API-Orders API.json +++ b/samples/OrdersApi/Consumer.Tests/pacts/Fulfilment API-Orders API.json @@ -158,8 +158,8 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.12", + "models": "1.3.17" }, "pactSpecification": { "version": "4.0" diff --git a/tests/PactNet.Tests/data/v2-consumer-integration.json b/tests/PactNet.Tests/data/v2-consumer-integration.json index 9484eef4..b1477514 100644 --- a/tests/PactNet.Tests/data/v2-consumer-integration.json +++ b/tests/PactNet.Tests/data/v2-consumer-integration.json @@ -74,8 +74,8 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.12", + "models": "1.3.17" }, "pactSpecification": { "version": "2.0.0" diff --git a/tests/PactNet.Tests/data/v3-consumer-integration.json b/tests/PactNet.Tests/data/v3-consumer-integration.json index b220eb49..920fa486 100644 --- a/tests/PactNet.Tests/data/v3-consumer-integration.json +++ b/tests/PactNet.Tests/data/v3-consumer-integration.json @@ -130,8 +130,8 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.12", + "models": "1.3.17" }, "pactSpecification": { "version": "3.0.0" diff --git a/tests/PactNet.Tests/data/v3-message-consumer-integration.json b/tests/PactNet.Tests/data/v3-message-consumer-integration.json index 494ea225..c998c718 100644 --- a/tests/PactNet.Tests/data/v3-message-consumer-integration.json +++ b/tests/PactNet.Tests/data/v3-message-consumer-integration.json @@ -36,8 +36,8 @@ "language": "C#" }, "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.12", + "models": "1.3.17" }, "pactSpecification": { "version": "3.0.0" diff --git a/tests/PactNet.Tests/data/v3-message-integration.json b/tests/PactNet.Tests/data/v3-message-integration.json index 4a3ace22..088f09f6 100644 --- a/tests/PactNet.Tests/data/v3-message-integration.json +++ b/tests/PactNet.Tests/data/v3-message-integration.json @@ -16,8 +16,8 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.12", + "models": "1.3.17" }, "pactSpecification": { "version": "3.0.0" diff --git a/tests/PactNet.Tests/data/v3-server-integration.json b/tests/PactNet.Tests/data/v3-server-integration.json index c5050bd5..5c745396 100644 --- a/tests/PactNet.Tests/data/v3-server-integration.json +++ b/tests/PactNet.Tests/data/v3-server-integration.json @@ -46,8 +46,8 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.12", + "models": "1.3.17" }, "pactSpecification": { "version": "3.0.0" diff --git a/tests/PactNet.Tests/data/v4-combined-integration.json b/tests/PactNet.Tests/data/v4-combined-integration.json index 61808511..0eebe956 100644 --- a/tests/PactNet.Tests/data/v4-combined-integration.json +++ b/tests/PactNet.Tests/data/v4-combined-integration.json @@ -185,8 +185,8 @@ "language": "C#" }, "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.12", + "models": "1.3.17" }, "pactSpecification": { "version": "4.0" diff --git a/tests/PactNet.Tests/data/v4-consumer-integration.json b/tests/PactNet.Tests/data/v4-consumer-integration.json index 87ef562b..32a8d9d9 100644 --- a/tests/PactNet.Tests/data/v4-consumer-integration.json +++ b/tests/PactNet.Tests/data/v4-consumer-integration.json @@ -150,8 +150,8 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.12", + "models": "1.3.17" }, "pactSpecification": { "version": "4.0" diff --git a/tests/PactNet.Tests/data/v4-message-consumer-integration.json b/tests/PactNet.Tests/data/v4-message-consumer-integration.json index 8861180b..3ed2b1af 100644 --- a/tests/PactNet.Tests/data/v4-message-consumer-integration.json +++ b/tests/PactNet.Tests/data/v4-message-consumer-integration.json @@ -41,8 +41,8 @@ "language": "C#" }, "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.12", + "models": "1.3.17" }, "pactSpecification": { "version": "4.0" From aa18dc5122b110173be76d114f969c17d96ae03d Mon Sep 17 00:00:00 2001 From: Fabio Rodrigues Date: Thu, 24 Sep 2026 15:43:49 +0100 Subject: [PATCH 02/15] feat: add consumer-side support for synchronous (request/response) messages PactNet already supports writing asynchronous (fire-and-forget) message pacts, but had no way to write V4 synchronous message pacts (used by e.g. AsyncAPI 3 operations with a reply block), even though the underlying pact_ffi native library already exposes pactffi_new_sync_message_interaction and can set request/response bodies and metadata on it via the existing generic pactffi_with_body/pactffi_with_metadata functions. This adds: - IPactV4.WithSynchronousMessageInteractions() entry point - ISyncMessagePactBuilderV4 / ISyncMessageBuilderV4 / IConfiguredSyncMessageVerifier public API, mirroring the existing async IMessagePactBuilderV4 API - SyncMessageInteractionDriver, wiring the above onto the native FFI calls The consumer-side Verify reads the generated request contents (matchers stripped, generators applied) via the new pactffi_sync_message_reify FFI function and feeds it to the handler under test; the response content is stored but not currently asserted against, matching the existing async message Verify semantics. Depends on pactffi_sync_message_reify, proposed in https://github.com/pact-foundation/pact-reference/pull/555. Until that lands in a released pact_ffi build, calling ConfiguredSyncMessageVerifier.Verify will fail with EntryPointNotFoundException - the corresponding FFI integration test is marked Skip until then. --- .../IConfiguredSyncMessageVerifier.cs | 23 +++ .../ISyncMessageBuilder.cs | 72 ++++++++ .../ISyncMessagePactBuilder.cs | 24 +++ src/PactNet/ConfiguredSyncMessageVerifier.cs | 99 +++++++++++ src/PactNet/Drivers/IMessagePactDriver.cs | 7 + .../Drivers/ISyncMessageInteractionDriver.cs | 43 +++++ src/PactNet/Drivers/MessagePactDriver.cs | 11 ++ .../Drivers/SyncMessageInteractionDriver.cs | 84 +++++++++ src/PactNet/Interop/NativeInterop.cs | 9 + src/PactNet/Models/NativeSyncMessage.cs | 18 ++ src/PactNet/PactExtensions.cs | 16 ++ src/PactNet/SyncMessageBuilder.cs | 165 ++++++++++++++++++ src/PactNet/SyncMessagePactBuilder.cs | 65 +++++++ .../ConfiguredSyncMessageVerifierTests.cs | 139 +++++++++++++++ .../Drivers/FfiIntegrationTests.cs | 34 ++++ .../PactNet.Tests/SyncMessageBuilderTests.cs | 134 ++++++++++++++ .../SyncMessagePactBuilderTests.cs | 79 +++++++++ 17 files changed, 1022 insertions(+) create mode 100644 src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs create mode 100644 src/PactNet.Abstractions/ISyncMessageBuilder.cs create mode 100644 src/PactNet.Abstractions/ISyncMessagePactBuilder.cs create mode 100644 src/PactNet/ConfiguredSyncMessageVerifier.cs create mode 100644 src/PactNet/Drivers/ISyncMessageInteractionDriver.cs create mode 100644 src/PactNet/Drivers/SyncMessageInteractionDriver.cs create mode 100644 src/PactNet/Models/NativeSyncMessage.cs create mode 100644 src/PactNet/SyncMessageBuilder.cs create mode 100644 src/PactNet/SyncMessagePactBuilder.cs create mode 100644 tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs create mode 100644 tests/PactNet.Tests/SyncMessageBuilderTests.cs create mode 100644 tests/PactNet.Tests/SyncMessagePactBuilderTests.cs diff --git a/src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs b/src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs new file mode 100644 index 00000000..40000bc6 --- /dev/null +++ b/src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs @@ -0,0 +1,23 @@ +using System; +using System.Threading.Tasks; + +namespace PactNet +{ + /// + /// A configured synchronous (request/response) message type state, which can now be verified + /// + public interface IConfiguredSyncMessageVerifier + { + /// + /// Verify a request message is read and handled correctly + /// + /// The method handling the request message and producing a response + void Verify(Func handler); + + /// + /// Verify a request message is read and handled correctly + /// + /// The method handling the request message and producing a response + Task VerifyAsync(Func> handler); + } +} diff --git a/src/PactNet.Abstractions/ISyncMessageBuilder.cs b/src/PactNet.Abstractions/ISyncMessageBuilder.cs new file mode 100644 index 00000000..9b748cb2 --- /dev/null +++ b/src/PactNet.Abstractions/ISyncMessageBuilder.cs @@ -0,0 +1,72 @@ +using System.Collections.Generic; +using System.Text.Json; + +namespace PactNet +{ + /// + /// Build up a mock synchronous (request/response) message for a v4 message pact + /// + public interface ISyncMessageBuilderV4 + { + /// + /// Add a provider state + /// + /// Provider state description + /// Fluent builder + ISyncMessageBuilderV4 Given(string providerState); + + /// + /// Add a provider state with one or more parameters + /// + /// Provider state description + /// Provider state parameters + /// Fluent builder + ISyncMessageBuilderV4 Given(string providerState, IDictionary parameters); + + /// + /// Set the request metadata + /// + /// the metadata key + /// the metadata value + /// Fluent builder + ISyncMessageBuilderV4 WithRequestMetadata(string key, string value); + + /// + /// Set the response metadata + /// + /// the metadata key + /// the metadata value + /// Fluent builder + ISyncMessageBuilderV4 WithResponseMetadata(string key, string value); + + /// + /// Set the request content which is serialised as JSON + /// + /// Request body + /// Fluent builder + ISyncMessageBuilderV4 WithRequestJsonContent(dynamic body); + + /// + /// Set the request content which is serialised as JSON + /// + /// Request body + /// Custom JSON serializer settings + /// Fluent builder + ISyncMessageBuilderV4 WithRequestJsonContent(dynamic body, JsonSerializerOptions settings); + + /// + /// Set the response content which is serialised as JSON + /// + /// Response body + /// Configured message + IConfiguredSyncMessageVerifier WithResponseJsonContent(dynamic body); + + /// + /// Set the response content which is serialised as JSON + /// + /// Response body + /// Custom JSON serializer settings + /// Configured message + IConfiguredSyncMessageVerifier WithResponseJsonContent(dynamic body, JsonSerializerOptions settings); + } +} diff --git a/src/PactNet.Abstractions/ISyncMessagePactBuilder.cs b/src/PactNet.Abstractions/ISyncMessagePactBuilder.cs new file mode 100644 index 00000000..140e9ac0 --- /dev/null +++ b/src/PactNet.Abstractions/ISyncMessagePactBuilder.cs @@ -0,0 +1,24 @@ +namespace PactNet +{ + /// + /// Synchronous (request/response) message pact v4 Builder + /// + public interface ISyncMessagePactBuilderV4 + { + /// + /// Add a new synchronous message to the pact + /// + /// Message description + /// Fluent builder + ISyncMessageBuilderV4 ExpectsToReceive(string description); + + /// + /// Add metadata information to message pact + /// + /// the parent configuration section + /// the metadata field value + /// the metadata field value + /// Fluent builder + ISyncMessagePactBuilderV4 WithPactMetadata(string @namespace, string name, string value); + } +} diff --git a/src/PactNet/ConfiguredSyncMessageVerifier.cs b/src/PactNet/ConfiguredSyncMessageVerifier.cs new file mode 100644 index 00000000..58fcaa60 --- /dev/null +++ b/src/PactNet/ConfiguredSyncMessageVerifier.cs @@ -0,0 +1,99 @@ +using System; +using System.Text.Json; +using System.Threading.Tasks; +using PactNet.Drivers; +using PactNet.Exceptions; +using PactNet.Interop; +using PactNet.Models; + +namespace PactNet +{ + /// + /// Verifies a configured synchronous (request/response) message interaction + /// + internal class ConfiguredSyncMessageVerifier : IConfiguredSyncMessageVerifier + { + // the native message returned from the FFI always uses camel case property + // names, but the inner content may use different settings supplied by the user + private static readonly JsonSerializerOptions NativeMessageSettings = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + private readonly ISyncMessageInteractionDriver driver; + private readonly PactConfig config; + private readonly PactSpecification version; + + /// + /// Initialises a new instance of the + /// + /// Pact driver + /// Pact configuration + /// Pact specification version + internal ConfiguredSyncMessageVerifier(ISyncMessageInteractionDriver driver, PactConfig config, PactSpecification version) + { + this.driver = driver; + this.config = config; + this.version = version; + } + + /// + /// Verify a request message is read and handled correctly and write the message pact + /// + /// The method handling the request message and producing a response + public void Verify(Func handler) + { + try + { + TRequest requestReified = this.RequestReified(); + + handler(requestReified); + + this.driver.WritePactFile(this.config.PactDir); + } + catch (Exception e) + { + throw new PactMessageConsumerVerificationException($"The message could not be verified by the consumer handler", e); + } + } + + /// + /// Verify a request message is read and handled correctly and write the message pact + /// + /// The method handling the request message and producing a response + public async Task VerifyAsync(Func> handler) + { + try + { + TRequest requestReified = this.RequestReified(); + + await handler(requestReified); + + this.driver.WritePactFile(this.config.PactDir); + } + catch (Exception e) + { + throw new PactMessageConsumerVerificationException($"The message could not be verified by the consumer handler", e); + } + } + + /// + /// Try to read the reified request message + /// + /// the type of the request message + /// the request message + private TRequest RequestReified() + { + string reified = this.driver.Reify(); + NativeSyncMessage content = JsonSerializer.Deserialize(reified, NativeMessageSettings); + + // Synchronous messages only exist in the V4 Pact format, so the reified contents + // always use the V4 body envelope (a `content` field) + string contentString = ((JsonElement)content.Request.Contents).GetProperty("content").GetRawText(); + + TRequest requestReified = JsonSerializer.Deserialize(contentString, this.config.DefaultJsonSettings); + + return requestReified; + } + } +} diff --git a/src/PactNet/Drivers/IMessagePactDriver.cs b/src/PactNet/Drivers/IMessagePactDriver.cs index 4999226a..51f16adb 100644 --- a/src/PactNet/Drivers/IMessagePactDriver.cs +++ b/src/PactNet/Drivers/IMessagePactDriver.cs @@ -12,6 +12,13 @@ internal interface IMessagePactDriver /// Message interaction driver IMessageInteractionDriver NewMessageInteraction(string description); + /// + /// Create a new synchronous (request/response) message interaction on the current pact + /// + /// Interaction description + /// Synchronous message interaction driver + ISyncMessageInteractionDriver NewSyncMessageInteraction(string description); + /// /// Add metadata to the message pact /// diff --git a/src/PactNet/Drivers/ISyncMessageInteractionDriver.cs b/src/PactNet/Drivers/ISyncMessageInteractionDriver.cs new file mode 100644 index 00000000..f1747fae --- /dev/null +++ b/src/PactNet/Drivers/ISyncMessageInteractionDriver.cs @@ -0,0 +1,43 @@ +namespace PactNet.Drivers +{ + /// + /// Driver for synchronous (request/response) message interactions + /// + internal interface ISyncMessageInteractionDriver : IProviderStateDriver, ICompletedPactDriver + { + /// + /// Set the metadata of the request message + /// + /// the key + /// the value + void WithRequestMetadata(string key, string value); + + /// + /// Set the metadata of the response message + /// + /// the key + /// the value + void WithResponseMetadata(string key, string value); + + /// + /// Set the contents of the request message + /// + /// the content type + /// the body of the request message + void WithRequestContents(string contentType, string body); + + /// + /// Set the contents of the response message + /// + /// the content type + /// the body of the response message + void WithResponseContents(string contentType, string body); + + /// + /// Returns the request and response contents without the matchers, with any configured + /// generators applied + /// + /// Reified message + string Reify(); + } +} diff --git a/src/PactNet/Drivers/MessagePactDriver.cs b/src/PactNet/Drivers/MessagePactDriver.cs index 11b99c39..6e62a839 100644 --- a/src/PactNet/Drivers/MessagePactDriver.cs +++ b/src/PactNet/Drivers/MessagePactDriver.cs @@ -29,6 +29,17 @@ public IMessageInteractionDriver NewMessageInteraction(string description) return new MessageInteractionDriver(this.pact, interaction); } + /// + /// Create a new synchronous (request/response) message interaction on the current pact + /// + /// Interaction description + /// Synchronous message interaction driver + public ISyncMessageInteractionDriver NewSyncMessageInteraction(string description) + { + InteractionHandle interaction = NativeInterop.NewSyncMessageInteraction(this.pact, description); + return new SyncMessageInteractionDriver(this.pact, interaction); + } + /// /// Add metadata to the message pact /// diff --git a/src/PactNet/Drivers/SyncMessageInteractionDriver.cs b/src/PactNet/Drivers/SyncMessageInteractionDriver.cs new file mode 100644 index 00000000..92ea5fbb --- /dev/null +++ b/src/PactNet/Drivers/SyncMessageInteractionDriver.cs @@ -0,0 +1,84 @@ +using System; +using System.Runtime.InteropServices; +using PactNet.Interop; + +namespace PactNet.Drivers +{ + /// + /// Driver for synchronous (request/response) message interactions + /// + internal class SyncMessageInteractionDriver : AbstractPactDriver, ISyncMessageInteractionDriver + { + private readonly InteractionHandle interaction; + + /// + /// Initialises a new instance of the class. + /// + /// Pact handle + /// Interaction handle + internal SyncMessageInteractionDriver(PactHandle pact, InteractionHandle interaction) : base(pact) + { + this.interaction = interaction; + } + + /// + /// Add a provider state to the interaction + /// + /// Provider state description + public void Given(string description) + => NativeInterop.Given(this.interaction, description).CheckInteropSuccess(); + + /// + /// Add a provider state with a parameter to the interaction + /// + /// Provider state description + /// Parameter name + /// Parameter value + public void GivenWithParam(string description, string name, string value) + => NativeInterop.GivenWithParam(this.interaction, description, name, value).CheckInteropSuccess(); + + /// + /// Set the metadata of the request message + /// + /// the key + /// the value + public void WithRequestMetadata(string key, string value) + => NativeInterop.WithMetadata(this.interaction, key, value, InteractionPart.Request).CheckInteropSuccess(); + + /// + /// Set the metadata of the response message + /// + /// the key + /// the value + public void WithResponseMetadata(string key, string value) + => NativeInterop.WithMetadata(this.interaction, key, value, InteractionPart.Response).CheckInteropSuccess(); + + /// + /// Set the contents of the request message + /// + /// the content type + /// the body of the request message + public void WithRequestContents(string contentType, string body) + => NativeInterop.WithBody(this.interaction, InteractionPart.Request, contentType, body).CheckInteropSuccess(); + + /// + /// Set the contents of the response message + /// + /// the content type + /// the body of the response message + public void WithResponseContents(string contentType, string body) + => NativeInterop.WithBody(this.interaction, InteractionPart.Response, contentType, body).CheckInteropSuccess(); + + /// + /// Returns the request and response contents without the matchers, with any configured + /// generators applied + /// + /// Reified message + public string Reify() + { + IntPtr pointer = NativeInterop.SyncMessageReify(this.interaction); + string body = Marshal.PtrToStringAnsi(pointer); + return body; + } + } +} diff --git a/src/PactNet/Interop/NativeInterop.cs b/src/PactNet/Interop/NativeInterop.cs index 92bdc911..5f0c02f9 100644 --- a/src/PactNet/Interop/NativeInterop.cs +++ b/src/PactNet/Interop/NativeInterop.cs @@ -91,6 +91,15 @@ internal static class NativeInterop [DllImport(DllName, EntryPoint = "pactffi_message_reify")] public static extern IntPtr MessageReify(InteractionHandle message); + [DllImport(DllName, EntryPoint = "pactffi_new_sync_message_interaction")] + public static extern InteractionHandle NewSyncMessageInteraction(PactHandle pact, string description); + + [DllImport(DllName, EntryPoint = "pactffi_with_metadata")] + public static extern bool WithMetadata(InteractionHandle interaction, string key, string value, InteractionPart part); + + [DllImport(DllName, EntryPoint = "pactffi_sync_message_reify")] + public static extern IntPtr SyncMessageReify(InteractionHandle message); + #endregion Http Interop Support #region Verifier Support diff --git a/src/PactNet/Models/NativeSyncMessage.cs b/src/PactNet/Models/NativeSyncMessage.cs new file mode 100644 index 00000000..e8cd6ea6 --- /dev/null +++ b/src/PactNet/Models/NativeSyncMessage.cs @@ -0,0 +1,18 @@ +namespace PactNet.Models +{ + /// + /// Placeholder for a native synchronous (request/response) message from the backend + /// + internal class NativeSyncMessage + { + /// + /// The request message + /// + public NativeMessage Request { get; set; } + + /// + /// The response messages + /// + public NativeMessage[] Response { get; set; } + } +} diff --git a/src/PactNet/PactExtensions.cs b/src/PactNet/PactExtensions.cs index 32aa358f..fc7a84d9 100644 --- a/src/PactNet/PactExtensions.cs +++ b/src/PactNet/PactExtensions.cs @@ -114,6 +114,22 @@ public static IMessagePactBuilderV4 WithMessageInteractions(this IPactV4 pact) return builder; } + /// + /// Add synchronous (request/response) message (i.e. AsyncAPI request/reply) interactions to the pact + /// + /// Pact details + /// Pact builder + public static ISyncMessagePactBuilderV4 WithSynchronousMessageInteractions(this IPactV4 pact) + { + InitialiseLogging(pact.Config.LogLevel); + + IPactDriver driver = new PactDriver(); + IMessagePactDriver messagePact = driver.NewMessagePact(pact.Consumer, pact.Provider, PactSpecification.V4); + + var builder = new SyncMessagePactBuilder(messagePact, pact.Config, PactSpecification.V4); + return builder; + } + /// /// Initialise logging in the native library /// diff --git a/src/PactNet/SyncMessageBuilder.cs b/src/PactNet/SyncMessageBuilder.cs new file mode 100644 index 00000000..94470da8 --- /dev/null +++ b/src/PactNet/SyncMessageBuilder.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using System.Text.Json; +using PactNet.Drivers; +using PactNet.Interop; + +namespace PactNet +{ + /// + /// Mock synchronous (request/response) message builder + /// + internal class SyncMessageBuilder : ISyncMessageBuilderV4 + { + private readonly ISyncMessageInteractionDriver driver; + private readonly PactConfig config; + private readonly PactSpecification version; + + /// + /// Initialises a new instance of the class. + /// + /// Interaction driver + /// Pact config + /// Pact specification version + internal SyncMessageBuilder(ISyncMessageInteractionDriver driver, PactConfig config, PactSpecification version) + { + this.driver = driver ?? throw new ArgumentNullException(nameof(driver)); + this.config = config; + this.version = version; + } + + #region ISyncMessageBuilderV4 explicit implementation + + /// + ISyncMessageBuilderV4 ISyncMessageBuilderV4.Given(string providerState) + => Given(providerState); + + /// + ISyncMessageBuilderV4 ISyncMessageBuilderV4.Given(string providerState, IDictionary parameters) + => Given(providerState, parameters); + + /// + ISyncMessageBuilderV4 ISyncMessageBuilderV4.WithRequestMetadata(string key, string value) + => WithRequestMetadata(key, value); + + /// + ISyncMessageBuilderV4 ISyncMessageBuilderV4.WithResponseMetadata(string key, string value) + => WithResponseMetadata(key, value); + + /// + ISyncMessageBuilderV4 ISyncMessageBuilderV4.WithRequestJsonContent(dynamic body) + => WithRequestJsonContent(body); + + /// + ISyncMessageBuilderV4 ISyncMessageBuilderV4.WithRequestJsonContent(dynamic body, JsonSerializerOptions settings) + => WithRequestJsonContent(body, settings); + + /// + IConfiguredSyncMessageVerifier ISyncMessageBuilderV4.WithResponseJsonContent(dynamic body) + => WithResponseJsonContent(body); + + /// + IConfiguredSyncMessageVerifier ISyncMessageBuilderV4.WithResponseJsonContent(dynamic body, JsonSerializerOptions settings) + => WithResponseJsonContent(body, settings); + + #endregion + + /// + /// Add a provider state + /// + /// Provider state description + /// Fluent builder + internal SyncMessageBuilder Given(string providerState) + { + this.driver.Given(providerState); + + return this; + } + + /// + /// Add a provider state with one or more parameters + /// + /// Provider state description + /// Provider state parameters + /// Fluent builder + internal SyncMessageBuilder Given(string providerState, IDictionary parameters) + { + foreach (var param in parameters) + { + this.driver.GivenWithParam(providerState, param.Key, param.Value); + } + + return this; + } + + /// + /// Set the request metadata + /// + /// key of the metadata + /// value of the metadata + /// Fluent builder + internal SyncMessageBuilder WithRequestMetadata(string key, string value) + { + this.driver.WithRequestMetadata(key, value); + + return this; + } + + /// + /// Set the response metadata + /// + /// key of the metadata + /// value of the metadata + /// Fluent builder + internal SyncMessageBuilder WithResponseMetadata(string key, string value) + { + this.driver.WithResponseMetadata(key, value); + + return this; + } + + /// + /// Set a request body which is serialised as JSON + /// + /// Request body + /// Fluent builder + internal SyncMessageBuilder WithRequestJsonContent(dynamic body) => WithRequestJsonContent(body, this.config.DefaultJsonSettings); + + /// + /// Set a request body which is serialised as JSON + /// + /// Request body + /// Custom JSON serializer settings + /// Fluent builder + internal SyncMessageBuilder WithRequestJsonContent(dynamic body, JsonSerializerOptions settings) + { + string serialised = JsonSerializer.Serialize(body, settings); + + this.driver.WithRequestContents("application/json", serialised); + + return this; + } + + /// + /// Set a response body which is serialised as JSON + /// + /// Response body + /// Configured message + internal ConfiguredSyncMessageVerifier WithResponseJsonContent(dynamic body) => WithResponseJsonContent(body, this.config.DefaultJsonSettings); + + /// + /// Set a response body which is serialised as JSON + /// + /// Response body + /// Custom JSON serializer settings + /// Configured message + internal ConfiguredSyncMessageVerifier WithResponseJsonContent(dynamic body, JsonSerializerOptions settings) + { + string serialised = JsonSerializer.Serialize(body, settings); + + this.driver.WithResponseContents("application/json", serialised); + + return new ConfiguredSyncMessageVerifier(this.driver, this.config, this.version); + } + } +} diff --git a/src/PactNet/SyncMessagePactBuilder.cs b/src/PactNet/SyncMessagePactBuilder.cs new file mode 100644 index 00000000..e9c7a692 --- /dev/null +++ b/src/PactNet/SyncMessagePactBuilder.cs @@ -0,0 +1,65 @@ +using System; +using PactNet.Drivers; +using PactNet.Interop; + +namespace PactNet +{ + /// + /// Mock synchronous (request/response) message pact builder + /// + internal class SyncMessagePactBuilder : ISyncMessagePactBuilderV4 + { + private readonly IMessagePactDriver driver; + private readonly PactConfig config; + private readonly PactSpecification version; + + /// + /// Initialises a new instance of the class. + /// + /// Pact driver + /// the message pact configuration + /// Pact specification version + internal SyncMessagePactBuilder(IMessagePactDriver pact, PactConfig config, PactSpecification version) + { + this.driver = pact ?? throw new ArgumentNullException(nameof(pact)); + this.config = config ?? throw new ArgumentNullException(nameof(config)); + this.version = version; + } + + #region ISyncMessagePactBuilderV4 explicit implementation + + /// + ISyncMessageBuilderV4 ISyncMessagePactBuilderV4.ExpectsToReceive(string description) + => ExpectsToReceive(description); + + /// + ISyncMessagePactBuilderV4 ISyncMessagePactBuilderV4.WithPactMetadata(string @namespace, string name, string value) + => WithPactMetadata(@namespace, name, value); + + #endregion + + /// + /// Add a new synchronous message to the message pact + /// + /// Message description + /// Fluent builder + internal SyncMessageBuilder ExpectsToReceive(string description) + { + ISyncMessageInteractionDriver messageDriver = this.driver.NewSyncMessageInteraction(description); + return new SyncMessageBuilder(messageDriver, this.config, this.version); + } + + /// + /// Add a new metadata to the message pact + /// + /// the parent configuration section + /// the metadata field value + /// the metadata field value + /// Fluent builder + internal SyncMessagePactBuilder WithPactMetadata(string @namespace, string name, string value) + { + this.driver.WithMessagePactMetadata(@namespace, name, value); + return this; + } + } +} diff --git a/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs b/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs new file mode 100644 index 00000000..010d76b5 --- /dev/null +++ b/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs @@ -0,0 +1,139 @@ +using System; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading.Tasks; +using FluentAssertions; +using Moq; +using PactNet.Drivers; +using PactNet.Exceptions; +using PactNet.Interop; +using PactNet.Models; +using Xunit; + +namespace PactNet.Tests +{ + public class ConfiguredSyncMessageVerifierTests + { + private static readonly JsonSerializerOptions CamelCase = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + private readonly Mock mockDriver; + + private readonly PactConfig config; + + public ConfiguredSyncMessageVerifierTests() + { + this.mockDriver = new Mock(); + + this.config = new PactConfig { PactDir = "/path/to/pacts", DefaultJsonSettings = CamelCase }; + } + + [Fact] + public void Verify_SuccessfullyVerified_WritesPactFile() + { + (var verifier, Request request) = this.SetupMessage(); + + verifier.Verify(r => + { + r.Should().BeEquivalentTo(request); + return new Response { Status = "ok" }; + }); + + this.mockDriver.Verify(s => s.WritePactFile(this.config.PactDir)); + } + + [Fact] + public void Verify_FailedToVerify_ThrowsVerificationException() + { + (var verifier, _) = this.SetupMessage(); + + Action action = () => verifier.Verify(_ => throw new Exception("oh noes")); + + action.Should().Throw().WithInnerException(); + } + + [Fact] + public void Verify_FailedToVerify_DoesNotWritePactFile() + { + (var verifier, _) = this.SetupMessage(); + + try + { + verifier.Verify(_ => throw new Exception("oh noes")); + } + catch + { + // ignore + } + + this.mockDriver.Verify(s => s.WritePactFile(It.IsAny()), Times.Never); + } + + [Fact] + public async Task VerifyAsync_SuccessfullyVerified_WritesPactFile() + { + (var verifier, Request request) = this.SetupMessage(); + + await verifier.VerifyAsync(r => + { + r.Should().BeEquivalentTo(request); + return Task.FromResult(new Response { Status = "ok" }); + }); + + this.mockDriver.Verify(s => s.WritePactFile(this.config.PactDir)); + } + + [Fact] + public async Task VerifyAsync_FailedToVerifyAsync_ThrowsVerificationException() + { + (var verifier, _) = this.SetupMessage(); + + Func action = () => verifier.VerifyAsync(_ => throw new Exception("oh noes")); + + await action.Should().ThrowAsync(); + } + + private (ConfiguredSyncMessageVerifier Verifier, Request Request) SetupMessage() + { + var verifier = new ConfiguredSyncMessageVerifier(this.mockDriver.Object, this.config, PactSpecification.V4); + + // this simulates what the FFI library does - the content uses user-supplied JSON settings + // then they are interpreted literally to a JToken + var request = new Request { Id = 42 }; + string serialisedRequest = JsonSerializer.Serialize(request, this.config.DefaultJsonSettings); + + JsonNode requestToken = JsonSerializer.Deserialize( + @$"{{""content"":{serialisedRequest},""contentType"":""application/json"",""encoded"":false}}"); + + var response = new Response { Status = "ok" }; + string serialisedResponse = JsonSerializer.Serialize(response, this.config.DefaultJsonSettings); + JsonNode responseToken = JsonSerializer.Deserialize( + @$"{{""content"":{serialisedResponse},""contentType"":""application/json"",""encoded"":false}}"); + + NativeSyncMessage native = new NativeSyncMessage + { + Request = new NativeMessage { Contents = requestToken }, + Response = new[] { new NativeMessage { Contents = responseToken } } + }; + + // the native message returned from the FFI is always camel-cased + this.mockDriver + .Setup(s => s.Reify()) + .Returns(JsonSerializer.Serialize(native, CamelCase)); + + return (verifier, request); + } + + private class Request + { + public int Id { get; set; } + } + + private class Response + { + public string Status { get; set; } + } + } +} diff --git a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs index 81ab072e..dcdc198e 100644 --- a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs +++ b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs @@ -130,5 +130,39 @@ public void MessageInteraction_v3_CreatesPactFile() string expectedPactContent = File.ReadAllText("data/v3-message-integration.json").TrimEnd(); pactContents.Should().Be(expectedPactContent); } + + [Fact(Skip = "Requires a pact_ffi build with pactffi_sync_message_reify " + + "(see https://github.com/pact-foundation/pact-reference/pull/555); " + + "remove this Skip once that lands in a released pact_ffi version")] + public void SyncMessageInteraction_v4_CreatesPactFile() + { + var driver = new PactDriver(); + + try + { + IMessagePactDriver pact = driver.NewMessagePact("NativeDriverTests-Consumer-V4", + "NativeDriverTests-Producer", + PactSpecification.V4); + + ISyncMessageInteractionDriver interaction = pact.NewSyncMessageInteraction("a sync message interaction"); + + interaction.WithRequestMetadata("foo", "bar"); + interaction.WithRequestContents("application/json", @"{""foo"":42}"); + interaction.WithResponseMetadata("baz", "bash"); + interaction.WithResponseContents("application/json", @"{""baz"":42}"); + + string reified = interaction.Reify(); + reified.Should().NotBeNullOrEmpty(); + + interaction.WritePactFile(Environment.CurrentDirectory); + } + finally + { + this.WriteDriverLogs(driver); + } + + var file = new FileInfo("NativeDriverTests-Consumer-V4-NativeDriverTests-Producer.json"); + file.Exists.Should().BeTrue(); + } } } diff --git a/tests/PactNet.Tests/SyncMessageBuilderTests.cs b/tests/PactNet.Tests/SyncMessageBuilderTests.cs new file mode 100644 index 00000000..5c669894 --- /dev/null +++ b/tests/PactNet.Tests/SyncMessageBuilderTests.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using System.Text.Json; +using Moq; +using PactNet.Drivers; +using PactNet.Interop; +using Xunit; +using Match = PactNet.Matchers.Match; + +namespace PactNet.Tests +{ + public class SyncMessageBuilderTests + { + private readonly ISyncMessageBuilderV4 builder; + + private readonly Mock mockDriver; + + private readonly PactConfig config; + + public SyncMessageBuilderTests() + { + this.mockDriver = new Mock(); + + this.config = new PactConfig { DefaultJsonSettings = new JsonSerializerOptions() }; + + this.builder = new SyncMessageBuilder(this.mockDriver.Object, this.config, PactSpecification.V4); + } + + [Fact] + public void Ctor_Throws_Exception_If_Driver_Not_Set() + { + Assert.Throws(() => + new SyncMessageBuilder(null, new PactConfig(), PactSpecification.V4)); + } + + [Fact] + public void Given_WhenCalled_AddsProviderState() + { + this.builder.Given("provider state"); + + this.mockDriver.Verify(s => s.Given("provider state")); + } + + [Fact] + public void Given_WithParams_AddsProviderState() + { + this.builder.Given("provider state", + new Dictionary + { + ["foo"] = "bar", + ["baz"] = "bash", + }); + + this.mockDriver.Verify(s => s.GivenWithParam("provider state", "foo", "bar")); + this.mockDriver.Verify(s => s.GivenWithParam("provider state", "baz", "bash")); + } + + [Fact] + public void WithRequestMetadata_WhenCalled_AddsRequestMetadata() + { + this.builder.WithRequestMetadata("poolId", "1234"); + + this.mockDriver.Verify(s => s.WithRequestMetadata("poolId", "1234")); + } + + [Fact] + public void WithResponseMetadata_WhenCalled_AddsResponseMetadata() + { + this.builder.WithResponseMetadata("poolId", "1234"); + + this.mockDriver.Verify(s => s.WithResponseMetadata("poolId", "1234")); + } + + [Fact] + public void WithRequestJsonContent_WithoutCustomSettings_AddsContentWithDefaultSettings() + { + var content = new { Id = 1, Desc = "description" }; + const string expected = @"{""Id"":1,""Desc"":""description""}"; + + this.builder.WithRequestJsonContent(content); + + this.mockDriver.Verify(s => s.WithRequestContents("application/json", expected)); + } + + [Fact] + public void WithRequestJsonContent_WithCustomSettings_AddsContentWithOverriddenSettings() + { + var content = new { Id = 1, Desc = "description" }; + const string expected = @"{""id"":1,""desc"":""description""}"; + + this.builder.WithRequestJsonContent(content, new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }); + + this.mockDriver.Verify(s => s.WithRequestContents("application/json", expected)); + } + + [Fact] + public void WithRequestJsonContent_MatcherProperties_AddsContent() + { + dynamic content = new { Matcher = Match.Integer(42) }; + const string expected = @"{""matcher"":{""pact:matcher:type"":""integer"",""value"":42}}"; + + this.builder.WithRequestJsonContent(content, new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }); + + this.mockDriver.Verify(s => s.WithRequestContents("application/json", expected)); + } + + [Fact] + public void WithResponseJsonContent_WithoutCustomSettings_AddsContentWithDefaultSettings() + { + var content = new { Id = 1, Desc = "description" }; + const string expected = @"{""Id"":1,""Desc"":""description""}"; + + this.builder.WithResponseJsonContent(content); + + this.mockDriver.Verify(s => s.WithResponseContents("application/json", expected)); + } + + [Fact] + public void WithResponseJsonContent_ReturnsConfiguredVerifier() + { + var content = new { Id = 1 }; + + IConfiguredSyncMessageVerifier verifier = this.builder.WithResponseJsonContent(content); + + Assert.NotNull(verifier); + } + } +} diff --git a/tests/PactNet.Tests/SyncMessagePactBuilderTests.cs b/tests/PactNet.Tests/SyncMessagePactBuilderTests.cs new file mode 100644 index 00000000..56e979bd --- /dev/null +++ b/tests/PactNet.Tests/SyncMessagePactBuilderTests.cs @@ -0,0 +1,79 @@ +using System; +using FluentAssertions; +using Moq; +using PactNet.Drivers; +using PactNet.Interop; +using Xunit; + +namespace PactNet.Tests +{ + public class SyncMessagePactBuilderTests + { + private readonly SyncMessagePactBuilder builder; + + private readonly Mock mockDriver; + private readonly Mock mockInteractions; + + private readonly PactConfig config; + + public SyncMessagePactBuilderTests() + { + this.mockDriver = new Mock(); + this.mockInteractions = new Mock(); + + this.config = new PactConfig(); + + this.mockDriver + .Setup(d => d.NewSyncMessageInteraction(It.IsAny())) + .Returns(this.mockInteractions.Object); + + this.builder = new SyncMessagePactBuilder(this.mockDriver.Object, this.config, PactSpecification.V4); + } + + [Fact] + public void Ctor_NullDriver_ThrowsArgumentNullException() + { + Action action = () => + { + var _ = new SyncMessagePactBuilder(null, this.config, PactSpecification.V4); + }; + + action.Should().Throw(); + } + + [Fact] + public void Ctor_NullConfig_ThrowsArgumentNullException() + { + Action action = () => + { + var _ = new SyncMessagePactBuilder(this.mockDriver.Object, null, PactSpecification.V4); + }; + + action.Should().Throw(); + } + + [Fact] + public void ExpectsToReceive_WhenCalled_StartsNewMessage() + { + this.builder.ExpectsToReceive("a message"); + + this.mockDriver.Verify(s => s.NewSyncMessageInteraction("a message"), Times.Once); + } + + [Fact] + public void WithPactMetadata_WhenCalled_ConfiguresMetadata() + { + this.builder.WithPactMetadata("test", "name", "value"); + + this.mockDriver.Verify(s => s.WithMessagePactMetadata("test", "name", "value")); + } + + [Fact] + public void WithPactMetadata_WhenCalled_ReturnsFluentBuilder() + { + var returned = this.builder.WithPactMetadata("test", "name", "value"); + + returned.Should().BeSameAs(this.builder); + } + } +} From 94a4d8fb63a7cb0c9358efbdd30811b41cd2e5d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A1bio=20Andr=C3=A9=20Ramos=20Rodrigues?= Date: Thu, 24 Sep 2026 15:57:03 +0100 Subject: [PATCH 03/15] Refine summary comment in IConfiguredSyncMessageVerifier Removed redundant phrase from summary comment. --- src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs b/src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs index 40000bc6..f45b72fc 100644 --- a/src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs +++ b/src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs @@ -4,7 +4,7 @@ namespace PactNet { /// - /// A configured synchronous (request/response) message type state, which can now be verified + /// A configured synchronous (request/response) message type state /// public interface IConfiguredSyncMessageVerifier { From 5f055c3c1fcf59875a4d4ac683d8daa4ef4c3618 Mon Sep 17 00:00:00 2001 From: Fabio Rodrigues Date: Thu, 24 Sep 2026 16:07:11 +0100 Subject: [PATCH 04/15] refactor: rename sync message Reify() members to GenerateContents() Callers of PactNet don't need to know the Pact-internal term "reify" - GenerateContents describes what the method actually returns. Matches the pactffi_sync_message_generate_contents rename on the pact-reference side (pact-foundation/pact-reference#555). The pre-existing async message Reify()/pactffi_message_reify naming is untouched. --- src/PactNet/ConfiguredSyncMessageVerifier.cs | 23 ++++++++++--------- .../Drivers/ISyncMessageInteractionDriver.cs | 8 +++---- .../Drivers/SyncMessageInteractionDriver.cs | 10 ++++---- src/PactNet/Interop/NativeInterop.cs | 4 ++-- .../ConfiguredSyncMessageVerifierTests.cs | 2 +- .../Drivers/FfiIntegrationTests.cs | 6 ++--- 6 files changed, 27 insertions(+), 26 deletions(-) diff --git a/src/PactNet/ConfiguredSyncMessageVerifier.cs b/src/PactNet/ConfiguredSyncMessageVerifier.cs index 58fcaa60..ba83fccc 100644 --- a/src/PactNet/ConfiguredSyncMessageVerifier.cs +++ b/src/PactNet/ConfiguredSyncMessageVerifier.cs @@ -45,9 +45,9 @@ public void Verify(Func handler) { try { - TRequest requestReified = this.RequestReified(); + TRequest request = this.GeneratedRequest(); - handler(requestReified); + handler(request); this.driver.WritePactFile(this.config.PactDir); } @@ -65,9 +65,9 @@ public async Task VerifyAsync(Func(); + TRequest request = this.GeneratedRequest(); - await handler(requestReified); + await handler(request); this.driver.WritePactFile(this.config.PactDir); } @@ -78,22 +78,23 @@ public async Task VerifyAsync(Func - /// Try to read the reified request message + /// Get the actual request message, with any matchers removed and any configured + /// generators applied /// /// the type of the request message /// the request message - private TRequest RequestReified() + private TRequest GeneratedRequest() { - string reified = this.driver.Reify(); - NativeSyncMessage content = JsonSerializer.Deserialize(reified, NativeMessageSettings); + string generated = this.driver.GenerateContents(); + NativeSyncMessage content = JsonSerializer.Deserialize(generated, NativeMessageSettings); - // Synchronous messages only exist in the V4 Pact format, so the reified contents + // Synchronous messages only exist in the V4 Pact format, so the generated contents // always use the V4 body envelope (a `content` field) string contentString = ((JsonElement)content.Request.Contents).GetProperty("content").GetRawText(); - TRequest requestReified = JsonSerializer.Deserialize(contentString, this.config.DefaultJsonSettings); + TRequest request = JsonSerializer.Deserialize(contentString, this.config.DefaultJsonSettings); - return requestReified; + return request; } } } diff --git a/src/PactNet/Drivers/ISyncMessageInteractionDriver.cs b/src/PactNet/Drivers/ISyncMessageInteractionDriver.cs index f1747fae..673a40e0 100644 --- a/src/PactNet/Drivers/ISyncMessageInteractionDriver.cs +++ b/src/PactNet/Drivers/ISyncMessageInteractionDriver.cs @@ -34,10 +34,10 @@ internal interface ISyncMessageInteractionDriver : IProviderStateDriver, IComple void WithResponseContents(string contentType, string body); /// - /// Returns the request and response contents without the matchers, with any configured - /// generators applied + /// Get the actual request and response contents, with any matchers removed and any + /// configured generators applied /// - /// Reified message - string Reify(); + /// The generated request and response contents + string GenerateContents(); } } diff --git a/src/PactNet/Drivers/SyncMessageInteractionDriver.cs b/src/PactNet/Drivers/SyncMessageInteractionDriver.cs index 92ea5fbb..3f988037 100644 --- a/src/PactNet/Drivers/SyncMessageInteractionDriver.cs +++ b/src/PactNet/Drivers/SyncMessageInteractionDriver.cs @@ -70,13 +70,13 @@ public void WithResponseContents(string contentType, string body) => NativeInterop.WithBody(this.interaction, InteractionPart.Response, contentType, body).CheckInteropSuccess(); /// - /// Returns the request and response contents without the matchers, with any configured - /// generators applied + /// Get the actual request and response contents, with any matchers removed and any + /// configured generators applied /// - /// Reified message - public string Reify() + /// The generated request and response contents + public string GenerateContents() { - IntPtr pointer = NativeInterop.SyncMessageReify(this.interaction); + IntPtr pointer = NativeInterop.SyncMessageGenerateContents(this.interaction); string body = Marshal.PtrToStringAnsi(pointer); return body; } diff --git a/src/PactNet/Interop/NativeInterop.cs b/src/PactNet/Interop/NativeInterop.cs index 5f0c02f9..f9909225 100644 --- a/src/PactNet/Interop/NativeInterop.cs +++ b/src/PactNet/Interop/NativeInterop.cs @@ -97,8 +97,8 @@ internal static class NativeInterop [DllImport(DllName, EntryPoint = "pactffi_with_metadata")] public static extern bool WithMetadata(InteractionHandle interaction, string key, string value, InteractionPart part); - [DllImport(DllName, EntryPoint = "pactffi_sync_message_reify")] - public static extern IntPtr SyncMessageReify(InteractionHandle message); + [DllImport(DllName, EntryPoint = "pactffi_sync_message_generate_contents")] + public static extern IntPtr SyncMessageGenerateContents(InteractionHandle message); #endregion Http Interop Support diff --git a/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs b/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs index 010d76b5..8d72744f 100644 --- a/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs +++ b/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs @@ -120,7 +120,7 @@ public async Task VerifyAsync_FailedToVerifyAsync_ThrowsVerificationException() // the native message returned from the FFI is always camel-cased this.mockDriver - .Setup(s => s.Reify()) + .Setup(s => s.GenerateContents()) .Returns(JsonSerializer.Serialize(native, CamelCase)); return (verifier, request); diff --git a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs index dcdc198e..e3a5a792 100644 --- a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs +++ b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs @@ -131,7 +131,7 @@ public void MessageInteraction_v3_CreatesPactFile() pactContents.Should().Be(expectedPactContent); } - [Fact(Skip = "Requires a pact_ffi build with pactffi_sync_message_reify " + + [Fact(Skip = "Requires a pact_ffi build with pactffi_sync_message_generate_contents " + "(see https://github.com/pact-foundation/pact-reference/pull/555); " + "remove this Skip once that lands in a released pact_ffi version")] public void SyncMessageInteraction_v4_CreatesPactFile() @@ -151,8 +151,8 @@ public void SyncMessageInteraction_v4_CreatesPactFile() interaction.WithResponseMetadata("baz", "bash"); interaction.WithResponseContents("application/json", @"{""baz"":42}"); - string reified = interaction.Reify(); - reified.Should().NotBeNullOrEmpty(); + string generated = interaction.GenerateContents(); + generated.Should().NotBeNullOrEmpty(); interaction.WritePactFile(Environment.CurrentDirectory); } From 4b3b0e0e9d6673c33b7a4ff6dc7573c90a5bee08 Mon Sep 17 00:00:00 2001 From: Fabio Rodrigues Date: Thu, 24 Sep 2026 16:12:36 +0100 Subject: [PATCH 05/15] docs: document synchronous (request/response) message support Adds a section to messaging-pacts.md covering WithSynchronousMessageInteractions, alongside the existing fire-and-forget message docs. Notes that provider verification isn't covered yet and that this depends on pactffi_sync_message_generate_contents landing upstream. --- docs/messaging-pacts.md | 56 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/docs/messaging-pacts.md b/docs/messaging-pacts.md index 6fe29be5..cad2b967 100644 --- a/docs/messaging-pacts.md +++ b/docs/messaging-pacts.md @@ -153,3 +153,59 @@ public class StockEventGeneratorTests : IDisposable } } ``` + +Synchronous (Request/Response) Messages +---------------------------------------- + +> This is a V4-only pact feature (`Pact.V4(...)`). It's used for message flows that expect a reply +> to each request - for example an AsyncAPI operation with a `reply` block. + +Unlike the fire-and-forget messages above, a synchronous message interaction has both a request and a +response. The consumer specifies the expected request and response content, and PactNet feeds the +generated request to your handler under test. + +In code, this is: + +```csharp +public class OrderLookupConsumerTests +{ + private readonly ISyncMessagePactBuilderV4 messagePact; + + public OrderLookupConsumerTests(ITestOutputHelper output) + { + IPactV4 v4 = Pact.V4("Order Lookup Consumer", "Order Lookup Producer", new PactConfig + { + PactDir = "../../../pacts/", + Outputters = new[] + { + new XUnitOutput(output) + } + }); + + this.messagePact = v4.WithSynchronousMessageInteractions(); + } + + [Fact] + public void LooksUpAnOrder() + { + this.messagePact + .ExpectsToReceive("a request for an order") + .Given("order 1234 exists") + .WithRequestJsonContent(new { OrderId = Match.Type("1234") }) + .WithResponseJsonContent(new { Status = Match.Type("shipped") }) + .Verify(request => + { + OrderStatus response = this.orderLookupClient.Lookup(request); + return response; + }); + } +} +``` + +As with fire-and-forget messages, a pact file is written to disk once all consumer tests have passed. + +Only consumer-side pact generation is currently supported for synchronous messages; provider +verification support is tracked separately. See +[pact-foundation/pact-net#562](https://github.com/pact-foundation/pact-net/pull/562) for status - it +also depends on `pactffi_sync_message_generate_contents`, proposed in +[pact-foundation/pact-reference#555](https://github.com/pact-foundation/pact-reference/pull/555). From 2a7194d2b9bb8dcefcc8e113f009863a61718f2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A1bio=20Andr=C3=A9=20Ramos=20Rodrigues?= Date: Thu, 24 Sep 2026 16:19:34 +0100 Subject: [PATCH 06/15] Simplify messaging pacts documentation Removed information about provider verification support and related issues. --- docs/messaging-pacts.md | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/docs/messaging-pacts.md b/docs/messaging-pacts.md index cad2b967..e06bf469 100644 --- a/docs/messaging-pacts.md +++ b/docs/messaging-pacts.md @@ -202,10 +202,4 @@ public class OrderLookupConsumerTests } ``` -As with fire-and-forget messages, a pact file is written to disk once all consumer tests have passed. - -Only consumer-side pact generation is currently supported for synchronous messages; provider -verification support is tracked separately. See -[pact-foundation/pact-net#562](https://github.com/pact-foundation/pact-net/pull/562) for status - it -also depends on `pactffi_sync_message_generate_contents`, proposed in -[pact-foundation/pact-reference#555](https://github.com/pact-foundation/pact-reference/pull/555). +As with fire-and-forget messages, a pact file is written to disk once all consumer tests have passed From e506c0a6c50679cff5434b9250ca7b1b0db6b6cc Mon Sep 17 00:00:00 2001 From: Fabio Rodrigues Date: Fri, 25 Sep 2026 11:46:10 +0100 Subject: [PATCH 07/15] fix: free the native string returned by Reify/GenerateContents MessageInteractionDriver.Reify() and SyncMessageInteractionDriver.GenerateContents() copied the FFI-returned string into managed memory but never freed the native allocation, leaking it on every call. --- src/PactNet/Drivers/MessageInteractionDriver.cs | 1 + src/PactNet/Drivers/SyncMessageInteractionDriver.cs | 1 + 2 files changed, 2 insertions(+) diff --git a/src/PactNet/Drivers/MessageInteractionDriver.cs b/src/PactNet/Drivers/MessageInteractionDriver.cs index 035f8f4c..e93bbc73 100644 --- a/src/PactNet/Drivers/MessageInteractionDriver.cs +++ b/src/PactNet/Drivers/MessageInteractionDriver.cs @@ -69,6 +69,7 @@ public string Reify() { IntPtr pointer = NativeInterop.MessageReify(this.interaction); string body = Marshal.PtrToStringAnsi(pointer); + NativeInterop.FreeString(pointer); return body; } } diff --git a/src/PactNet/Drivers/SyncMessageInteractionDriver.cs b/src/PactNet/Drivers/SyncMessageInteractionDriver.cs index 3f988037..5f09d5b7 100644 --- a/src/PactNet/Drivers/SyncMessageInteractionDriver.cs +++ b/src/PactNet/Drivers/SyncMessageInteractionDriver.cs @@ -78,6 +78,7 @@ public string GenerateContents() { IntPtr pointer = NativeInterop.SyncMessageGenerateContents(this.interaction); string body = Marshal.PtrToStringAnsi(pointer); + NativeInterop.FreeString(pointer); return body; } } From 961d1c28a778644509bb8150bd0ec26238e8722a Mon Sep 17 00:00:00 2001 From: Fabio Rodrigues Date: Mon, 28 Sep 2026 12:14:19 +0100 Subject: [PATCH 08/15] feat: assert the handler's response against the configured response Verify/VerifyAsync already required the handler to return a TResponse but never checked it, so a consumer test would pass regardless of what the handler returned. Compare it against the FFI-generated response content (matchers stripped, generators applied) via a structural JSON equality check, so a mismatch fails the test instead of being silently written to the pact file. --- docs/messaging-pacts.md | 5 +- .../IConfiguredSyncMessageVerifier.cs | 12 +- src/PactNet/ConfiguredSyncMessageVerifier.cs | 156 ++++++++++++++++-- .../ConfiguredSyncMessageVerifierTests.cs | 54 ++++++ 4 files changed, 208 insertions(+), 19 deletions(-) diff --git a/docs/messaging-pacts.md b/docs/messaging-pacts.md index e06bf469..0c9df494 100644 --- a/docs/messaging-pacts.md +++ b/docs/messaging-pacts.md @@ -161,8 +161,9 @@ Synchronous (Request/Response) Messages > to each request - for example an AsyncAPI operation with a `reply` block. Unlike the fire-and-forget messages above, a synchronous message interaction has both a request and a -response. The consumer specifies the expected request and response content, and PactNet feeds the -generated request to your handler under test. +response. The consumer specifies the expected request and response content, PactNet feeds the +generated request to your handler under test, and checks that the value your handler returns matches +the generated response content (matchers stripped, generators applied) before writing the pact file. In code, this is: diff --git a/src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs b/src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs index f45b72fc..8e5178a5 100644 --- a/src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs +++ b/src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs @@ -9,15 +9,23 @@ namespace PactNet public interface IConfiguredSyncMessageVerifier { /// - /// Verify a request message is read and handled correctly + /// Verify a request message is read and handled correctly, and that the response returned + /// by the handler matches the configured response content /// /// The method handling the request message and producing a response + /// + /// The handler threw, or its response did not match the configured response content + /// void Verify(Func handler); /// - /// Verify a request message is read and handled correctly + /// Verify a request message is read and handled correctly, and that the response returned + /// by the handler matches the configured response content /// /// The method handling the request message and producing a response + /// + /// The handler threw, or its response did not match the configured response content + /// Task VerifyAsync(Func> handler); } } diff --git a/src/PactNet/ConfiguredSyncMessageVerifier.cs b/src/PactNet/ConfiguredSyncMessageVerifier.cs index ba83fccc..ff9b9d1e 100644 --- a/src/PactNet/ConfiguredSyncMessageVerifier.cs +++ b/src/PactNet/ConfiguredSyncMessageVerifier.cs @@ -38,19 +38,26 @@ internal ConfiguredSyncMessageVerifier(ISyncMessageInteractionDriver driver, Pac } /// - /// Verify a request message is read and handled correctly and write the message pact + /// Verify a request message is read and handled correctly, and that the response returned + /// by the handler matches the configured response content, then write the message pact /// /// The method handling the request message and producing a response public void Verify(Func handler) { try { - TRequest request = this.GeneratedRequest(); + NativeSyncMessage generated = this.GeneratedMessage(); + TRequest request = DeserializeContent((JsonElement)generated.Request.Contents); - handler(request); + TResponse actualResponse = handler(request); + this.VerifyResponse(generated, actualResponse); this.driver.WritePactFile(this.config.PactDir); } + catch (PactMessageConsumerVerificationException) + { + throw; + } catch (Exception e) { throw new PactMessageConsumerVerificationException($"The message could not be verified by the consumer handler", e); @@ -58,19 +65,26 @@ public void Verify(Func handler) } /// - /// Verify a request message is read and handled correctly and write the message pact + /// Verify a request message is read and handled correctly, and that the response returned + /// by the handler matches the configured response content, then write the message pact /// /// The method handling the request message and producing a response public async Task VerifyAsync(Func> handler) { try { - TRequest request = this.GeneratedRequest(); + NativeSyncMessage generated = this.GeneratedMessage(); + TRequest request = DeserializeContent((JsonElement)generated.Request.Contents); - await handler(request); + TResponse actualResponse = await handler(request); + this.VerifyResponse(generated, actualResponse); this.driver.WritePactFile(this.config.PactDir); } + catch (PactMessageConsumerVerificationException) + { + throw; + } catch (Exception e) { throw new PactMessageConsumerVerificationException($"The message could not be verified by the consumer handler", e); @@ -78,23 +92,135 @@ public async Task VerifyAsync(Func - /// Get the actual request message, with any matchers removed and any configured - /// generators applied + /// Get the generated message, with any matchers removed and any configured generators applied /// - /// the type of the request message - /// the request message - private TRequest GeneratedRequest() + /// the native message + private NativeSyncMessage GeneratedMessage() { string generated = this.driver.GenerateContents(); - NativeSyncMessage content = JsonSerializer.Deserialize(generated, NativeMessageSettings); + return JsonSerializer.Deserialize(generated, NativeMessageSettings); + } + + /// + /// Check the handler's response against the configured response content + /// + /// the generated message + /// the response returned by the handler under test + private void VerifyResponse(NativeSyncMessage generated, TResponse actualResponse) + { + JsonElement expectedContent = ((JsonElement)generated.Response[0].Contents).GetProperty("content"); + + string actualJson = JsonSerializer.Serialize(actualResponse, this.config.DefaultJsonSettings); + using JsonDocument actualDocument = JsonDocument.Parse(actualJson); + if (!JsonElementsEqual(expectedContent, actualDocument.RootElement)) + { + throw new PactMessageConsumerVerificationException( + $"The response returned by the consumer handler did not match the configured response content. " + + $"Expected {expectedContent.GetRawText()} but got {actualJson}"); + } + } + + /// + /// Deserialize the content of the request or response, with any matchers removed and any + /// configured generators applied + /// + /// the type to deserialize the content into + /// the generated message contents + /// the deserialized content + private T DeserializeContent(JsonElement contents) + { // Synchronous messages only exist in the V4 Pact format, so the generated contents // always use the V4 body envelope (a `content` field) - string contentString = ((JsonElement)content.Request.Contents).GetProperty("content").GetRawText(); + string contentString = contents.GetProperty("content").GetRawText(); - TRequest request = JsonSerializer.Deserialize(contentString, this.config.DefaultJsonSettings); + return JsonSerializer.Deserialize(contentString, this.config.DefaultJsonSettings); + } - return request; + /// + /// Recursively compare two JSON elements for structural equality, ignoring object property order + /// + private static bool JsonElementsEqual(JsonElement expected, JsonElement actual) + { + if (expected.ValueKind != actual.ValueKind) + { + return false; + } + + switch (expected.ValueKind) + { + case JsonValueKind.Object: + var expectedProperties = new System.Collections.Generic.Dictionary(StringComparer.Ordinal); + foreach (JsonProperty property in expected.EnumerateObject()) + { + expectedProperties[property.Name] = property.Value; + } + + var actualProperties = new System.Collections.Generic.Dictionary(StringComparer.Ordinal); + foreach (JsonProperty property in actual.EnumerateObject()) + { + actualProperties[property.Name] = property.Value; + } + + if (expectedProperties.Count != actualProperties.Count) + { + return false; + } + + foreach (var property in expectedProperties) + { + if (!actualProperties.TryGetValue(property.Key, out JsonElement actualValue) || + !JsonElementsEqual(property.Value, actualValue)) + { + return false; + } + } + + return true; + + case JsonValueKind.Array: + var expectedItems = new System.Collections.Generic.List(); + foreach (JsonElement item in expected.EnumerateArray()) + { + expectedItems.Add(item); + } + + var actualItems = new System.Collections.Generic.List(); + foreach (JsonElement item in actual.EnumerateArray()) + { + actualItems.Add(item); + } + + if (expectedItems.Count != actualItems.Count) + { + return false; + } + + for (int i = 0; i < expectedItems.Count; i++) + { + if (!JsonElementsEqual(expectedItems[i], actualItems[i])) + { + return false; + } + } + + return true; + + case JsonValueKind.String: + return expected.GetString() == actual.GetString(); + + case JsonValueKind.Number: + return expected.GetRawText() == actual.GetRawText(); + + case JsonValueKind.True: + case JsonValueKind.False: + case JsonValueKind.Null: + case JsonValueKind.Undefined: + return true; + + default: + return expected.GetRawText() == actual.GetRawText(); + } } } } diff --git a/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs b/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs index 8d72744f..71705aa0 100644 --- a/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs +++ b/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs @@ -71,6 +71,33 @@ public void Verify_FailedToVerify_DoesNotWritePactFile() this.mockDriver.Verify(s => s.WritePactFile(It.IsAny()), Times.Never); } + [Fact] + public void Verify_ResponseDoesNotMatchConfiguredResponse_ThrowsVerificationException() + { + (var verifier, _) = this.SetupMessage(); + + Action action = () => verifier.Verify(_ => new Response { Status = "not-ok" }); + + action.Should().Throw(); + } + + [Fact] + public void Verify_ResponseDoesNotMatchConfiguredResponse_DoesNotWritePactFile() + { + (var verifier, _) = this.SetupMessage(); + + try + { + verifier.Verify(_ => new Response { Status = "not-ok" }); + } + catch + { + // ignore + } + + this.mockDriver.Verify(s => s.WritePactFile(It.IsAny()), Times.Never); + } + [Fact] public async Task VerifyAsync_SuccessfullyVerified_WritesPactFile() { @@ -95,6 +122,33 @@ public async Task VerifyAsync_FailedToVerifyAsync_ThrowsVerificationException() await action.Should().ThrowAsync(); } + [Fact] + public async Task VerifyAsync_ResponseDoesNotMatchConfiguredResponse_ThrowsVerificationException() + { + (var verifier, _) = this.SetupMessage(); + + Func action = () => verifier.VerifyAsync(_ => Task.FromResult(new Response { Status = "not-ok" })); + + await action.Should().ThrowAsync(); + } + + [Fact] + public async Task VerifyAsync_ResponseDoesNotMatchConfiguredResponse_DoesNotWritePactFile() + { + (var verifier, _) = this.SetupMessage(); + + try + { + await verifier.VerifyAsync(_ => Task.FromResult(new Response { Status = "not-ok" })); + } + catch + { + // ignore + } + + this.mockDriver.Verify(s => s.WritePactFile(It.IsAny()), Times.Never); + } + private (ConfiguredSyncMessageVerifier Verifier, Request Request) SetupMessage() { var verifier = new ConfiguredSyncMessageVerifier(this.mockDriver.Object, this.config, PactSpecification.V4); From 9f64d81fc9c9427aa3c89e5327a06a1bb6d64a55 Mon Sep 17 00:00:00 2001 From: Fabio Rodrigues Date: Mon, 28 Sep 2026 12:21:37 +0100 Subject: [PATCH 09/15] chore: move sync message driver into Drivers/Message #551 reorganises Drivers/ into Http/, Message/ and Plugins/ subfolders. The sync message driver belongs in Message/ alongside the async one, since it's the same message-queue-style request/response category, not a plugin. Namespace stays PactNet.Drivers for now since the rest of the tree hasn't moved yet; that follows once #551 lands. --- .../Drivers/{ => Message}/ISyncMessageInteractionDriver.cs | 0 src/PactNet/Drivers/{ => Message}/SyncMessageInteractionDriver.cs | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename src/PactNet/Drivers/{ => Message}/ISyncMessageInteractionDriver.cs (100%) rename src/PactNet/Drivers/{ => Message}/SyncMessageInteractionDriver.cs (100%) diff --git a/src/PactNet/Drivers/ISyncMessageInteractionDriver.cs b/src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs similarity index 100% rename from src/PactNet/Drivers/ISyncMessageInteractionDriver.cs rename to src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs diff --git a/src/PactNet/Drivers/SyncMessageInteractionDriver.cs b/src/PactNet/Drivers/Message/SyncMessageInteractionDriver.cs similarity index 100% rename from src/PactNet/Drivers/SyncMessageInteractionDriver.cs rename to src/PactNet/Drivers/Message/SyncMessageInteractionDriver.cs From e02541e06b13b6403f4f63052e42d3e633e4906b Mon Sep 17 00:00:00 2001 From: Fabio Rodrigues Date: Thu, 8 Oct 2026 13:48:21 +0100 Subject: [PATCH 10/15] fix: typed sync message metadata, applied after the response exists pactffi_with_metadata only applies response metadata to responses that already exist, and the response is created by the terminal WithResponseJsonContent call, so response metadata was always dropped. The builder now buffers it and applies it after the response content. Request/response metadata values are now dynamic and serialised as JSON, so strings, numbers, booleans and matchers keep their type in the pact instead of relying on the FFI's parse-or-fallback-to-string behaviour. --- .../ISyncMessageBuilder.cs | 12 +++--- .../Message/ISyncMessageInteractionDriver.cs | 8 ++-- src/PactNet/SyncMessageBuilder.cs | 29 ++++++++++---- .../PactNet.Tests/SyncMessageBuilderTests.cs | 38 +++++++++++++++++-- 4 files changed, 66 insertions(+), 21 deletions(-) diff --git a/src/PactNet.Abstractions/ISyncMessageBuilder.cs b/src/PactNet.Abstractions/ISyncMessageBuilder.cs index 9b748cb2..334de8d3 100644 --- a/src/PactNet.Abstractions/ISyncMessageBuilder.cs +++ b/src/PactNet.Abstractions/ISyncMessageBuilder.cs @@ -24,20 +24,20 @@ public interface ISyncMessageBuilderV4 ISyncMessageBuilderV4 Given(string providerState, IDictionary parameters); /// - /// Set the request metadata + /// Set a request metadata value, which is serialised as JSON /// /// the metadata key - /// the metadata value + /// the metadata value, e.g. a string, number, boolean or matcher /// Fluent builder - ISyncMessageBuilderV4 WithRequestMetadata(string key, string value); + ISyncMessageBuilderV4 WithRequestMetadata(string key, dynamic value); /// - /// Set the response metadata + /// Set a response metadata value, which is serialised as JSON /// /// the metadata key - /// the metadata value + /// the metadata value, e.g. a string, number, boolean or matcher /// Fluent builder - ISyncMessageBuilderV4 WithResponseMetadata(string key, string value); + ISyncMessageBuilderV4 WithResponseMetadata(string key, dynamic value); /// /// Set the request content which is serialised as JSON diff --git a/src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs b/src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs index 673a40e0..1338b62f 100644 --- a/src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs +++ b/src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs @@ -6,17 +6,17 @@ namespace PactNet.Drivers internal interface ISyncMessageInteractionDriver : IProviderStateDriver, ICompletedPactDriver { /// - /// Set the metadata of the request message + /// Set a metadata value of the request message /// /// the key - /// the value + /// the value as JSON, which may contain matchers void WithRequestMetadata(string key, string value); /// - /// Set the metadata of the response message + /// Set a metadata value of all the existing response messages /// /// the key - /// the value + /// the value as JSON, which may contain matchers void WithResponseMetadata(string key, string value); /// diff --git a/src/PactNet/SyncMessageBuilder.cs b/src/PactNet/SyncMessageBuilder.cs index 94470da8..7f262e1d 100644 --- a/src/PactNet/SyncMessageBuilder.cs +++ b/src/PactNet/SyncMessageBuilder.cs @@ -15,6 +15,10 @@ internal class SyncMessageBuilder : ISyncMessageBuilderV4 private readonly PactConfig config; private readonly PactSpecification version; + // pactffi_with_metadata only applies response metadata to responses that already exist, and the response is + // only created by the terminal WithResponseJsonContent call, so response metadata is applied after it + private readonly List> responseMetadata = new List>(); + /// /// Initialises a new instance of the class. /// @@ -39,11 +43,11 @@ ISyncMessageBuilderV4 ISyncMessageBuilderV4.Given(string providerState, IDiction => Given(providerState, parameters); /// - ISyncMessageBuilderV4 ISyncMessageBuilderV4.WithRequestMetadata(string key, string value) + ISyncMessageBuilderV4 ISyncMessageBuilderV4.WithRequestMetadata(string key, dynamic value) => WithRequestMetadata(key, value); /// - ISyncMessageBuilderV4 ISyncMessageBuilderV4.WithResponseMetadata(string key, string value) + ISyncMessageBuilderV4 ISyncMessageBuilderV4.WithResponseMetadata(string key, dynamic value) => WithResponseMetadata(key, value); /// @@ -93,27 +97,31 @@ internal SyncMessageBuilder Given(string providerState, IDictionary - /// Set the request metadata + /// Set a request metadata value, which is serialised as JSON /// /// key of the metadata /// value of the metadata /// Fluent builder - internal SyncMessageBuilder WithRequestMetadata(string key, string value) + internal SyncMessageBuilder WithRequestMetadata(string key, dynamic value) { - this.driver.WithRequestMetadata(key, value); + string serialised = JsonSerializer.Serialize(value, this.config.DefaultJsonSettings); + + this.driver.WithRequestMetadata(key, serialised); return this; } /// - /// Set the response metadata + /// Set a response metadata value, which is serialised as JSON /// /// key of the metadata /// value of the metadata /// Fluent builder - internal SyncMessageBuilder WithResponseMetadata(string key, string value) + internal SyncMessageBuilder WithResponseMetadata(string key, dynamic value) { - this.driver.WithResponseMetadata(key, value); + string serialised = JsonSerializer.Serialize(value, this.config.DefaultJsonSettings); + + this.responseMetadata.Add(new KeyValuePair(key, serialised)); return this; } @@ -159,6 +167,11 @@ internal ConfiguredSyncMessageVerifier WithResponseJsonContent(dynamic body, Jso this.driver.WithResponseContents("application/json", serialised); + foreach (KeyValuePair metadata in this.responseMetadata) + { + this.driver.WithResponseMetadata(metadata.Key, metadata.Value); + } + return new ConfiguredSyncMessageVerifier(this.driver, this.config, this.version); } } diff --git a/tests/PactNet.Tests/SyncMessageBuilderTests.cs b/tests/PactNet.Tests/SyncMessageBuilderTests.cs index 5c669894..dc2b85e3 100644 --- a/tests/PactNet.Tests/SyncMessageBuilderTests.cs +++ b/tests/PactNet.Tests/SyncMessageBuilderTests.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Text.Json; +using FluentAssertions; using Moq; using PactNet.Drivers; using PactNet.Interop; @@ -60,15 +61,46 @@ public void WithRequestMetadata_WhenCalled_AddsRequestMetadata() { this.builder.WithRequestMetadata("poolId", "1234"); - this.mockDriver.Verify(s => s.WithRequestMetadata("poolId", "1234")); + this.mockDriver.Verify(s => s.WithRequestMetadata("poolId", @"""1234""")); } [Fact] - public void WithResponseMetadata_WhenCalled_AddsResponseMetadata() + public void WithRequestMetadata_TypedValues_KeepsTheirJsonType() { + this.builder.WithRequestMetadata("count", 1234); + this.builder.WithRequestMetadata("enabled", true); + + this.mockDriver.Verify(s => s.WithRequestMetadata("count", "1234")); + this.mockDriver.Verify(s => s.WithRequestMetadata("enabled", "true")); + } + + [Fact] + public void WithRequestMetadata_Matcher_AddsMatcher() + { + this.builder.WithRequestMetadata("poolId", Match.Regex("1234", "^[0-9]{4}$")); + + this.mockDriver.Verify(s => s.WithRequestMetadata("poolId", @"{""pact:matcher:type"":""regex"",""value"":""1234"",""regex"":""^[0-9]{4}$""}")); + } + + [Fact] + public void WithResponseMetadata_WhenCalled_AddsResponseMetadataAfterResponseContent() + { + var calls = new List(); + this.mockDriver + .Setup(s => s.WithResponseContents(It.IsAny(), It.IsAny())) + .Callback(() => calls.Add("contents")); + this.mockDriver + .Setup(s => s.WithResponseMetadata(It.IsAny(), It.IsAny())) + .Callback((string key, string value) => calls.Add($"{key}={value}")); + this.builder.WithResponseMetadata("poolId", "1234"); + this.builder.WithResponseMetadata("region", "eu"); + + calls.Should().BeEmpty("the FFI drops response metadata set before the response exists"); + + this.builder.WithResponseJsonContent(new { Id = 1 }); - this.mockDriver.Verify(s => s.WithResponseMetadata("poolId", "1234")); + calls.Should().Equal("contents", @"poolId=""1234""", @"region=""eu"""); } [Fact] From c22a50cc06eae71fe03df2514079e61dde346cfd Mon Sep 17 00:00:00 2001 From: Fabio Rodrigues Date: Thu, 8 Oct 2026 13:48:21 +0100 Subject: [PATCH 11/15] test: verify sync messages end to end on pact_ffi 0.5.10 Un-skip the FFI integration test now that 0.5.10 ships pactffi_sync_message_generate_contents, and compare the written pact against a fixture. Add public API tests for WithSynchronousMessageInteractions covering body matchers, typed metadata, response metadata matchers and a mismatching response. --- .../Drivers/FfiIntegrationTests.cs | 15 ++- tests/PactNet.Tests/PactExtensionsTests.cs | 56 ++++++++ .../v4-sync-message-consumer-integration.json | 120 ++++++++++++++++++ .../data/v4-sync-message-integration.json | 66 ++++++++++ 4 files changed, 252 insertions(+), 5 deletions(-) create mode 100644 tests/PactNet.Tests/data/v4-sync-message-consumer-integration.json create mode 100644 tests/PactNet.Tests/data/v4-sync-message-integration.json diff --git a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs index e3a5a792..ae965ed7 100644 --- a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs +++ b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs @@ -131,9 +131,7 @@ public void MessageInteraction_v3_CreatesPactFile() pactContents.Should().Be(expectedPactContent); } - [Fact(Skip = "Requires a pact_ffi build with pactffi_sync_message_generate_contents " + - "(see https://github.com/pact-foundation/pact-reference/pull/555); " + - "remove this Skip once that lands in a released pact_ffi version")] + [Fact] public void SyncMessageInteraction_v4_CreatesPactFile() { var driver = new PactDriver(); @@ -146,10 +144,13 @@ public void SyncMessageInteraction_v4_CreatesPactFile() ISyncMessageInteractionDriver interaction = pact.NewSyncMessageInteraction("a sync message interaction"); - interaction.WithRequestMetadata("foo", "bar"); + interaction.WithRequestMetadata("foo", @"""bar"""); + interaction.WithRequestMetadata("count", "42"); interaction.WithRequestContents("application/json", @"{""foo"":42}"); - interaction.WithResponseMetadata("baz", "bash"); + + // response metadata only applies to responses that already exist, so set the contents first interaction.WithResponseContents("application/json", @"{""baz"":42}"); + interaction.WithResponseMetadata("baz", @"{""pact:matcher:type"":""regex"",""value"":""bash"",""regex"":""^ba""}"); string generated = interaction.GenerateContents(); generated.Should().NotBeNullOrEmpty(); @@ -163,6 +164,10 @@ public void SyncMessageInteraction_v4_CreatesPactFile() var file = new FileInfo("NativeDriverTests-Consumer-V4-NativeDriverTests-Producer.json"); file.Exists.Should().BeTrue(); + + string pactContents = File.ReadAllText(file.FullName).TrimEnd(); + string expectedPactContent = File.ReadAllText("data/v4-sync-message-integration.json").TrimEnd(); + pactContents.Should().Be(expectedPactContent); } } } diff --git a/tests/PactNet.Tests/PactExtensionsTests.cs b/tests/PactNet.Tests/PactExtensionsTests.cs index 160205b9..6750ea89 100644 --- a/tests/PactNet.Tests/PactExtensionsTests.cs +++ b/tests/PactNet.Tests/PactExtensionsTests.cs @@ -230,6 +230,56 @@ public void WithMessageInteractions_V4_CreatesExpectedPactFile() actualPact.Should().Be(expectedPact); } + [Fact] + public void WithSynchronousMessageInteractions_V4_CreatesExpectedPactFile() + { + IPactV4 messagePact = Pact.V4("PactExtensionsTests-SyncMessageConsumer-V4", "PactExtensionsTests-SyncMessageProvider", config); + ISyncMessagePactBuilderV4 builder = messagePact.WithSynchronousMessageInteractions(); + + SyncData received = null; + + builder + .WithPactMetadata("framework", "language", "C#") + .ExpectsToReceive("a sample request") + .Given("a provider state") + .Given("a provider state with params", new Dictionary + { + ["foo"] = "bar" + }) + .WithRequestMetadata("queueId", "1234") + .WithRequestMetadata("priority", 1) + .WithRequestJsonContent(new { Int = Match.Integer(1), String = Match.Type("a description") }) + .WithResponseMetadata("replyTo", Match.Regex("queue-1", "^queue-")) + .WithResponseJsonContent(new { Int = Match.Integer(2), String = Match.Type("a reply") }) + .Verify(request => + { + received = request; + return new SyncData { Int = 2, String = "a reply" }; + }); + + received.Should().BeEquivalentTo(new SyncData { Int = 1, String = "a description" }); + + string actualPact = File.ReadAllText("PactExtensionsTests-SyncMessageConsumer-V4-PactExtensionsTests-SyncMessageProvider.json").TrimEnd(); + string expectedPact = File.ReadAllText("data/v4-sync-message-consumer-integration.json").TrimEnd(); + + actualPact.Should().Be(expectedPact); + } + + [Fact] + public void WithSynchronousMessageInteractions_ResponseDoesNotMatch_Throws() + { + IPactV4 messagePact = Pact.V4("PactExtensionsTests-SyncMessageConsumer-Mismatch", "PactExtensionsTests-SyncMessageProvider", config); + + Action action = () => messagePact + .WithSynchronousMessageInteractions() + .ExpectsToReceive("a sample request") + .WithRequestJsonContent(new { Int = 1 }) + .WithResponseJsonContent(new { Int = 2, String = "a reply" }) + .Verify(_ => new SyncData { Int = 3, String = "something else" }); + + action.Should().Throw(); + } + [Fact] public async Task CombinedHttpAndMessageInteractions_v4_CreatesExpectedPactFile() { @@ -307,6 +357,12 @@ private static async Task PerformRequestAsync(IConsumerContext context, TestData responseData.Should().BeEquivalentTo(body); } + public class SyncData + { + public int Int { get; set; } + public string String { get; set; } + } + public class TestData { public bool Bool { get; set; } diff --git a/tests/PactNet.Tests/data/v4-sync-message-consumer-integration.json b/tests/PactNet.Tests/data/v4-sync-message-consumer-integration.json new file mode 100644 index 00000000..95871030 --- /dev/null +++ b/tests/PactNet.Tests/data/v4-sync-message-consumer-integration.json @@ -0,0 +1,120 @@ +{ + "consumer": { + "name": "PactExtensionsTests-SyncMessageConsumer-V4" + }, + "interactions": [ + { + "description": "a sample request", + "pending": false, + "providerStates": [ + { + "name": "a provider state" + }, + { + "name": "a provider state with params", + "params": { + "foo": "bar" + } + } + ], + "request": { + "contents": { + "content": { + "int": 1, + "string": "a description" + }, + "contentType": "application/json", + "encoded": false + }, + "matchingRules": { + "body": { + "$.int": { + "combine": "AND", + "matchers": [ + { + "match": "integer" + } + ] + }, + "$.string": { + "combine": "AND", + "matchers": [ + { + "match": "type" + } + ] + } + } + }, + "metadata": { + "contentType": "application/json", + "priority": 1, + "queueId": "1234" + } + }, + "response": [ + { + "contents": { + "content": { + "int": 2, + "string": "a reply" + }, + "contentType": "application/json", + "encoded": false + }, + "matchingRules": { + "body": { + "$.int": { + "combine": "AND", + "matchers": [ + { + "match": "integer" + } + ] + }, + "$.string": { + "combine": "AND", + "matchers": [ + { + "match": "type" + } + ] + } + }, + "metadata": { + "replyTo": { + "combine": "AND", + "matchers": [ + { + "match": "regex", + "regex": "^queue-" + } + ] + } + } + }, + "metadata": { + "contentType": "application/json", + "replyTo": "queue-1" + } + } + ], + "type": "Synchronous/Messages" + } + ], + "metadata": { + "framework": { + "language": "C#" + }, + "pactRust": { + "ffi": "0.5.10", + "models": "1.3.16" + }, + "pactSpecification": { + "version": "4.0" + } + }, + "provider": { + "name": "PactExtensionsTests-SyncMessageProvider" + } +} \ No newline at end of file diff --git a/tests/PactNet.Tests/data/v4-sync-message-integration.json b/tests/PactNet.Tests/data/v4-sync-message-integration.json new file mode 100644 index 00000000..3fb98df0 --- /dev/null +++ b/tests/PactNet.Tests/data/v4-sync-message-integration.json @@ -0,0 +1,66 @@ +{ + "consumer": { + "name": "NativeDriverTests-Consumer-V4" + }, + "interactions": [ + { + "description": "a sync message interaction", + "pending": false, + "request": { + "contents": { + "content": { + "foo": 42 + }, + "contentType": "application/json", + "encoded": false + }, + "metadata": { + "contentType": "application/json", + "count": 42, + "foo": "bar" + } + }, + "response": [ + { + "contents": { + "content": { + "baz": 42 + }, + "contentType": "application/json", + "encoded": false + }, + "matchingRules": { + "metadata": { + "baz": { + "combine": "AND", + "matchers": [ + { + "match": "regex", + "regex": "^ba" + } + ] + } + } + }, + "metadata": { + "baz": "bash", + "contentType": "application/json" + } + } + ], + "type": "Synchronous/Messages" + } + ], + "metadata": { + "pactRust": { + "ffi": "0.5.10", + "models": "1.3.16" + }, + "pactSpecification": { + "version": "4.0" + } + }, + "provider": { + "name": "NativeDriverTests-Producer" + } +} \ No newline at end of file From 29b2119b25cd634ea361a93b4e820651ec56f0c2 Mon Sep 17 00:00:00 2001 From: Fabio Rodrigues Date: Thu, 8 Oct 2026 13:51:45 +0100 Subject: [PATCH 12/15] feat: add WithReference to synchronous message interactions Links a sync message interaction to an external resource such as an AsyncAPI operation via pactffi_add_interaction_reference, written to comments.references.{group}.{name}. Same signature as the async WithReference proposed in #559. The FFI parses the value as JSON, so the driver encodes it to keep a string reference value a string in the pact. --- docs/messaging-pacts.md | 7 +++++++ .../ISyncMessageBuilder.cs | 10 ++++++++++ .../Message/ISyncMessageInteractionDriver.cs | 8 ++++++++ .../Message/SyncMessageInteractionDriver.cs | 14 ++++++++++++++ src/PactNet/Interop/NativeInterop.cs | 3 +++ src/PactNet/SyncMessageBuilder.cs | 18 ++++++++++++++++++ tests/PactNet.Tests/PactExtensionsTests.cs | 2 ++ tests/PactNet.Tests/SyncMessageBuilderTests.cs | 8 ++++++++ .../v4-sync-message-consumer-integration.json | 8 ++++++++ 9 files changed, 78 insertions(+) diff --git a/docs/messaging-pacts.md b/docs/messaging-pacts.md index 0c9df494..244910de 100644 --- a/docs/messaging-pacts.md +++ b/docs/messaging-pacts.md @@ -192,7 +192,10 @@ public class OrderLookupConsumerTests this.messagePact .ExpectsToReceive("a request for an order") .Given("order 1234 exists") + .WithReference("AsyncAPI", "operationId", "getOrder") + .WithRequestMetadata("priority", 1) .WithRequestJsonContent(new { OrderId = Match.Type("1234") }) + .WithResponseMetadata("replyTo", Match.Regex("orders-reply", "^orders-")) .WithResponseJsonContent(new { Status = Match.Type("shipped") }) .Verify(request => { @@ -203,4 +206,8 @@ public class OrderLookupConsumerTests } ``` +Metadata values are serialised as JSON, so they keep their type (`1` is a number, `"1"` is a string) and can be +matchers. `WithReference` links the interaction to an external resource such as an AsyncAPI operation; it's +written to the pact under `comments.references.{group}.{name}`. + As with fire-and-forget messages, a pact file is written to disk once all consumer tests have passed diff --git a/src/PactNet.Abstractions/ISyncMessageBuilder.cs b/src/PactNet.Abstractions/ISyncMessageBuilder.cs index 334de8d3..55ed0322 100644 --- a/src/PactNet.Abstractions/ISyncMessageBuilder.cs +++ b/src/PactNet.Abstractions/ISyncMessageBuilder.cs @@ -23,6 +23,16 @@ public interface ISyncMessageBuilderV4 /// Fluent builder ISyncMessageBuilderV4 Given(string providerState, IDictionary parameters); + /// + /// Add a reference to an external resource, e.g. an AsyncAPI operation, which is written to the + /// interaction's comments under references.{group}.{name} + /// + /// Reference group, e.g. AsyncAPI + /// Reference name, e.g. operationId + /// Reference value + /// Fluent builder + ISyncMessageBuilderV4 WithReference(string group, string name, string value); + /// /// Set a request metadata value, which is serialised as JSON /// diff --git a/src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs b/src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs index 1338b62f..c44bccfc 100644 --- a/src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs +++ b/src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs @@ -5,6 +5,14 @@ namespace PactNet.Drivers /// internal interface ISyncMessageInteractionDriver : IProviderStateDriver, ICompletedPactDriver { + /// + /// Add a reference to an external resource, e.g. an AsyncAPI operation, to the interaction + /// + /// Reference group, e.g. the name of the external specification + /// Reference name, e.g. operationId + /// Reference value + void AddReference(string group, string name, string value); + /// /// Set a metadata value of the request message /// diff --git a/src/PactNet/Drivers/Message/SyncMessageInteractionDriver.cs b/src/PactNet/Drivers/Message/SyncMessageInteractionDriver.cs index 5f09d5b7..dd5ede06 100644 --- a/src/PactNet/Drivers/Message/SyncMessageInteractionDriver.cs +++ b/src/PactNet/Drivers/Message/SyncMessageInteractionDriver.cs @@ -1,5 +1,6 @@ using System; using System.Runtime.InteropServices; +using System.Text.Json; using PactNet.Interop; namespace PactNet.Drivers @@ -37,6 +38,19 @@ public void Given(string description) public void GivenWithParam(string description, string name, string value) => NativeInterop.GivenWithParam(this.interaction, description, name, value).CheckInteropSuccess(); + /// + /// Add a reference to an external resource, e.g. an AsyncAPI operation, to the interaction + /// + /// Reference group, e.g. the name of the external specification + /// Reference name, e.g. operationId + /// Reference value + /// + /// The FFI parses the value as JSON and only falls back to a string if that fails, so it's encoded first + /// to stop a value like "123" being written as a number + /// + public void AddReference(string group, string name, string value) + => NativeInterop.AddInteractionReference(this.interaction, group, name, JsonSerializer.Serialize(value)).CheckInteropSuccess(); + /// /// Set the metadata of the request message /// diff --git a/src/PactNet/Interop/NativeInterop.cs b/src/PactNet/Interop/NativeInterop.cs index f9909225..1fae3774 100644 --- a/src/PactNet/Interop/NativeInterop.cs +++ b/src/PactNet/Interop/NativeInterop.cs @@ -69,6 +69,9 @@ internal static class NativeInterop [DllImport(DllName, EntryPoint = "pactffi_verify")] public static extern int Verify(string args); + [DllImport(DllName, EntryPoint = "pactffi_add_interaction_reference")] + public static extern bool AddInteractionReference(InteractionHandle interaction, string group, string name, string value); + #endregion Http Interop Support #region Messaging Interop Support diff --git a/src/PactNet/SyncMessageBuilder.cs b/src/PactNet/SyncMessageBuilder.cs index 7f262e1d..55af2e01 100644 --- a/src/PactNet/SyncMessageBuilder.cs +++ b/src/PactNet/SyncMessageBuilder.cs @@ -42,6 +42,10 @@ ISyncMessageBuilderV4 ISyncMessageBuilderV4.Given(string providerState) ISyncMessageBuilderV4 ISyncMessageBuilderV4.Given(string providerState, IDictionary parameters) => Given(providerState, parameters); + /// + ISyncMessageBuilderV4 ISyncMessageBuilderV4.WithReference(string group, string name, string value) + => WithReference(group, name, value); + /// ISyncMessageBuilderV4 ISyncMessageBuilderV4.WithRequestMetadata(string key, dynamic value) => WithRequestMetadata(key, value); @@ -96,6 +100,20 @@ internal SyncMessageBuilder Given(string providerState, IDictionary + /// Add a reference to an external resource, e.g. an AsyncAPI operation + /// + /// Reference group + /// Reference name + /// Reference value + /// Fluent builder + internal SyncMessageBuilder WithReference(string group, string name, string value) + { + this.driver.AddReference(group, name, value); + + return this; + } + /// /// Set a request metadata value, which is serialised as JSON /// diff --git a/tests/PactNet.Tests/PactExtensionsTests.cs b/tests/PactNet.Tests/PactExtensionsTests.cs index 6750ea89..475b91c2 100644 --- a/tests/PactNet.Tests/PactExtensionsTests.cs +++ b/tests/PactNet.Tests/PactExtensionsTests.cs @@ -246,6 +246,8 @@ public void WithSynchronousMessageInteractions_V4_CreatesExpectedPactFile() { ["foo"] = "bar" }) + .WithReference("AsyncAPI", "operationId", "getOrder") + .WithReference("AsyncAPI", "version", "123") .WithRequestMetadata("queueId", "1234") .WithRequestMetadata("priority", 1) .WithRequestJsonContent(new { Int = Match.Integer(1), String = Match.Type("a description") }) diff --git a/tests/PactNet.Tests/SyncMessageBuilderTests.cs b/tests/PactNet.Tests/SyncMessageBuilderTests.cs index dc2b85e3..5efad3a9 100644 --- a/tests/PactNet.Tests/SyncMessageBuilderTests.cs +++ b/tests/PactNet.Tests/SyncMessageBuilderTests.cs @@ -56,6 +56,14 @@ public void Given_WithParams_AddsProviderState() this.mockDriver.Verify(s => s.GivenWithParam("provider state", "baz", "bash")); } + [Fact] + public void WithReference_WhenCalled_AddsReference() + { + this.builder.WithReference("AsyncAPI", "operationId", "getOrder"); + + this.mockDriver.Verify(s => s.AddReference("AsyncAPI", "operationId", "getOrder")); + } + [Fact] public void WithRequestMetadata_WhenCalled_AddsRequestMetadata() { diff --git a/tests/PactNet.Tests/data/v4-sync-message-consumer-integration.json b/tests/PactNet.Tests/data/v4-sync-message-consumer-integration.json index 95871030..2e4408a2 100644 --- a/tests/PactNet.Tests/data/v4-sync-message-consumer-integration.json +++ b/tests/PactNet.Tests/data/v4-sync-message-consumer-integration.json @@ -4,6 +4,14 @@ }, "interactions": [ { + "comments": { + "references": { + "AsyncAPI": { + "operationId": "getOrder", + "version": "123" + } + } + }, "description": "a sample request", "pending": false, "providerStates": [ From bc34c5c852e90df177c28b262a66e016fd32e2a2 Mon Sep 17 00:00:00 2001 From: Fabio Rodrigues Date: Thu, 8 Oct 2026 14:15:11 +0100 Subject: [PATCH 13/15] feat: match the sync handler's response against the response matchers Verify/VerifyAsync compared the handler's response to the generated example by exact JSON equality, so a type matcher still required the example value. They now call pactffi_sync_message_match_response_contents, which applies the response's matching rules the same way the verifier does: Match.Type checks the type of the example, Match.Integer and Match.Decimal the kind of number, Match.Regex the format (e.g. datetimes), and unexpected keys are allowed. Mismatches are reported by path. Requires a pact_ffi release with pactffi_sync_message_match_response_contents. --- src/PactNet/ConfiguredSyncMessageVerifier.cs | 125 ++++-------------- .../Message/ISyncMessageInteractionDriver.cs | 9 ++ .../Message/SyncMessageInteractionDriver.cs | 21 +++ src/PactNet/Interop/NativeInterop.cs | 3 + .../ConfiguredSyncMessageVerifierTests.cs | 28 ++++ tests/PactNet.Tests/PactExtensionsTests.cs | 29 +++- 6 files changed, 117 insertions(+), 98 deletions(-) diff --git a/src/PactNet/ConfiguredSyncMessageVerifier.cs b/src/PactNet/ConfiguredSyncMessageVerifier.cs index ff9b9d1e..0c4d9522 100644 --- a/src/PactNet/ConfiguredSyncMessageVerifier.cs +++ b/src/PactNet/ConfiguredSyncMessageVerifier.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Linq; using System.Text.Json; using System.Threading.Tasks; using PactNet.Drivers; @@ -51,7 +53,7 @@ public void Verify(Func handler) TResponse actualResponse = handler(request); - this.VerifyResponse(generated, actualResponse); + this.VerifyResponse(actualResponse); this.driver.WritePactFile(this.config.PactDir); } catch (PactMessageConsumerVerificationException) @@ -78,7 +80,7 @@ public async Task VerifyAsync(Func - /// Check the handler's response against the configured response content + /// Check the handler's response against the configured response, applying its matching rules /// - /// the generated message /// the response returned by the handler under test - private void VerifyResponse(NativeSyncMessage generated, TResponse actualResponse) + private void VerifyResponse(TResponse actualResponse) { - JsonElement expectedContent = ((JsonElement)generated.Response[0].Contents).GetProperty("content"); - string actualJson = JsonSerializer.Serialize(actualResponse, this.config.DefaultJsonSettings); - using JsonDocument actualDocument = JsonDocument.Parse(actualJson); + string mismatchesJson = this.driver.MatchResponseContents(0, "application/json", actualJson); + + using JsonDocument mismatches = JsonDocument.Parse(mismatchesJson); - if (!JsonElementsEqual(expectedContent, actualDocument.RootElement)) + if (mismatches.RootElement.GetArrayLength() > 0) { + IEnumerable descriptions = mismatches.RootElement + .EnumerateArray() + .Select(DescribeMismatch); + throw new PactMessageConsumerVerificationException( - $"The response returned by the consumer handler did not match the configured response content. " + - $"Expected {expectedContent.GetRawText()} but got {actualJson}"); + "The response returned by the consumer handler did not match the configured response:" + + Environment.NewLine + string.Join(Environment.NewLine, descriptions)); } } + /// + /// Describe a mismatch returned by the FFI, e.g. "$.status: Expected 1 (Integer) to be the same type as 'shipped' (String)" + /// + private static string DescribeMismatch(JsonElement mismatch) + { + string description = mismatch.TryGetProperty("mismatch", out JsonElement text) ? text.GetString() : mismatch.GetRawText(); + + return mismatch.TryGetProperty("path", out JsonElement path) + ? $" {path.GetString()}: {description}" + : $" {description}"; + } + /// /// Deserialize the content of the request or response, with any matchers removed and any /// configured generators applied @@ -136,91 +153,5 @@ private T DeserializeContent(JsonElement contents) return JsonSerializer.Deserialize(contentString, this.config.DefaultJsonSettings); } - - /// - /// Recursively compare two JSON elements for structural equality, ignoring object property order - /// - private static bool JsonElementsEqual(JsonElement expected, JsonElement actual) - { - if (expected.ValueKind != actual.ValueKind) - { - return false; - } - - switch (expected.ValueKind) - { - case JsonValueKind.Object: - var expectedProperties = new System.Collections.Generic.Dictionary(StringComparer.Ordinal); - foreach (JsonProperty property in expected.EnumerateObject()) - { - expectedProperties[property.Name] = property.Value; - } - - var actualProperties = new System.Collections.Generic.Dictionary(StringComparer.Ordinal); - foreach (JsonProperty property in actual.EnumerateObject()) - { - actualProperties[property.Name] = property.Value; - } - - if (expectedProperties.Count != actualProperties.Count) - { - return false; - } - - foreach (var property in expectedProperties) - { - if (!actualProperties.TryGetValue(property.Key, out JsonElement actualValue) || - !JsonElementsEqual(property.Value, actualValue)) - { - return false; - } - } - - return true; - - case JsonValueKind.Array: - var expectedItems = new System.Collections.Generic.List(); - foreach (JsonElement item in expected.EnumerateArray()) - { - expectedItems.Add(item); - } - - var actualItems = new System.Collections.Generic.List(); - foreach (JsonElement item in actual.EnumerateArray()) - { - actualItems.Add(item); - } - - if (expectedItems.Count != actualItems.Count) - { - return false; - } - - for (int i = 0; i < expectedItems.Count; i++) - { - if (!JsonElementsEqual(expectedItems[i], actualItems[i])) - { - return false; - } - } - - return true; - - case JsonValueKind.String: - return expected.GetString() == actual.GetString(); - - case JsonValueKind.Number: - return expected.GetRawText() == actual.GetRawText(); - - case JsonValueKind.True: - case JsonValueKind.False: - case JsonValueKind.Null: - case JsonValueKind.Undefined: - return true; - - default: - return expected.GetRawText() == actual.GetRawText(); - } - } } } diff --git a/src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs b/src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs index c44bccfc..3154c44f 100644 --- a/src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs +++ b/src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs @@ -47,5 +47,14 @@ internal interface ISyncMessageInteractionDriver : IProviderStateDriver, IComple /// /// The generated request and response contents string GenerateContents(); + + /// + /// Match actual contents against an expected response, applying the response's matching rules + /// + /// Index of the expected response + /// Content type of the actual contents + /// Actual contents + /// JSON array of mismatches, which is empty if the contents matched + string MatchResponseContents(int index, string contentType, string contents); } } diff --git a/src/PactNet/Drivers/Message/SyncMessageInteractionDriver.cs b/src/PactNet/Drivers/Message/SyncMessageInteractionDriver.cs index dd5ede06..c34620a6 100644 --- a/src/PactNet/Drivers/Message/SyncMessageInteractionDriver.cs +++ b/src/PactNet/Drivers/Message/SyncMessageInteractionDriver.cs @@ -95,5 +95,26 @@ public string GenerateContents() NativeInterop.FreeString(pointer); return body; } + + /// + /// Match actual contents against an expected response, applying the response's matching rules + /// + /// Index of the expected response + /// Content type of the actual contents + /// Actual contents + /// JSON array of mismatches, which is empty if the contents matched + public string MatchResponseContents(int index, string contentType, string contents) + { + IntPtr pointer = NativeInterop.SyncMessageMatchResponseContents(this.interaction, new UIntPtr((uint)index), contentType, contents); + + if (pointer == IntPtr.Zero) + { + throw new InvalidOperationException($"Unable to match the response contents against expected response {index}"); + } + + string mismatches = Marshal.PtrToStringAnsi(pointer); + NativeInterop.FreeString(pointer); + return mismatches; + } } } diff --git a/src/PactNet/Interop/NativeInterop.cs b/src/PactNet/Interop/NativeInterop.cs index 1fae3774..33705822 100644 --- a/src/PactNet/Interop/NativeInterop.cs +++ b/src/PactNet/Interop/NativeInterop.cs @@ -103,6 +103,9 @@ internal static class NativeInterop [DllImport(DllName, EntryPoint = "pactffi_sync_message_generate_contents")] public static extern IntPtr SyncMessageGenerateContents(InteractionHandle message); + [DllImport(DllName, EntryPoint = "pactffi_sync_message_match_response_contents")] + public static extern IntPtr SyncMessageMatchResponseContents(InteractionHandle message, UIntPtr index, string contentType, string contents); + #endregion Http Interop Support #region Verifier Support diff --git a/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs b/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs index 71705aa0..b831411d 100644 --- a/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs +++ b/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs @@ -81,6 +81,27 @@ public void Verify_ResponseDoesNotMatchConfiguredResponse_ThrowsVerificationExce action.Should().Throw(); } + [Fact] + public void Verify_ResponseDoesNotMatchConfiguredResponse_ReportsMismatches() + { + (var verifier, _) = this.SetupMessage(); + + Action action = () => verifier.Verify(_ => new Response { Status = "not-ok" }); + + action.Should().Throw() + .WithMessage("*$.status: Expected 'not-ok' to be equal to 'ok'*"); + } + + [Fact] + public void Verify_WhenCalled_MatchesResponseSerialisedWithUserSettings() + { + (var verifier, _) = this.SetupMessage(); + + verifier.Verify(_ => new Response { Status = "ok" }); + + this.mockDriver.Verify(s => s.MatchResponseContents(0, "application/json", @"{""status"":""ok""}")); + } + [Fact] public void Verify_ResponseDoesNotMatchConfiguredResponse_DoesNotWritePactFile() { @@ -177,6 +198,13 @@ public async Task VerifyAsync_ResponseDoesNotMatchConfiguredResponse_DoesNotWrit .Setup(s => s.GenerateContents()) .Returns(JsonSerializer.Serialize(native, CamelCase)); + // simulates the FFI applying the response matching rules + this.mockDriver + .Setup(s => s.MatchResponseContents(0, "application/json", It.IsAny())) + .Returns((int _, string _, string actual) => actual == @"{""status"":""ok""}" + ? "[]" + : @"[{""type"":""BodyMismatch"",""path"":""$.status"",""mismatch"":""Expected 'not-ok' to be equal to 'ok'""}]"); + return (verifier, request); } diff --git a/tests/PactNet.Tests/PactExtensionsTests.cs b/tests/PactNet.Tests/PactExtensionsTests.cs index 475b91c2..3b1c3e8f 100644 --- a/tests/PactNet.Tests/PactExtensionsTests.cs +++ b/tests/PactNet.Tests/PactExtensionsTests.cs @@ -8,6 +8,7 @@ using System.Text.Json.Serialization; using System.Threading.Tasks; using FluentAssertions; +using PactNet.Exceptions; using PactNet.Matchers; using PactNet.Output.Xunit; using Xunit; @@ -256,7 +257,9 @@ public void WithSynchronousMessageInteractions_V4_CreatesExpectedPactFile() .Verify(request => { received = request; - return new SyncData { Int = 2, String = "a reply" }; + + // matched against the response matchers, not the example values + return new SyncData { Int = 7, String = "another reply" }; }); received.Should().BeEquivalentTo(new SyncData { Int = 1, String = "a description" }); @@ -267,6 +270,30 @@ public void WithSynchronousMessageInteractions_V4_CreatesExpectedPactFile() actualPact.Should().Be(expectedPact); } + [Theory] + [InlineData("2026-01-01 10:00:00", true)] + [InlineData("01/01/2026", false)] + public void WithSynchronousMessageInteractions_RegexMatcher_ChecksResponseFormat(string actual, bool matches) + { + IPactV4 messagePact = Pact.V4("PactExtensionsTests-SyncMessageConsumer-Regex", "PactExtensionsTests-SyncMessageProvider", config); + + Action action = () => messagePact + .WithSynchronousMessageInteractions() + .ExpectsToReceive("a sample request") + .WithRequestJsonContent(new { Int = 1 }) + .WithResponseJsonContent(new { Int = Match.Integer(2), String = Match.Regex("2024-10-12 03:31:11", @"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$") }) + .Verify(_ => new SyncData { Int = 3, String = actual }); + + if (matches) + { + action.Should().NotThrow(); + } + else + { + action.Should().Throw().WithMessage("*$.string*"); + } + } + [Fact] public void WithSynchronousMessageInteractions_ResponseDoesNotMatch_Throws() { From b946d4f3465779639dba27b186616fed48c789d3 Mon Sep 17 00:00:00 2001 From: Fabio Rodrigues Date: Thu, 8 Oct 2026 14:15:37 +0100 Subject: [PATCH 14/15] docs: describe how sync message responses are matched --- docs/messaging-pacts.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/messaging-pacts.md b/docs/messaging-pacts.md index 244910de..a012702a 100644 --- a/docs/messaging-pacts.md +++ b/docs/messaging-pacts.md @@ -162,8 +162,11 @@ Synchronous (Request/Response) Messages Unlike the fire-and-forget messages above, a synchronous message interaction has both a request and a response. The consumer specifies the expected request and response content, PactNet feeds the -generated request to your handler under test, and checks that the value your handler returns matches -the generated response content (matchers stripped, generators applied) before writing the pact file. +generated request (matchers stripped, generators applied) to your handler under test, and checks the +value your handler returns against the response's matchers before writing the pact file. For example +`Match.Type("shipped")` accepts any string, `Match.Integer(12)` any integer, `Match.Decimal(12.5)` any +decimal, and `Match.Regex(...)` any value in the given format, such as a datetime. Values without a +matcher must be equal, and extra properties in the response are allowed. In code, this is: From c1acf8d5ed63c88f7730ec1534b348cfc9e3bf4a Mon Sep 17 00:00:00 2001 From: Fabio Rodrigues Date: Fri, 16 Oct 2026 14:09:40 +0100 Subject: [PATCH 15/15] test: bump sync message fixtures to pact-ffi 0.5.12 Aligns the sync message integration fixtures with the ffi 0.5.12 / models 1.3.17 metadata from the pact-ffi upgrade. --- .../data/v4-sync-message-consumer-integration.json | 4 ++-- tests/PactNet.Tests/data/v4-sync-message-integration.json | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/PactNet.Tests/data/v4-sync-message-consumer-integration.json b/tests/PactNet.Tests/data/v4-sync-message-consumer-integration.json index 2e4408a2..49926295 100644 --- a/tests/PactNet.Tests/data/v4-sync-message-consumer-integration.json +++ b/tests/PactNet.Tests/data/v4-sync-message-consumer-integration.json @@ -115,8 +115,8 @@ "language": "C#" }, "pactRust": { - "ffi": "0.5.10", - "models": "1.3.16" + "ffi": "0.5.12", + "models": "1.3.17" }, "pactSpecification": { "version": "4.0" diff --git a/tests/PactNet.Tests/data/v4-sync-message-integration.json b/tests/PactNet.Tests/data/v4-sync-message-integration.json index 3fb98df0..cfa5d369 100644 --- a/tests/PactNet.Tests/data/v4-sync-message-integration.json +++ b/tests/PactNet.Tests/data/v4-sync-message-integration.json @@ -53,8 +53,8 @@ ], "metadata": { "pactRust": { - "ffi": "0.5.10", - "models": "1.3.16" + "ffi": "0.5.12", + "models": "1.3.17" }, "pactSpecification": { "version": "4.0"