From a051eea3bdc9acd65735ab9056861d96d0485299 Mon Sep 17 00:00:00 2001 From: Adam Rodger Date: Sat, 20 Sep 2025 21:09:29 +0100 Subject: [PATCH 01/35] feat: Interop calls and internal interface code to support plugins This enables creating a nicer API to expose publicly for use by plugin wrappers. See: #492 --- src/PactNet/ConfiguredMessageVerifier.cs | 2 +- .../{ => Http}/HttpInteractionDriver.cs | 2 +- .../Drivers/{ => Http}/HttpPactDriver.cs | 2 +- .../{ => Http}/IHttpInteractionDriver.cs | 2 +- .../Drivers/{ => Http}/IHttpPactDriver.cs | 2 +- src/PactNet/Drivers/IPactDriver.cs | 4 +- .../IMessageInteractionDriver.cs | 2 +- .../{ => Message}/IMessagePactDriver.cs | 2 +- .../{ => Message}/MessageInteractionDriver.cs | 2 +- .../{ => Message}/MessagePactDriver.cs | 2 +- src/PactNet/Drivers/PactDriver.cs | 56 ++++++++++++++-- .../Plugins/IPluginInteractionDriver.cs | 15 +++++ .../Drivers/Plugins/IPluginPactDriver.cs | 28 ++++++++ .../Plugins/PluginInteractionDriver.cs | 65 +++++++++++++++++++ .../Drivers/Plugins/PluginPactDriver.cs | 62 ++++++++++++++++++ src/PactNet/Interop/NativeInterop.cs | 16 +++++ src/PactNet/MessageBuilder.cs | 2 +- src/PactNet/MessagePactBuilder.cs | 2 +- src/PactNet/PactBuilder.cs | 1 + src/PactNet/PactExtensions.cs | 2 + src/PactNet/RequestBuilder.cs | 2 +- src/PactNet/ResponseBuilder.cs | 2 +- .../ConfiguredMessageVerifierTests.cs | 2 +- .../Drivers/FfiIntegrationTests.cs | 2 + tests/PactNet.Tests/MessageBuilderTests.cs | 2 +- .../PactNet.Tests/MessagePactBuilderTests.cs | 2 +- tests/PactNet.Tests/PactBuilderTests.cs | 1 + tests/PactNet.Tests/RequestBuilderTests.cs | 2 +- tests/PactNet.Tests/ResponseBuilderTests.cs | 2 +- 29 files changed, 263 insertions(+), 25 deletions(-) rename src/PactNet/Drivers/{ => Http}/HttpInteractionDriver.cs (99%) rename src/PactNet/Drivers/{ => Http}/HttpPactDriver.cs (98%) rename src/PactNet/Drivers/{ => Http}/IHttpInteractionDriver.cs (98%) rename src/PactNet/Drivers/{ => Http}/IHttpPactDriver.cs (97%) rename src/PactNet/Drivers/{ => Message}/IMessageInteractionDriver.cs (97%) rename src/PactNet/Drivers/{ => Message}/IMessagePactDriver.cs (95%) rename src/PactNet/Drivers/{ => Message}/MessageInteractionDriver.cs (98%) rename src/PactNet/Drivers/{ => Message}/MessagePactDriver.cs (97%) create mode 100644 src/PactNet/Drivers/Plugins/IPluginInteractionDriver.cs create mode 100644 src/PactNet/Drivers/Plugins/IPluginPactDriver.cs create mode 100644 src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs create mode 100644 src/PactNet/Drivers/Plugins/PluginPactDriver.cs diff --git a/src/PactNet/ConfiguredMessageVerifier.cs b/src/PactNet/ConfiguredMessageVerifier.cs index 45f125d24..46b758f36 100644 --- a/src/PactNet/ConfiguredMessageVerifier.cs +++ b/src/PactNet/ConfiguredMessageVerifier.cs @@ -1,7 +1,7 @@ using System; using System.Text.Json; using System.Threading.Tasks; -using PactNet.Drivers; +using PactNet.Drivers.Message; using PactNet.Exceptions; using PactNet.Interop; using PactNet.Models; diff --git a/src/PactNet/Drivers/HttpInteractionDriver.cs b/src/PactNet/Drivers/Http/HttpInteractionDriver.cs similarity index 99% rename from src/PactNet/Drivers/HttpInteractionDriver.cs rename to src/PactNet/Drivers/Http/HttpInteractionDriver.cs index a91d6b4f2..fd6520a90 100644 --- a/src/PactNet/Drivers/HttpInteractionDriver.cs +++ b/src/PactNet/Drivers/Http/HttpInteractionDriver.cs @@ -1,7 +1,7 @@ using System; using PactNet.Interop; -namespace PactNet.Drivers +namespace PactNet.Drivers.Http { /// /// Driver for synchronous HTTP interactions diff --git a/src/PactNet/Drivers/HttpPactDriver.cs b/src/PactNet/Drivers/Http/HttpPactDriver.cs similarity index 98% rename from src/PactNet/Drivers/HttpPactDriver.cs rename to src/PactNet/Drivers/Http/HttpPactDriver.cs index 52026bff8..19572cac0 100644 --- a/src/PactNet/Drivers/HttpPactDriver.cs +++ b/src/PactNet/Drivers/Http/HttpPactDriver.cs @@ -1,7 +1,7 @@ using System; using PactNet.Interop; -namespace PactNet.Drivers +namespace PactNet.Drivers.Http { /// /// Driver for synchronous HTTP pacts diff --git a/src/PactNet/Drivers/IHttpInteractionDriver.cs b/src/PactNet/Drivers/Http/IHttpInteractionDriver.cs similarity index 98% rename from src/PactNet/Drivers/IHttpInteractionDriver.cs rename to src/PactNet/Drivers/Http/IHttpInteractionDriver.cs index ccb1473e0..653ce2fcb 100644 --- a/src/PactNet/Drivers/IHttpInteractionDriver.cs +++ b/src/PactNet/Drivers/Http/IHttpInteractionDriver.cs @@ -1,4 +1,4 @@ -namespace PactNet.Drivers +namespace PactNet.Drivers.Http { /// /// Driver for synchronous HTTP interactions diff --git a/src/PactNet/Drivers/IHttpPactDriver.cs b/src/PactNet/Drivers/Http/IHttpPactDriver.cs similarity index 97% rename from src/PactNet/Drivers/IHttpPactDriver.cs rename to src/PactNet/Drivers/Http/IHttpPactDriver.cs index 8cb815ffb..38895d25e 100644 --- a/src/PactNet/Drivers/IHttpPactDriver.cs +++ b/src/PactNet/Drivers/Http/IHttpPactDriver.cs @@ -1,6 +1,6 @@ using System; -namespace PactNet.Drivers +namespace PactNet.Drivers.Http { /// /// Driver for synchronous HTTP pacts diff --git a/src/PactNet/Drivers/IPactDriver.cs b/src/PactNet/Drivers/IPactDriver.cs index 449aac9a4..a787052b9 100644 --- a/src/PactNet/Drivers/IPactDriver.cs +++ b/src/PactNet/Drivers/IPactDriver.cs @@ -1,4 +1,6 @@ -using PactNet.Interop; +using PactNet.Drivers.Http; +using PactNet.Drivers.Message; +using PactNet.Interop; namespace PactNet.Drivers { diff --git a/src/PactNet/Drivers/IMessageInteractionDriver.cs b/src/PactNet/Drivers/Message/IMessageInteractionDriver.cs similarity index 97% rename from src/PactNet/Drivers/IMessageInteractionDriver.cs rename to src/PactNet/Drivers/Message/IMessageInteractionDriver.cs index 964b8377f..ec3ec38fb 100644 --- a/src/PactNet/Drivers/IMessageInteractionDriver.cs +++ b/src/PactNet/Drivers/Message/IMessageInteractionDriver.cs @@ -1,4 +1,4 @@ -namespace PactNet.Drivers +namespace PactNet.Drivers.Message { /// /// Driver for asynchronous message interactions diff --git a/src/PactNet/Drivers/IMessagePactDriver.cs b/src/PactNet/Drivers/Message/IMessagePactDriver.cs similarity index 95% rename from src/PactNet/Drivers/IMessagePactDriver.cs rename to src/PactNet/Drivers/Message/IMessagePactDriver.cs index 4999226a6..a5c724c86 100644 --- a/src/PactNet/Drivers/IMessagePactDriver.cs +++ b/src/PactNet/Drivers/Message/IMessagePactDriver.cs @@ -1,4 +1,4 @@ -namespace PactNet.Drivers +namespace PactNet.Drivers.Message { /// /// Driver for message pacts diff --git a/src/PactNet/Drivers/MessageInteractionDriver.cs b/src/PactNet/Drivers/Message/MessageInteractionDriver.cs similarity index 98% rename from src/PactNet/Drivers/MessageInteractionDriver.cs rename to src/PactNet/Drivers/Message/MessageInteractionDriver.cs index 035f8f4cc..58ee7128f 100644 --- a/src/PactNet/Drivers/MessageInteractionDriver.cs +++ b/src/PactNet/Drivers/Message/MessageInteractionDriver.cs @@ -2,7 +2,7 @@ using System.Runtime.InteropServices; using PactNet.Interop; -namespace PactNet.Drivers +namespace PactNet.Drivers.Message { /// /// Driver for asynchronous message interactions diff --git a/src/PactNet/Drivers/MessagePactDriver.cs b/src/PactNet/Drivers/Message/MessagePactDriver.cs similarity index 97% rename from src/PactNet/Drivers/MessagePactDriver.cs rename to src/PactNet/Drivers/Message/MessagePactDriver.cs index 11b99c39e..91a43a62c 100644 --- a/src/PactNet/Drivers/MessagePactDriver.cs +++ b/src/PactNet/Drivers/Message/MessagePactDriver.cs @@ -1,6 +1,6 @@ using PactNet.Interop; -namespace PactNet.Drivers +namespace PactNet.Drivers.Message { /// /// Driver for message pacts diff --git a/src/PactNet/Drivers/PactDriver.cs b/src/PactNet/Drivers/PactDriver.cs index bce352796..8cb8624cf 100644 --- a/src/PactNet/Drivers/PactDriver.cs +++ b/src/PactNet/Drivers/PactDriver.cs @@ -1,4 +1,8 @@ -using PactNet.Interop; +using PactNet.Drivers.Http; +using PactNet.Drivers.Message; +using PactNet.Drivers.Plugins; +using PactNet.Exceptions; +using PactNet.Interop; namespace PactNet.Drivers { @@ -16,9 +20,7 @@ internal class PactDriver : IPactDriver /// HTTP pact driver public IHttpPactDriver NewHttpPact(string consumerName, string providerName, PactSpecification version) { - PactHandle pact = NativeInterop.NewPact(consumerName, providerName); - NativeInterop.WithSpecification(pact, version).CheckInteropSuccess(); - + PactHandle pact = CreatePactHandle(consumerName, providerName, version); return new HttpPactDriver(pact); } @@ -28,13 +30,55 @@ public IHttpPactDriver NewHttpPact(string consumerName, string providerName, Pac /// Consumer name /// Provider name /// Specification version - /// Message pact driver driver + /// Message pact driver public IMessagePactDriver NewMessagePact(string consumerName, string providerName, PactSpecification version) + { + PactHandle pact = CreatePactHandle(consumerName, providerName, version); + return new MessagePactDriver(pact); + } + + /// + /// Create a new plugin pact + /// + /// Consumer name + /// Provider name + /// Plugin name + /// Plugin version + /// Specification version + /// Plugin pact driver + public IPluginPactDriver NewPluginPact(string consumerName, string providerName, string pluginName, string pluginVersion, PactSpecification version) { PactHandle pact = NativeInterop.NewPact(consumerName, providerName); NativeInterop.WithSpecification(pact, version).CheckInteropSuccess(); - return new MessagePactDriver(pact); + uint code = NativeInterop.UsingPlugin(pact, pluginName, pluginVersion); + + if (code == 0) + { + return new PluginPactDriver(pact); + } + + throw code switch + { + 1 => new PactFailureException("Unable to setup the plugin - general panic"), + 2 => new PactFailureException("Unable to setup the plugin - invalid plugin name or version"), + 3 => new PactFailureException("Unable to setup the plugin - invalid pact handle"), + _ => new PactFailureException($"Unable to setup the plugin - unknown error {code}") + }; + } + + /// + /// Create a new pact handle and set the specification version + /// + /// Consumer name + /// Provider name + /// Specification version + /// Pact handle + private static PactHandle CreatePactHandle(string consumerName, string providerName, PactSpecification version) + { + PactHandle pact = NativeInterop.NewPact(consumerName, providerName); + NativeInterop.WithSpecification(pact, version).CheckInteropSuccess(); + return pact; } /// diff --git a/src/PactNet/Drivers/Plugins/IPluginInteractionDriver.cs b/src/PactNet/Drivers/Plugins/IPluginInteractionDriver.cs new file mode 100644 index 000000000..9cc90aa6e --- /dev/null +++ b/src/PactNet/Drivers/Plugins/IPluginInteractionDriver.cs @@ -0,0 +1,15 @@ +namespace PactNet.Drivers.Plugins +{ + /// + /// Driver for plugin interactions + /// + internal interface IPluginInteractionDriver : IProviderStateDriver + { + /// + /// Add a plugin interaction content + /// + /// Content type + /// Content + void WithContent(string contentType, string content); + } +} diff --git a/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs b/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs new file mode 100644 index 000000000..1e635f5a9 --- /dev/null +++ b/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs @@ -0,0 +1,28 @@ +using System; + +namespace PactNet.Drivers.Plugins +{ + /// + /// Driver for plugin-based pacts + /// + internal interface IPluginPactDriver : ICompletedPactDriver + { + /// + /// Create a new sync interaction on the current pact + /// + /// Interaction description + /// Interaction driver + IPluginInteractionDriver NewSyncInteraction(string description); + + /// + /// Create the mock server for the current pact + /// + /// Host for the mock server + /// Port for the mock server, or null to allocate one automatically + /// Transport - e.g. http, https, grpc + /// Transport config string + /// Mock server port + /// Failed to start mock server + IMockServerDriver CreateMockServer(string host, int? port, string transport, string transportConfig); + } +} diff --git a/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs b/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs new file mode 100644 index 000000000..e4969c479 --- /dev/null +++ b/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs @@ -0,0 +1,65 @@ +using PactNet.Exceptions; +using PactNet.Interop; + +namespace PactNet.Drivers.Plugins +{ + /// + /// Driver for plugin interactions + /// + internal class PluginInteractionDriver : IPluginInteractionDriver + { + private readonly PactHandle pact; + private readonly InteractionHandle interaction; + + /// + /// Initialises a new instance of the class. + /// + /// Pact handle + /// Interaction handle + public PluginInteractionDriver(PactHandle pact, InteractionHandle interaction) + { + this.pact = 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(); + + /// + /// Add a plugin interaction content + /// + /// Content type + /// Content + public void WithContent(string contentType, string content) + { + uint code = NativeInterop.InteractionContents(this.interaction, InteractionPart.Request, contentType, content); + + if (code != 0) + { + throw code switch + { + 1 => new PactFailureException("A general panic was caught"), + 2 => new PactFailureException("The mock server has already been started"), + 3 => new PactFailureException("The interaction handle is invalid"), + 4 => new PactFailureException("The content type is not valid"), + 5 => new PactFailureException("The contents JSON is not valid JSON"), + 6 => new PactFailureException("The plugin returned an error"), + _ => new PactFailureException($"An unknown error occurred when setting the interaction contents: {code}"), + }; + } + } + } +} diff --git a/src/PactNet/Drivers/Plugins/PluginPactDriver.cs b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs new file mode 100644 index 000000000..bfa4cd9cb --- /dev/null +++ b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs @@ -0,0 +1,62 @@ +using System; +using PactNet.Interop; + +namespace PactNet.Drivers.Plugins +{ + /// + /// Driver for plugin-based pacts + /// + internal class PluginPactDriver : AbstractPactDriver, IPluginPactDriver + { + private readonly PactHandle pact; + + /// + /// Initialize a new instance of the class. + /// + /// Pact handle + internal PluginPactDriver(PactHandle pact) : base(pact) + { + this.pact = pact; + } + + /// + /// Create a new sync interaction on the current pact + /// + /// Interaction description + /// Interaction driver + public IPluginInteractionDriver NewSyncInteraction(string description) + { + InteractionHandle interaction = NativeInterop.NewSyncMessageInteraction(this.pact, description); + return new PluginInteractionDriver(this.pact, interaction); + } + + /// + /// Create the mock server for the current pact + /// + /// Host for the mock server + /// Port for the mock server, or null to allocate one automatically + /// Transport - e.g. http, https, grpc + /// Transport config string + /// Mock server port + /// Failed to start mock server + public IMockServerDriver CreateMockServer(string host, int? port, string transport, string transportConfig) + { + int result = NativeInterop.CreateMockServerForTransport(this.pact, host, (ushort)port.GetValueOrDefault(0), transport, transportConfig); + + if (result > 0) + { + return new MockServerDriver(host, result, false); + } + + throw result switch + { + -1 => new InvalidOperationException("Invalid handle when starting mock server"), + -2 => new InvalidOperationException("The transport config is not valid JSON"), + -3 => new InvalidOperationException("Unable to start mock server"), + -4 => new InvalidOperationException("The pact reference library panicked"), + -5 => new InvalidOperationException("The IPAddress is invalid"), + _ => new InvalidOperationException($"Unknown mock server error: {result}") + }; + } + } +} diff --git a/src/PactNet/Interop/NativeInterop.cs b/src/PactNet/Interop/NativeInterop.cs index 92bdc9116..b9ba21dc9 100644 --- a/src/PactNet/Interop/NativeInterop.cs +++ b/src/PactNet/Interop/NativeInterop.cs @@ -42,6 +42,9 @@ internal static class NativeInterop [DllImport(DllName, EntryPoint = "pactffi_new_interaction")] public static extern InteractionHandle NewInteraction(PactHandle pact, string description); + [DllImport(DllName, EntryPoint = "pactffi_new_sync_message_interaction")] + public static extern InteractionHandle NewSyncMessageInteraction(PactHandle pact, string description); + [DllImport(DllName, EntryPoint = "pactffi_given")] public static extern bool Given(InteractionHandle interaction, string description); @@ -168,5 +171,18 @@ public static extern void VerifierBrokerSourceWithSelectors(IntPtr handle, public static extern IntPtr VerifierOutput(IntPtr handle, byte stripAnsi); #endregion + + #region Plugins + + [DllImport(DllName, EntryPoint = "pactffi_using_plugin")] + public static extern uint UsingPlugin(PactHandle pact, string name, string version); + + [DllImport(DllName, EntryPoint = "pactffi_interaction_contents")] + public static extern uint InteractionContents(InteractionHandle interaction, InteractionPart part, string contentType, string body); + + [DllImport(DllName, EntryPoint = "pactffi_cleanup_plugins")] + public static extern void CleanupPlugins(PactHandle pact); + + #endregion } } diff --git a/src/PactNet/MessageBuilder.cs b/src/PactNet/MessageBuilder.cs index 83c7cffe4..571a98472 100644 --- a/src/PactNet/MessageBuilder.cs +++ b/src/PactNet/MessageBuilder.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Text.Json; -using PactNet.Drivers; +using PactNet.Drivers.Message; using PactNet.Interop; namespace PactNet diff --git a/src/PactNet/MessagePactBuilder.cs b/src/PactNet/MessagePactBuilder.cs index 0cd17567d..c70e23497 100644 --- a/src/PactNet/MessagePactBuilder.cs +++ b/src/PactNet/MessagePactBuilder.cs @@ -1,5 +1,5 @@ using System; -using PactNet.Drivers; +using PactNet.Drivers.Message; using PactNet.Interop; namespace PactNet diff --git a/src/PactNet/PactBuilder.cs b/src/PactNet/PactBuilder.cs index fe311c885..0f18d3bf0 100644 --- a/src/PactNet/PactBuilder.cs +++ b/src/PactNet/PactBuilder.cs @@ -1,6 +1,7 @@ using System; using System.Threading.Tasks; using PactNet.Drivers; +using PactNet.Drivers.Http; using PactNet.Exceptions; using PactNet.Internal; using PactNet.Models; diff --git a/src/PactNet/PactExtensions.cs b/src/PactNet/PactExtensions.cs index 32aa358fb..7999b227d 100644 --- a/src/PactNet/PactExtensions.cs +++ b/src/PactNet/PactExtensions.cs @@ -1,5 +1,7 @@ using System; using PactNet.Drivers; +using PactNet.Drivers.Http; +using PactNet.Drivers.Message; using PactNet.Interop; using PactNet.Models; diff --git a/src/PactNet/RequestBuilder.cs b/src/PactNet/RequestBuilder.cs index d245cfbfc..20204fbc1 100644 --- a/src/PactNet/RequestBuilder.cs +++ b/src/PactNet/RequestBuilder.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Net.Http; using System.Text.Json; -using PactNet.Drivers; +using PactNet.Drivers.Http; using PactNet.Matchers; namespace PactNet diff --git a/src/PactNet/ResponseBuilder.cs b/src/PactNet/ResponseBuilder.cs index badb0e96d..21abfd229 100644 --- a/src/PactNet/ResponseBuilder.cs +++ b/src/PactNet/ResponseBuilder.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Net; using System.Text.Json; -using PactNet.Drivers; +using PactNet.Drivers.Http; using PactNet.Matchers; namespace PactNet diff --git a/tests/PactNet.Tests/ConfiguredMessageVerifierTests.cs b/tests/PactNet.Tests/ConfiguredMessageVerifierTests.cs index 6b9bb0a7b..577b2a27e 100644 --- a/tests/PactNet.Tests/ConfiguredMessageVerifierTests.cs +++ b/tests/PactNet.Tests/ConfiguredMessageVerifierTests.cs @@ -4,7 +4,7 @@ using System.Threading.Tasks; using FluentAssertions; using Moq; -using PactNet.Drivers; +using PactNet.Drivers.Message; using PactNet.Exceptions; using PactNet.Interop; using PactNet.Models; diff --git a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs index 81ab072e2..3edef2199 100644 --- a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs +++ b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs @@ -6,6 +6,8 @@ using System.Threading.Tasks; using FluentAssertions; using PactNet.Drivers; +using PactNet.Drivers.Http; +using PactNet.Drivers.Message; using PactNet.Interop; using Xunit; using Xunit.Abstractions; diff --git a/tests/PactNet.Tests/MessageBuilderTests.cs b/tests/PactNet.Tests/MessageBuilderTests.cs index 4fa72c5c5..34a7e922f 100644 --- a/tests/PactNet.Tests/MessageBuilderTests.cs +++ b/tests/PactNet.Tests/MessageBuilderTests.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Text.Json; using Moq; -using PactNet.Drivers; +using PactNet.Drivers.Message; using PactNet.Interop; using Xunit; using Match = PactNet.Matchers.Match; diff --git a/tests/PactNet.Tests/MessagePactBuilderTests.cs b/tests/PactNet.Tests/MessagePactBuilderTests.cs index cff2f18cc..daee234da 100644 --- a/tests/PactNet.Tests/MessagePactBuilderTests.cs +++ b/tests/PactNet.Tests/MessagePactBuilderTests.cs @@ -1,7 +1,7 @@ using System; using FluentAssertions; using Moq; -using PactNet.Drivers; +using PactNet.Drivers.Message; using PactNet.Interop; using Xunit; diff --git a/tests/PactNet.Tests/PactBuilderTests.cs b/tests/PactNet.Tests/PactBuilderTests.cs index fd6453043..ce86c34de 100644 --- a/tests/PactNet.Tests/PactBuilderTests.cs +++ b/tests/PactNet.Tests/PactBuilderTests.cs @@ -3,6 +3,7 @@ using FluentAssertions; using Moq; using PactNet.Drivers; +using PactNet.Drivers.Http; using PactNet.Exceptions; using PactNet.Infrastructure.Outputters; using Xunit; diff --git a/tests/PactNet.Tests/RequestBuilderTests.cs b/tests/PactNet.Tests/RequestBuilderTests.cs index d4be96244..a55a204bb 100644 --- a/tests/PactNet.Tests/RequestBuilderTests.cs +++ b/tests/PactNet.Tests/RequestBuilderTests.cs @@ -4,7 +4,7 @@ using System.Text.Json; using FluentAssertions; using Moq; -using PactNet.Drivers; +using PactNet.Drivers.Http; using Xunit; using Match = PactNet.Matchers.Match; diff --git a/tests/PactNet.Tests/ResponseBuilderTests.cs b/tests/PactNet.Tests/ResponseBuilderTests.cs index d92cee718..cd71e771b 100644 --- a/tests/PactNet.Tests/ResponseBuilderTests.cs +++ b/tests/PactNet.Tests/ResponseBuilderTests.cs @@ -1,7 +1,7 @@ using System.Net; using System.Text.Json; using Moq; -using PactNet.Drivers; +using PactNet.Drivers.Http; using Xunit; using Match = PactNet.Matchers.Match; From e250aa85bb7d04fa0a9f4a78903c2791754f7e62 Mon Sep 17 00:00:00 2001 From: Max Lancaster Date: Tue, 7 Oct 2025 18:11:03 -0400 Subject: [PATCH 02/35] refactor: Remove unnecessary PactHandle constructor parameters --- src/PactNet/Drivers/Http/HttpInteractionDriver.cs | 5 +---- src/PactNet/Drivers/Http/HttpPactDriver.cs | 2 +- src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs | 5 +---- src/PactNet/Drivers/Plugins/PluginPactDriver.cs | 2 +- 4 files changed, 4 insertions(+), 10 deletions(-) diff --git a/src/PactNet/Drivers/Http/HttpInteractionDriver.cs b/src/PactNet/Drivers/Http/HttpInteractionDriver.cs index fd6520a90..6072ca6d3 100644 --- a/src/PactNet/Drivers/Http/HttpInteractionDriver.cs +++ b/src/PactNet/Drivers/Http/HttpInteractionDriver.cs @@ -8,17 +8,14 @@ namespace PactNet.Drivers.Http /// internal class HttpInteractionDriver : IHttpInteractionDriver { - private readonly PactHandle pact; private readonly InteractionHandle interaction; /// /// Initialises a new instance of the class. /// - /// Pact handle /// Interaction handle - internal HttpInteractionDriver(PactHandle pact, InteractionHandle interaction) + internal HttpInteractionDriver(InteractionHandle interaction) { - this.pact = pact; this.interaction = interaction; } diff --git a/src/PactNet/Drivers/Http/HttpPactDriver.cs b/src/PactNet/Drivers/Http/HttpPactDriver.cs index 19572cac0..0bbd456ad 100644 --- a/src/PactNet/Drivers/Http/HttpPactDriver.cs +++ b/src/PactNet/Drivers/Http/HttpPactDriver.cs @@ -27,7 +27,7 @@ internal HttpPactDriver(PactHandle pact) : base(pact) public IHttpInteractionDriver NewHttpInteraction(string description) { InteractionHandle interaction = NativeInterop.NewInteraction(this.pact, description); - return new HttpInteractionDriver(this.pact, interaction); + return new HttpInteractionDriver(interaction); } /// diff --git a/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs b/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs index e4969c479..15f4b70c3 100644 --- a/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs +++ b/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs @@ -8,17 +8,14 @@ namespace PactNet.Drivers.Plugins /// internal class PluginInteractionDriver : IPluginInteractionDriver { - private readonly PactHandle pact; private readonly InteractionHandle interaction; /// /// Initialises a new instance of the class. /// - /// Pact handle /// Interaction handle - public PluginInteractionDriver(PactHandle pact, InteractionHandle interaction) + public PluginInteractionDriver(InteractionHandle interaction) { - this.pact = pact; this.interaction = interaction; } diff --git a/src/PactNet/Drivers/Plugins/PluginPactDriver.cs b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs index bfa4cd9cb..2dad77b8b 100644 --- a/src/PactNet/Drivers/Plugins/PluginPactDriver.cs +++ b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs @@ -27,7 +27,7 @@ internal PluginPactDriver(PactHandle pact) : base(pact) public IPluginInteractionDriver NewSyncInteraction(string description) { InteractionHandle interaction = NativeInterop.NewSyncMessageInteraction(this.pact, description); - return new PluginInteractionDriver(this.pact, interaction); + return new PluginInteractionDriver(interaction); } /// From bc6b21fe0b03242961490d3c056723b51170953b Mon Sep 17 00:00:00 2001 From: Max Lancaster Date: Tue, 7 Oct 2025 09:51:13 -0400 Subject: [PATCH 03/35] refactor: Introduce AbstractPactBuilder for shared verify functionality --- src/PactNet/AbstractPactBuilder.cs | 133 ++++++++++++++++++ src/PactNet/Drivers/AbstractPactDriver.cs | 31 +++- src/PactNet/Drivers/Http/HttpPactDriver.cs | 31 ---- src/PactNet/Drivers/Http/IHttpPactDriver.cs | 10 -- src/PactNet/Drivers/ICompletedPactDriver.cs | 11 ++ .../Drivers/Message/MessagePactDriver.cs | 3 - .../Drivers/Plugins/IPluginPactDriver.cs | 15 +- .../Drivers/Plugins/PluginPactDriver.cs | 35 +---- src/PactNet/PactBuilder.cs | 120 +--------------- .../Drivers/FfiIntegrationTests.cs | 2 +- tests/PactNet.Tests/PactBuilderTests.cs | 8 +- 11 files changed, 184 insertions(+), 215 deletions(-) create mode 100644 src/PactNet/AbstractPactBuilder.cs diff --git a/src/PactNet/AbstractPactBuilder.cs b/src/PactNet/AbstractPactBuilder.cs new file mode 100644 index 000000000..563aa1c89 --- /dev/null +++ b/src/PactNet/AbstractPactBuilder.cs @@ -0,0 +1,133 @@ +using System; +using System.Threading.Tasks; +using PactNet.Drivers; +using PactNet.Exceptions; +using PactNet.Internal; +using PactNet.Models; + +namespace PactNet; + +internal abstract class AbstractPactBuilder : IPactBuilder +{ + private readonly ICompletedPactDriver pact; + protected readonly PactConfig config; + protected readonly int? port; + protected readonly IPAddress host; + private readonly string transport; + + /// + /// Initialises a new instance of the class. + /// + /// Pact driver + /// Pact config + /// Optional port, otherwise one is dynamically allocated + /// Optional host, otherwise loopback is used + /// The transport to use (i.e. http, https, grpc). Must be a valid UTF-8 NULL-terminated string, or NULL or empty, in which case http will be used. + protected AbstractPactBuilder(ICompletedPactDriver pact, PactConfig config, int? port, IPAddress host, + string transport = null) + { + this.pact = pact; + this.config = config; + this.port = port; + this.host = host; + this.transport = transport; + } + + /// + /// Verify the configured interactions + /// + /// Action to perform the real interactions against the mock driver + /// Failed to verify the interactions + public void Verify(Action interact) + { + Guard.NotNull(interact, nameof(interact)); + + using IMockServerDriver mockServer = this.StartMockServer(); + + try + { + interact(new ConsumerContext { MockServerUri = mockServer.Uri }); + + this.VerifyInternal(mockServer); + } + finally + { + this.PrintLogs(mockServer); + } + } + + /// + /// Verify the configured interactions + /// + /// Action to perform the real interactions against the mock driver + /// Failed to verify the interactions + public async Task VerifyAsync(Func interact) + { + Guard.NotNull(interact, nameof(interact)); + + using IMockServerDriver mockServer = this.StartMockServer(); + + try + { + await interact(new ConsumerContext { MockServerUri = mockServer.Uri }); + + this.VerifyInternal(mockServer); + } + finally + { + this.PrintLogs(mockServer); + } + } + + /// + /// Start the mock driver + /// + /// Mock driver + private IMockServerDriver StartMockServer() + { + string hostIp = this.host switch + { + IPAddress.Loopback => "127.0.0.1", + IPAddress.Any => "0.0.0.0", + _ => throw new ArgumentOutOfRangeException(nameof(this.host), this.host, "Unsupported IPAddress value") + }; + + // TODO: add TLS support + return this.pact.CreateMockServer(hostIp, this.port, false, transport); + } + + /// + /// Verify the interactions after the consumer client has been invoked + /// + /// Mock server + private void VerifyInternal(IMockServerDriver mockServer) + { + string errors = mockServer.MockServerMismatches(); + + if (string.IsNullOrWhiteSpace(errors) || errors == "[]") + { + this.pact.WritePactFile(this.config.PactDir); + return; + } + + this.config.WriteLine(string.Empty); + this.config.WriteLine("Verification mismatches:"); + this.config.WriteLine(string.Empty); + this.config.WriteLine(errors); + + throw new PactFailureException("Pact verification failed. See output for details"); + } + + /// + /// Print logs to the configured outputs + /// + /// Mock server + private void PrintLogs(IMockServerDriver mockServer) + { + string logs = mockServer.MockServerLogs(); + + this.config.WriteLine("Mock driver logs:"); + this.config.WriteLine(string.Empty); + this.config.WriteLine(logs); + } +} diff --git a/src/PactNet/Drivers/AbstractPactDriver.cs b/src/PactNet/Drivers/AbstractPactDriver.cs index 8e70fc3c2..2ea1c1397 100644 --- a/src/PactNet/Drivers/AbstractPactDriver.cs +++ b/src/PactNet/Drivers/AbstractPactDriver.cs @@ -8,7 +8,7 @@ namespace PactNet.Drivers /// internal abstract class AbstractPactDriver : ICompletedPactDriver { - private readonly PactHandle pact; + protected readonly PactHandle pact; /// /// Initialises a new instance of the class. @@ -40,5 +40,34 @@ public void WritePactFile(string directory) }; } } + + /// + /// Create the mock server for the current pact + /// + /// Host for the mock server + /// Port for the mock server, or null to allocate one automatically + /// Enable TLS + /// The transport to use (i.e. http, https, grpc). Must be a valid UTF-8 NULL-terminated string, or NULL or empty, in which case http will be used. + /// Mock server port + /// Failed to start mock server + public IMockServerDriver CreateMockServer(string host, int? port, bool tls, string transport = null) + { + int result = NativeInterop.CreateMockServerForTransport(this.pact, host, (ushort)port.GetValueOrDefault(0), transport, null); + + if (result > 0) + { + return new MockServerDriver(host, result, tls); + } + + throw result switch + { + -1 => new InvalidOperationException("Invalid handle when starting mock server"), + -3 => new InvalidOperationException("Unable to start mock server"), + -4 => new InvalidOperationException("The pact reference library panicked"), + -5 => new InvalidOperationException("The IPAddress is invalid"), + -6 => new InvalidOperationException("Could not create the TLS configuration with the self-signed certificate"), + _ => new InvalidOperationException($"Unknown mock server error: {result}") + }; + } } } diff --git a/src/PactNet/Drivers/Http/HttpPactDriver.cs b/src/PactNet/Drivers/Http/HttpPactDriver.cs index 0bbd456ad..7c8395ff9 100644 --- a/src/PactNet/Drivers/Http/HttpPactDriver.cs +++ b/src/PactNet/Drivers/Http/HttpPactDriver.cs @@ -8,15 +8,12 @@ namespace PactNet.Drivers.Http /// internal class HttpPactDriver : AbstractPactDriver, IHttpPactDriver { - private readonly PactHandle pact; - /// /// Initialises a new instance of the class. /// /// Pact handle internal HttpPactDriver(PactHandle pact) : base(pact) { - this.pact = pact; } /// @@ -29,33 +26,5 @@ public IHttpInteractionDriver NewHttpInteraction(string description) InteractionHandle interaction = NativeInterop.NewInteraction(this.pact, description); return new HttpInteractionDriver(interaction); } - - /// - /// Create the mock server for the current pact - /// - /// Host for the mock server - /// Port for the mock server, or null to allocate one automatically - /// Enable TLS - /// Mock server port - /// Failed to start mock server - public IMockServerDriver CreateMockServer(string host, int? port, bool tls) - { - int result = NativeInterop.CreateMockServerForTransport(this.pact, host, (ushort)port.GetValueOrDefault(0), "http", null); - - if (result > 0) - { - return new MockServerDriver(host, result, tls); - } - - throw result switch - { - -1 => new InvalidOperationException("Invalid handle when starting mock server"), - -3 => new InvalidOperationException("Unable to start mock server"), - -4 => new InvalidOperationException("The pact reference library panicked"), - -5 => new InvalidOperationException("The IPAddress is invalid"), - -6 => new InvalidOperationException("Could not create the TLS configuration with the self-signed certificate"), - _ => new InvalidOperationException($"Unknown mock server error: {result}") - }; - } } } diff --git a/src/PactNet/Drivers/Http/IHttpPactDriver.cs b/src/PactNet/Drivers/Http/IHttpPactDriver.cs index 38895d25e..0194f34b2 100644 --- a/src/PactNet/Drivers/Http/IHttpPactDriver.cs +++ b/src/PactNet/Drivers/Http/IHttpPactDriver.cs @@ -13,15 +13,5 @@ internal interface IHttpPactDriver : ICompletedPactDriver /// Interaction description /// HTTP interaction handle IHttpInteractionDriver NewHttpInteraction(string description); - - /// - /// Create the mock server for the current pact - /// - /// Host for the mock server - /// Port for the mock server, or null to allocate one automatically - /// Enable TLS - /// Mock server port - /// Failed to start mock server - IMockServerDriver CreateMockServer(string host, int? port, bool tls); } } diff --git a/src/PactNet/Drivers/ICompletedPactDriver.cs b/src/PactNet/Drivers/ICompletedPactDriver.cs index 199b075d9..7ef05bf1c 100644 --- a/src/PactNet/Drivers/ICompletedPactDriver.cs +++ b/src/PactNet/Drivers/ICompletedPactDriver.cs @@ -14,5 +14,16 @@ internal interface ICompletedPactDriver /// Status code /// Failed to write pact file void WritePactFile(string directory); + + /// + /// Create the mock server for the current pact + /// + /// Host for the mock server + /// Port for the mock server, or null to allocate one automatically + /// Enable TLS + /// The transport to use (i.e. http, https, grpc). Must be a valid UTF-8 NULL-terminated string, or NULL or empty, in which case http will be used. + /// Mock server port + /// Failed to start mock server + IMockServerDriver CreateMockServer(string host, int? port, bool tls, string transport = null); } } diff --git a/src/PactNet/Drivers/Message/MessagePactDriver.cs b/src/PactNet/Drivers/Message/MessagePactDriver.cs index 91a43a62c..bca25125e 100644 --- a/src/PactNet/Drivers/Message/MessagePactDriver.cs +++ b/src/PactNet/Drivers/Message/MessagePactDriver.cs @@ -7,15 +7,12 @@ namespace PactNet.Drivers.Message /// internal class MessagePactDriver : AbstractPactDriver, IMessagePactDriver { - private readonly PactHandle pact; - /// /// Initialises a new instance of the class. /// /// Pact handle internal MessagePactDriver(PactHandle pact) : base(pact) { - this.pact = pact; } /// diff --git a/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs b/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs index 1e635f5a9..79a09eac9 100644 --- a/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs +++ b/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs @@ -1,6 +1,4 @@ -using System; - -namespace PactNet.Drivers.Plugins +namespace PactNet.Drivers.Plugins { /// /// Driver for plugin-based pacts @@ -13,16 +11,5 @@ internal interface IPluginPactDriver : ICompletedPactDriver /// Interaction description /// Interaction driver IPluginInteractionDriver NewSyncInteraction(string description); - - /// - /// Create the mock server for the current pact - /// - /// Host for the mock server - /// Port for the mock server, or null to allocate one automatically - /// Transport - e.g. http, https, grpc - /// Transport config string - /// Mock server port - /// Failed to start mock server - IMockServerDriver CreateMockServer(string host, int? port, string transport, string transportConfig); } } diff --git a/src/PactNet/Drivers/Plugins/PluginPactDriver.cs b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs index 2dad77b8b..63acf58db 100644 --- a/src/PactNet/Drivers/Plugins/PluginPactDriver.cs +++ b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs @@ -1,5 +1,4 @@ -using System; -using PactNet.Interop; +using PactNet.Interop; namespace PactNet.Drivers.Plugins { @@ -8,15 +7,12 @@ namespace PactNet.Drivers.Plugins /// internal class PluginPactDriver : AbstractPactDriver, IPluginPactDriver { - private readonly PactHandle pact; - /// /// Initialize a new instance of the class. /// /// Pact handle internal PluginPactDriver(PactHandle pact) : base(pact) { - this.pact = pact; } /// @@ -29,34 +25,5 @@ public IPluginInteractionDriver NewSyncInteraction(string description) InteractionHandle interaction = NativeInterop.NewSyncMessageInteraction(this.pact, description); return new PluginInteractionDriver(interaction); } - - /// - /// Create the mock server for the current pact - /// - /// Host for the mock server - /// Port for the mock server, or null to allocate one automatically - /// Transport - e.g. http, https, grpc - /// Transport config string - /// Mock server port - /// Failed to start mock server - public IMockServerDriver CreateMockServer(string host, int? port, string transport, string transportConfig) - { - int result = NativeInterop.CreateMockServerForTransport(this.pact, host, (ushort)port.GetValueOrDefault(0), transport, transportConfig); - - if (result > 0) - { - return new MockServerDriver(host, result, false); - } - - throw result switch - { - -1 => new InvalidOperationException("Invalid handle when starting mock server"), - -2 => new InvalidOperationException("The transport config is not valid JSON"), - -3 => new InvalidOperationException("Unable to start mock server"), - -4 => new InvalidOperationException("The pact reference library panicked"), - -5 => new InvalidOperationException("The IPAddress is invalid"), - _ => new InvalidOperationException($"Unknown mock server error: {result}") - }; - } } } diff --git a/src/PactNet/PactBuilder.cs b/src/PactNet/PactBuilder.cs index 0f18d3bf0..3e1ac07fc 100644 --- a/src/PactNet/PactBuilder.cs +++ b/src/PactNet/PactBuilder.cs @@ -1,9 +1,4 @@ -using System; -using System.Threading.Tasks; -using PactNet.Drivers; using PactNet.Drivers.Http; -using PactNet.Exceptions; -using PactNet.Internal; using PactNet.Models; namespace PactNet @@ -11,12 +6,9 @@ namespace PactNet /// /// Pact builder for the native backend /// - internal class PactBuilder : IPactBuilderV2, IPactBuilderV3, IPactBuilderV4 + internal class PactBuilder : AbstractPactBuilder, IPactBuilderV2, IPactBuilderV3, IPactBuilderV4 { private readonly IHttpPactDriver pact; - private readonly PactConfig config; - private readonly int? port; - private readonly IPAddress host; /// /// Initialises a new instance of the class. @@ -25,12 +17,10 @@ internal class PactBuilder : IPactBuilderV2, IPactBuilderV3, IPactBuilderV4 /// Pact config /// Optional port, otherwise one is dynamically allocated /// Optional host, otherwise loopback is used - internal PactBuilder(IHttpPactDriver pact, PactConfig config, int? port = null, IPAddress host = IPAddress.Loopback) + internal PactBuilder(IHttpPactDriver pact, PactConfig config, int? port = null, + IPAddress host = IPAddress.Loopback) : base(pact, config, port, host, "http") { this.pact = pact; - this.config = config; - this.port = port; - this.host = host; } /// @@ -69,109 +59,5 @@ internal RequestBuilder UponReceiving(string description) var requestBuilder = new RequestBuilder(interactions, this.config.DefaultJsonSettings); return requestBuilder; } - - /// - /// Verify the configured interactions - /// - /// Action to perform the real interactions against the mock driver - /// Failed to verify the interactions - public void Verify(Action interact) - { - Guard.NotNull(interact, nameof(interact)); - - using IMockServerDriver mockServer = this.StartMockServer(); - - try - { - interact(new ConsumerContext - { - MockServerUri = mockServer.Uri - }); - - this.VerifyInternal(mockServer); - } - finally - { - this.PrintLogs(mockServer); - } - } - - /// - /// Verify the configured interactions - /// - /// Action to perform the real interactions against the mock driver - /// Failed to verify the interactions - public async Task VerifyAsync(Func interact) - { - Guard.NotNull(interact, nameof(interact)); - - using IMockServerDriver mockServer = this.StartMockServer(); - - try - { - await interact(new ConsumerContext - { - MockServerUri = mockServer.Uri - }); - - this.VerifyInternal(mockServer); - } - finally - { - this.PrintLogs(mockServer); - } - } - - /// - /// Start the mock driver - /// - /// Mock driver - private IMockServerDriver StartMockServer() - { - string hostIp = this.host switch - { - IPAddress.Loopback => "127.0.0.1", - IPAddress.Any => "0.0.0.0", - _ => throw new ArgumentOutOfRangeException(nameof(this.host), this.host, "Unsupported IPAddress value") - }; - - // TODO: add TLS support - return this.pact.CreateMockServer(hostIp, this.port, false); - } - - /// - /// Verify the interactions after the consumer client has been invoked - /// - /// Mock server - private void VerifyInternal(IMockServerDriver mockServer) - { - string errors = mockServer.MockServerMismatches(); - - if (string.IsNullOrWhiteSpace(errors) || errors == "[]") - { - this.pact.WritePactFile(this.config.PactDir); - return; - } - - this.config.WriteLine(string.Empty); - this.config.WriteLine("Verification mismatches:"); - this.config.WriteLine(string.Empty); - this.config.WriteLine(errors); - - throw new PactFailureException("Pact verification failed. See output for details"); - } - - /// - /// Print logs to the configured outputs - /// - /// Mock server - private void PrintLogs(IMockServerDriver mockServer) - { - string logs = mockServer.MockServerLogs(); - - this.config.WriteLine("Mock driver logs:"); - this.config.WriteLine(string.Empty); - this.config.WriteLine(logs); - } } } diff --git a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs index 3edef2199..a853d4c83 100644 --- a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs +++ b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs @@ -54,7 +54,7 @@ public async Task HttpInteraction_v3_CreatesPactFile() interaction.WithResponseHeader("X-Response-Header", "value2", 1); interaction.WithResponseBody("application/json", @"{""foo"":42}"); - using IMockServerDriver mockServer = pact.CreateMockServer("127.0.0.1", null, false); + using IMockServerDriver mockServer = pact.CreateMockServer("127.0.0.1", null, false, "http"); var client = new HttpClient { BaseAddress = mockServer.Uri }; client.DefaultRequestHeaders.Add("X-Request-Header", new[] { "request1", "request2" }); diff --git a/tests/PactNet.Tests/PactBuilderTests.cs b/tests/PactNet.Tests/PactBuilderTests.cs index ce86c34de..b193cbbf3 100644 --- a/tests/PactNet.Tests/PactBuilderTests.cs +++ b/tests/PactNet.Tests/PactBuilderTests.cs @@ -33,7 +33,7 @@ public PactBuilderTests() this.fixture = new Fixture(); var customization = new SupportMutableValueTypesCustomization(); customization.Customize(this.fixture); - + this.serverUri = this.fixture.Create(); this.config = new PactConfig { @@ -41,7 +41,7 @@ public PactBuilderTests() }; // set some default mock setups - this.mockDriver.Setup(s => s.CreateMockServer("127.0.0.1", null, false)).Returns(this.mockServer.Object); + this.mockDriver.Setup(s => s.CreateMockServer("127.0.0.1", null, false, "http")).Returns(this.mockServer.Object); this.mockDriver.Setup(s => s.NewHttpInteraction(It.IsAny())).Returns(this.mockInteractions.Object); this.mockDriver.Setup(s => s.WritePactFile(this.config.PactDir)); @@ -68,14 +68,14 @@ public void Verify_WhenCalled_StartsMockServer() { this.builder.Verify(Success); - this.mockDriver.Verify(d => d.CreateMockServer("127.0.0.1", null, false)); + this.mockDriver.Verify(d => d.CreateMockServer("127.0.0.1", null, false, "http")); } [Fact] public void Verify_ErrorStartingMockServer_ThrowsInvalidOperationException() { this.mockDriver - .Setup(s => s.CreateMockServer(It.IsAny(), It.IsAny(), It.IsAny())) + .Setup(s => s.CreateMockServer(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Throws(); Action action = () => this.builder.Verify(Success); From b191d6b75acdd5b0bfb7101ed27385274843b21f Mon Sep 17 00:00:00 2001 From: Max Lancaster Date: Tue, 7 Oct 2025 17:29:55 -0400 Subject: [PATCH 04/35] refactor: Use mock server port to write pact file --- .../pacts/Fulfilment API-Orders API.json | 4 ++++ src/PactNet/AbstractPactBuilder.cs | 2 +- src/PactNet/Drivers/AbstractPactDriver.cs | 15 +++++++++++++++ src/PactNet/Drivers/ICompletedPactDriver.cs | 7 +++++++ src/PactNet/Drivers/IMockServerDriver.cs | 5 +++++ src/PactNet/Drivers/MockServerDriver.cs | 15 ++++++++++----- src/PactNet/Interop/NativeInterop.cs | 3 +++ tests/PactNet.Tests/PactBuilderTests.cs | 8 +++++--- .../data/v2-consumer-integration.json | 1 + .../data/v3-consumer-integration.json | 1 + .../data/v4-combined-integration.json | 1 + .../data/v4-consumer-integration.json | 2 ++ 12 files changed, 55 insertions(+), 9 deletions(-) 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 b6f1a702c..2a79a1b1e 100644 --- a/samples/OrdersApi/Consumer.Tests/pacts/Fulfilment API-Orders API.json +++ b/samples/OrdersApi/Consumer.Tests/pacts/Fulfilment API-Orders API.json @@ -69,6 +69,7 @@ }, "status": 200 }, + "transport": "http", "type": "Synchronous/HTTP" }, { @@ -86,6 +87,7 @@ "response": { "status": 404 }, + "transport": "http", "type": "Synchronous/HTTP" }, { @@ -129,6 +131,7 @@ "response": { "status": 204 }, + "transport": "http", "type": "Synchronous/HTTP" }, { @@ -159,6 +162,7 @@ "metadata": { "pactRust": { "ffi": "0.4.27", + "mockserver": "1.2.11", "models": "1.2.8" }, "pactSpecification": { diff --git a/src/PactNet/AbstractPactBuilder.cs b/src/PactNet/AbstractPactBuilder.cs index 563aa1c89..95a666440 100644 --- a/src/PactNet/AbstractPactBuilder.cs +++ b/src/PactNet/AbstractPactBuilder.cs @@ -106,7 +106,7 @@ private void VerifyInternal(IMockServerDriver mockServer) if (string.IsNullOrWhiteSpace(errors) || errors == "[]") { - this.pact.WritePactFile(this.config.PactDir); + this.pact.WritePactFile(mockServer.Port, this.config.PactDir); return; } diff --git a/src/PactNet/Drivers/AbstractPactDriver.cs b/src/PactNet/Drivers/AbstractPactDriver.cs index 2ea1c1397..060d81778 100644 --- a/src/PactNet/Drivers/AbstractPactDriver.cs +++ b/src/PactNet/Drivers/AbstractPactDriver.cs @@ -28,7 +28,22 @@ protected AbstractPactDriver(PactHandle pact) public void WritePactFile(string directory) { var result = NativeInterop.WritePactFile(this.pact, directory, false); + ThrowExceptionOnWritePactFileFailure(result); + } + /// + /// Write the pact file to disk + /// + /// Port of the mock server + /// Directory of the pact file + public void WritePactFile(int port, string directory) + { + var result = NativeInterop.WritePactFileForPort(port, directory, false); + ThrowExceptionOnWritePactFileFailure(result); + } + + private static void ThrowExceptionOnWritePactFileFailure(int result) + { if (result != 0) { throw result switch diff --git a/src/PactNet/Drivers/ICompletedPactDriver.cs b/src/PactNet/Drivers/ICompletedPactDriver.cs index 7ef05bf1c..eb102950a 100644 --- a/src/PactNet/Drivers/ICompletedPactDriver.cs +++ b/src/PactNet/Drivers/ICompletedPactDriver.cs @@ -15,6 +15,13 @@ internal interface ICompletedPactDriver /// Failed to write pact file void WritePactFile(string directory); + /// + /// Write the pact file to disk + /// + /// Port of the mock server + /// Directory of the pact file + void WritePactFile(int port, string directory); + /// /// Create the mock server for the current pact /// diff --git a/src/PactNet/Drivers/IMockServerDriver.cs b/src/PactNet/Drivers/IMockServerDriver.cs index 8060613ea..3d93742e5 100644 --- a/src/PactNet/Drivers/IMockServerDriver.cs +++ b/src/PactNet/Drivers/IMockServerDriver.cs @@ -7,6 +7,11 @@ namespace PactNet.Drivers /// internal interface IMockServerDriver : IDisposable { + /// + /// Mock server port + /// + int Port { get; } + /// /// Mock server URI /// diff --git a/src/PactNet/Drivers/MockServerDriver.cs b/src/PactNet/Drivers/MockServerDriver.cs index bc92485f9..984fd6d07 100644 --- a/src/PactNet/Drivers/MockServerDriver.cs +++ b/src/PactNet/Drivers/MockServerDriver.cs @@ -9,7 +9,12 @@ namespace PactNet.Drivers /// internal class MockServerDriver : IMockServerDriver { - private readonly int port; + + /// + /// Mock server port + /// + public int Port { get; } + /// /// Mock server URI @@ -26,7 +31,7 @@ internal MockServerDriver(string host, int port, bool tls) { string scheme = tls ? "https" : "http"; this.Uri = new Uri($"{scheme}://{host}:{port}"); - this.port = port; + this.Port = port; } /// @@ -35,7 +40,7 @@ internal MockServerDriver(string host, int port, bool tls) /// Mismatch string public string MockServerMismatches() { - IntPtr matchesPtr = NativeInterop.MockServerMismatches(this.port); + IntPtr matchesPtr = NativeInterop.MockServerMismatches(this.Port); return matchesPtr == IntPtr.Zero ? string.Empty @@ -48,7 +53,7 @@ public string MockServerMismatches() /// Log string public string MockServerLogs() { - IntPtr logsPtr = NativeInterop.MockServerLogs(this.port); + IntPtr logsPtr = NativeInterop.MockServerLogs(this.Port); return logsPtr == IntPtr.Zero ? "ERROR: Unable to retrieve mock server logs" @@ -76,7 +81,7 @@ public void Dispose() /// private void ReleaseUnmanagedResources() { - NativeInterop.CleanupMockServer(this.port); + NativeInterop.CleanupMockServer(this.Port); } } } diff --git a/src/PactNet/Interop/NativeInterop.cs b/src/PactNet/Interop/NativeInterop.cs index b9ba21dc9..65ecd790c 100644 --- a/src/PactNet/Interop/NativeInterop.cs +++ b/src/PactNet/Interop/NativeInterop.cs @@ -30,6 +30,9 @@ internal static class NativeInterop [DllImport(DllName, EntryPoint = "pactffi_pact_handle_write_file")] public static extern int WritePactFile(PactHandle pact, string directory, bool overwrite); + [DllImport(DllName, EntryPoint = "pactffi_write_pact_file")] + public static extern int WritePactFileForPort(int port, string directory, bool overwrite); + [DllImport(DllName, EntryPoint = "pactffi_fetch_log_buffer")] public static extern string FetchLogBuffer(string logId); diff --git a/tests/PactNet.Tests/PactBuilderTests.cs b/tests/PactNet.Tests/PactBuilderTests.cs index b193cbbf3..a152bf72a 100644 --- a/tests/PactNet.Tests/PactBuilderTests.cs +++ b/tests/PactNet.Tests/PactBuilderTests.cs @@ -12,6 +12,7 @@ namespace PactNet.Tests { public class PactBuilderTests { + private const int MockServerPort = 5000; private readonly PactBuilder builder; private readonly Mock mockDriver; @@ -28,6 +29,7 @@ public PactBuilderTests() this.mockDriver = new Mock(MockBehavior.Strict); this.mockInteractions = new Mock(MockBehavior.Strict); this.mockServer = new Mock(MockBehavior.Strict); + this.mockServer.Setup(s => s.Port).Returns(MockServerPort); this.mockOutput = new Mock(); this.fixture = new Fixture(); @@ -43,7 +45,7 @@ public PactBuilderTests() // set some default mock setups this.mockDriver.Setup(s => s.CreateMockServer("127.0.0.1", null, false, "http")).Returns(this.mockServer.Object); this.mockDriver.Setup(s => s.NewHttpInteraction(It.IsAny())).Returns(this.mockInteractions.Object); - this.mockDriver.Setup(s => s.WritePactFile(this.config.PactDir)); + this.mockDriver.Setup(s => s.WritePactFile(MockServerPort, this.config.PactDir)); this.mockServer.Setup(s => s.Uri).Returns(this.serverUri); this.mockServer.Setup(s => s.MockServerLogs()).Returns(string.Empty); @@ -107,7 +109,7 @@ public void Verify_NoMismatches_WritesPactFile() { this.builder.Verify(Success); - this.mockDriver.Verify(s => s.WritePactFile(this.config.PactDir)); + this.mockDriver.Verify(s => s.WritePactFile(MockServerPort, this.config.PactDir)); } [Fact] @@ -122,7 +124,7 @@ public void Verify_NoMismatches_ShutsDownMockServer() public void Verify_FailedToWritePactFile_ThrowsInvalidOperationException() { this.mockDriver - .Setup(s => s.WritePactFile(It.IsAny())) + .Setup(s => s.WritePactFile(It.IsAny(), It.IsAny())) .Throws(); Action action = () => this.builder.Verify(Success); diff --git a/tests/PactNet.Tests/data/v2-consumer-integration.json b/tests/PactNet.Tests/data/v2-consumer-integration.json index 9484eef44..7c3a57028 100644 --- a/tests/PactNet.Tests/data/v2-consumer-integration.json +++ b/tests/PactNet.Tests/data/v2-consumer-integration.json @@ -75,6 +75,7 @@ "metadata": { "pactRust": { "ffi": "0.4.27", + "mockserver": "1.2.11", "models": "1.2.8" }, "pactSpecification": { diff --git a/tests/PactNet.Tests/data/v3-consumer-integration.json b/tests/PactNet.Tests/data/v3-consumer-integration.json index b220eb497..269da5e69 100644 --- a/tests/PactNet.Tests/data/v3-consumer-integration.json +++ b/tests/PactNet.Tests/data/v3-consumer-integration.json @@ -131,6 +131,7 @@ "metadata": { "pactRust": { "ffi": "0.4.27", + "mockserver": "1.2.11", "models": "1.2.8" }, "pactSpecification": { diff --git a/tests/PactNet.Tests/data/v4-combined-integration.json b/tests/PactNet.Tests/data/v4-combined-integration.json index 618085116..1a3483b2a 100644 --- a/tests/PactNet.Tests/data/v4-combined-integration.json +++ b/tests/PactNet.Tests/data/v4-combined-integration.json @@ -145,6 +145,7 @@ }, "status": 201 }, + "transport": "http", "type": "Synchronous/HTTP" }, { diff --git a/tests/PactNet.Tests/data/v4-consumer-integration.json b/tests/PactNet.Tests/data/v4-consumer-integration.json index 87ef562b3..5c1ee1619 100644 --- a/tests/PactNet.Tests/data/v4-consumer-integration.json +++ b/tests/PactNet.Tests/data/v4-consumer-integration.json @@ -145,12 +145,14 @@ }, "status": 201 }, + "transport": "http", "type": "Synchronous/HTTP" } ], "metadata": { "pactRust": { "ffi": "0.4.27", + "mockserver": "1.2.11", "models": "1.2.8" }, "pactSpecification": { From ab5204b111e4eb55708c79cb6965cbcf9216b48c Mon Sep 17 00:00:00 2001 From: Max Lancaster Date: Wed, 10 Sep 2025 17:08:26 -0400 Subject: [PATCH 05/35] refactor: Refactor InitialiseLogging to shared LogToBuffer extension method --- src/PactNet/Interop/LogLevelExtensions.cs | 42 ++++++++++++++++++ src/PactNet/PactExtensions.cs | 44 +++---------------- .../Verifier/InteropVerifierProvider.cs | 12 +---- .../Drivers/FfiIntegrationTests.cs | 4 +- 4 files changed, 49 insertions(+), 53 deletions(-) create mode 100644 src/PactNet/Interop/LogLevelExtensions.cs diff --git a/src/PactNet/Interop/LogLevelExtensions.cs b/src/PactNet/Interop/LogLevelExtensions.cs new file mode 100644 index 000000000..acc77f38d --- /dev/null +++ b/src/PactNet/Interop/LogLevelExtensions.cs @@ -0,0 +1,42 @@ +using System; + +namespace PactNet.Interop; + +/// +/// PactLogLevel extension methods +/// +internal static class LogLevelExtensions +{ + private static readonly object LogLocker = new object(); + private static bool LogInitialised = false; + + /// + /// Direct all logging in the native library to a task local memory buffer. + /// + /// Log level + /// Invalid log level + /// Logging can only be initialised **once**. Subsequent calls will have no effect + public static void LogToBuffer(this PactLogLevel level) + { + lock (LogLocker) + { + if (LogInitialised) + { + return; + } + + NativeInterop.LogToBuffer(level switch + { + PactLogLevel.Trace => LevelFilter.Trace, + PactLogLevel.Debug => LevelFilter.Debug, + PactLogLevel.Information => LevelFilter.Info, + PactLogLevel.Warn => LevelFilter.Warn, + PactLogLevel.Error => LevelFilter.Error, + PactLogLevel.None => LevelFilter.Off, + _ => throw new ArgumentOutOfRangeException(nameof(level), level, "Invalid log level") + }); + + LogInitialised = true; + } + } +} diff --git a/src/PactNet/PactExtensions.cs b/src/PactNet/PactExtensions.cs index 7999b227d..23d18d6b8 100644 --- a/src/PactNet/PactExtensions.cs +++ b/src/PactNet/PactExtensions.cs @@ -1,4 +1,3 @@ -using System; using PactNet.Drivers; using PactNet.Drivers.Http; using PactNet.Drivers.Message; @@ -12,9 +11,6 @@ namespace PactNet /// public static class PactExtensions { - private static readonly object LogLocker = new object(); - private static bool LogInitialised = false; - /// /// Establish a new pact using the native backend /// @@ -29,7 +25,7 @@ public static class PactExtensions /// public static IPactBuilderV2 WithHttpInteractions(this IPactV2 pact, int? port = null, IPAddress host = IPAddress.Loopback) { - InitialiseLogging(pact.Config.LogLevel); + pact.Config.LogLevel.LogToBuffer(); IPactDriver driver = new PactDriver(); IHttpPactDriver httpPact = driver.NewHttpPact(pact.Consumer, pact.Provider, PactSpecification.V2); @@ -52,7 +48,7 @@ public static IPactBuilderV2 WithHttpInteractions(this IPactV2 pact, int? port = /// public static IPactBuilderV3 WithHttpInteractions(this IPactV3 pact, int? port = null, IPAddress host = IPAddress.Loopback) { - InitialiseLogging(pact.Config.LogLevel); + pact.Config.LogLevel.LogToBuffer(); IPactDriver driver = new PactDriver(); IHttpPactDriver httpPact = driver.NewHttpPact(pact.Consumer, pact.Provider, PactSpecification.V3); @@ -75,7 +71,7 @@ public static IPactBuilderV3 WithHttpInteractions(this IPactV3 pact, int? port = /// public static IPactBuilderV4 WithHttpInteractions(this IPactV4 pact, int? port = null, IPAddress host = IPAddress.Loopback) { - InitialiseLogging(pact.Config.LogLevel); + pact.Config.LogLevel.LogToBuffer(); IPactDriver driver = new PactDriver(); IHttpPactDriver httpPact = driver.NewHttpPact(pact.Consumer, pact.Provider, PactSpecification.V4); @@ -91,7 +87,7 @@ public static IPactBuilderV4 WithHttpInteractions(this IPactV4 pact, int? port = /// Pact builder public static IMessagePactBuilderV3 WithMessageInteractions(this IPactV3 pact) { - InitialiseLogging(pact.Config.LogLevel); + pact.Config.LogLevel.LogToBuffer(); IPactDriver driver = new PactDriver(); IMessagePactDriver messagePact = driver.NewMessagePact(pact.Consumer, pact.Provider, PactSpecification.V3); @@ -107,7 +103,7 @@ public static IMessagePactBuilderV3 WithMessageInteractions(this IPactV3 pact) /// Pact builder public static IMessagePactBuilderV4 WithMessageInteractions(this IPactV4 pact) { - InitialiseLogging(pact.Config.LogLevel); + pact.Config.LogLevel.LogToBuffer(); IPactDriver driver = new PactDriver(); IMessagePactDriver messagePact = driver.NewMessagePact(pact.Consumer, pact.Provider, PactSpecification.V4); @@ -115,35 +111,5 @@ public static IMessagePactBuilderV4 WithMessageInteractions(this IPactV4 pact) var builder = new MessagePactBuilder(messagePact, pact.Config, PactSpecification.V4); return builder; } - - /// - /// Initialise logging in the native library - /// - /// Log level - /// Invalid log level - /// Logging can only be initialised **once**. Subsequent calls will have no effect - private static void InitialiseLogging(PactLogLevel level) - { - lock (LogLocker) - { - if (LogInitialised) - { - return; - } - - NativeInterop.LogToBuffer(level switch - { - PactLogLevel.Trace => LevelFilter.Trace, - PactLogLevel.Debug => LevelFilter.Debug, - PactLogLevel.Information => LevelFilter.Info, - PactLogLevel.Warn => LevelFilter.Warn, - PactLogLevel.Error => LevelFilter.Error, - PactLogLevel.None => LevelFilter.Off, - _ => throw new ArgumentOutOfRangeException(nameof(level), level, "Invalid log level") - }); - - LogInitialised = true; - } - } } } diff --git a/src/PactNet/Verifier/InteropVerifierProvider.cs b/src/PactNet/Verifier/InteropVerifierProvider.cs index c0245296f..8de20a676 100644 --- a/src/PactNet/Verifier/InteropVerifierProvider.cs +++ b/src/PactNet/Verifier/InteropVerifierProvider.cs @@ -31,17 +31,7 @@ public InteropVerifierProvider(PactVerifierConfig config) /// public void Initialise() { - NativeInterop.LogToBuffer(config.LogLevel switch - { - PactLogLevel.Trace => LevelFilter.Trace, - PactLogLevel.Debug => LevelFilter.Debug, - PactLogLevel.Information => LevelFilter.Info, - PactLogLevel.Warn => LevelFilter.Warn, - PactLogLevel.Error => LevelFilter.Error, - PactLogLevel.None => LevelFilter.Off, - _ => throw new ArgumentOutOfRangeException(nameof(config.LogLevel), config.LogLevel, "Invalid log level") - }); - + this.config.LogLevel.LogToBuffer(); this.handle = NativeInterop.VerifierNewForApplication("pact-net", typeof(InteropVerifierProvider).Assembly.GetName().Version.ToString()); } diff --git a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs index a853d4c83..e8a6098f8 100644 --- a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs +++ b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs @@ -24,8 +24,7 @@ public class FfiIntegrationTests public FfiIntegrationTests(ITestOutputHelper output) { this.output = output; - - NativeInterop.LogToBuffer(LevelFilter.Trace); + PactLogLevel.Trace.LogToBuffer(); } [Fact] @@ -38,7 +37,6 @@ public async Task HttpInteraction_v3_CreatesPactFile() IHttpPactDriver pact = driver.NewHttpPact("NativeDriverTests-Consumer-V3", "NativeDriverTests-Provider", PactSpecification.V3); - IHttpInteractionDriver interaction = pact.NewHttpInteraction("a sample interaction"); interaction.Given("provider state"); From 6ab9c0f0e751f7a410f878a91dfdacee8efd4dd3 Mon Sep 17 00:00:00 2001 From: Max Lancaster Date: Tue, 7 Oct 2025 16:49:44 -0400 Subject: [PATCH 06/35] feat: Add support for synchronous plugin interactions --- .../ISynchronousPluginPactBuilder.cs | 8 ++++ .../ISynchronousPluginRequestBuilder.cs | 28 ++++++++++++ src/PactNet/Drivers/IPactDriver.cs | 14 +++++- .../Plugins/IPluginInteractionDriver.cs | 8 ++-- .../Drivers/Plugins/IPluginPactDriver.cs | 6 ++- .../Plugins/PluginInteractionDriver.cs | 12 +++--- .../Drivers/Plugins/PluginPactDriver.cs | 31 ++++++++++++- src/PactNet/PactExtensions.cs | 31 +++++++++++-- src/PactNet/SynchronousPluginPactBuilder.cs | 20 +++++++++ .../SynchronousPluginRequestBuilder.cs | 43 +++++++++++++++++++ 10 files changed, 185 insertions(+), 16 deletions(-) create mode 100644 src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs create mode 100644 src/PactNet.Abstractions/ISynchronousPluginRequestBuilder.cs create mode 100644 src/PactNet/SynchronousPluginPactBuilder.cs create mode 100644 src/PactNet/SynchronousPluginRequestBuilder.cs diff --git a/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs b/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs new file mode 100644 index 000000000..0ac60ae17 --- /dev/null +++ b/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs @@ -0,0 +1,8 @@ +using System; + +namespace PactNet; + +public interface ISynchronousPluginPactBuilderV4 : IPactBuilder, IDisposable +{ + ISynchronousPluginRequestBuilderV4 UponReceiving(string description); +} diff --git a/src/PactNet.Abstractions/ISynchronousPluginRequestBuilder.cs b/src/PactNet.Abstractions/ISynchronousPluginRequestBuilder.cs new file mode 100644 index 000000000..eefe5b514 --- /dev/null +++ b/src/PactNet.Abstractions/ISynchronousPluginRequestBuilder.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; + +namespace PactNet; + +public interface ISynchronousPluginRequestBuilderV4 +{ + /// + /// Add a provider state + /// + /// Provider state description + /// Fluent builder + ISynchronousPluginRequestBuilderV4 Given(string description); + + /// + /// Add a provider state with a parameter to the interaction + /// + /// Provider state description + /// Parameter name + /// Parameter value + ISynchronousPluginRequestBuilderV4 Given(string description, string name, string value); + + /// + /// Add plugin interaction content + /// + /// Content type + /// A dictionary containing the plugin content. + ISynchronousPluginRequestBuilderV4 WithContent(string contentType, Dictionary content); +} diff --git a/src/PactNet/Drivers/IPactDriver.cs b/src/PactNet/Drivers/IPactDriver.cs index a787052b9..a3eaa1f7d 100644 --- a/src/PactNet/Drivers/IPactDriver.cs +++ b/src/PactNet/Drivers/IPactDriver.cs @@ -1,11 +1,12 @@ using PactNet.Drivers.Http; using PactNet.Drivers.Message; +using PactNet.Drivers.Plugins; using PactNet.Interop; namespace PactNet.Drivers { /// - /// Driver for creating a new pact and + /// Driver for creating a new pact and /// internal interface IPactDriver { @@ -32,5 +33,16 @@ internal interface IPactDriver /// /// Logs string DriverLogs(); + + /// + /// Create a new plugin pact + /// + /// Consumer name + /// Provider name + /// Plugin name + /// Plugin version + /// Specification version + /// Plugin pact driver + IPluginPactDriver NewPluginPact(string consumerName, string providerName, string pluginName, string pluginVersion, PactSpecification version); } } diff --git a/src/PactNet/Drivers/Plugins/IPluginInteractionDriver.cs b/src/PactNet/Drivers/Plugins/IPluginInteractionDriver.cs index 9cc90aa6e..7b6fa41f5 100644 --- a/src/PactNet/Drivers/Plugins/IPluginInteractionDriver.cs +++ b/src/PactNet/Drivers/Plugins/IPluginInteractionDriver.cs @@ -1,4 +1,6 @@ -namespace PactNet.Drivers.Plugins +using System.Collections.Generic; + +namespace PactNet.Drivers.Plugins { /// /// Driver for plugin interactions @@ -9,7 +11,7 @@ internal interface IPluginInteractionDriver : IProviderStateDriver /// Add a plugin interaction content /// /// Content type - /// Content - void WithContent(string contentType, string content); + /// A dictionary containing the plugin content. + void WithContent(string contentType, Dictionary content); } } diff --git a/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs b/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs index 79a09eac9..09c9b395b 100644 --- a/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs +++ b/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs @@ -1,9 +1,11 @@ -namespace PactNet.Drivers.Plugins +using System; + +namespace PactNet.Drivers.Plugins { /// /// Driver for plugin-based pacts /// - internal interface IPluginPactDriver : ICompletedPactDriver + internal interface IPluginPactDriver : ICompletedPactDriver, IDisposable { /// /// Create a new sync interaction on the current pact diff --git a/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs b/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs index 15f4b70c3..e2cf360b0 100644 --- a/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs +++ b/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs @@ -1,4 +1,6 @@ -using PactNet.Exceptions; +using System.Collections.Generic; +using System.Text.Json; +using PactNet.Exceptions; using PactNet.Interop; namespace PactNet.Drivers.Plugins @@ -36,13 +38,13 @@ public void GivenWithParam(string description, string name, string value) => NativeInterop.GivenWithParam(this.interaction, description, name, value).CheckInteropSuccess(); /// - /// Add a plugin interaction content + /// Add plugin interaction content /// /// Content type - /// Content - public void WithContent(string contentType, string content) + /// A dictionary containing the plugin content. + public void WithContent(string contentType, Dictionary content) { - uint code = NativeInterop.InteractionContents(this.interaction, InteractionPart.Request, contentType, content); + uint code = NativeInterop.InteractionContents(this.interaction, InteractionPart.Request, contentType, JsonSerializer.Serialize(content)); if (code != 0) { diff --git a/src/PactNet/Drivers/Plugins/PluginPactDriver.cs b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs index 63acf58db..45c28f1f4 100644 --- a/src/PactNet/Drivers/Plugins/PluginPactDriver.cs +++ b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs @@ -1,11 +1,12 @@ -using PactNet.Interop; +using System; +using PactNet.Interop; namespace PactNet.Drivers.Plugins { /// /// Driver for plugin-based pacts /// - internal class PluginPactDriver : AbstractPactDriver, IPluginPactDriver + internal class PluginPactDriver : AbstractPactDriver, IPluginPactDriver, IDisposable { /// /// Initialize a new instance of the class. @@ -25,5 +26,31 @@ public IPluginInteractionDriver NewSyncInteraction(string description) InteractionHandle interaction = NativeInterop.NewSyncMessageInteraction(this.pact, description); return new PluginInteractionDriver(interaction); } + + + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public void Dispose() + { + this.ReleaseUnmanagedResources(); + GC.SuppressFinalize(this); + } + + /// + /// Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. + /// + ~PluginPactDriver() + { + this.ReleaseUnmanagedResources(); + } + + /// + /// Release unmanaged resources + /// + private void ReleaseUnmanagedResources() + { + NativeInterop.CleanupPlugins(pact); + } } } diff --git a/src/PactNet/PactExtensions.cs b/src/PactNet/PactExtensions.cs index 23d18d6b8..b1432baf0 100644 --- a/src/PactNet/PactExtensions.cs +++ b/src/PactNet/PactExtensions.cs @@ -1,6 +1,7 @@ using PactNet.Drivers; using PactNet.Drivers.Http; using PactNet.Drivers.Message; +using PactNet.Drivers.Plugins; using PactNet.Interop; using PactNet.Models; @@ -23,7 +24,8 @@ public static class PactExtensions /// It is advised that the port is not specified whenever possible to allow PactNet to allocate a port dynamically /// and ensure there are no port clashes /// - public static IPactBuilderV2 WithHttpInteractions(this IPactV2 pact, int? port = null, IPAddress host = IPAddress.Loopback) + public static IPactBuilderV2 WithHttpInteractions(this IPactV2 pact, int? port = null, + IPAddress host = IPAddress.Loopback) { pact.Config.LogLevel.LogToBuffer(); @@ -46,7 +48,8 @@ public static IPactBuilderV2 WithHttpInteractions(this IPactV2 pact, int? port = /// It is advised that the port is not specified whenever possible to allow PactNet to allocate a port dynamically /// and ensure there are no port clashes /// - public static IPactBuilderV3 WithHttpInteractions(this IPactV3 pact, int? port = null, IPAddress host = IPAddress.Loopback) + public static IPactBuilderV3 WithHttpInteractions(this IPactV3 pact, int? port = null, + IPAddress host = IPAddress.Loopback) { pact.Config.LogLevel.LogToBuffer(); @@ -69,7 +72,8 @@ public static IPactBuilderV3 WithHttpInteractions(this IPactV3 pact, int? port = /// It is advised that the port is not specified whenever possible to allow PactNet to allocate a port dynamically /// and ensure there are no port clashes /// - public static IPactBuilderV4 WithHttpInteractions(this IPactV4 pact, int? port = null, IPAddress host = IPAddress.Loopback) + public static IPactBuilderV4 WithHttpInteractions(this IPactV4 pact, int? port = null, + IPAddress host = IPAddress.Loopback) { pact.Config.LogLevel.LogToBuffer(); @@ -111,5 +115,26 @@ public static IMessagePactBuilderV4 WithMessageInteractions(this IPactV4 pact) var builder = new MessagePactBuilder(messagePact, pact.Config, PactSpecification.V4); return builder; } + + /// + /// Establish a new pact with synchronous plugin interactions. + /// + /// + /// Plugin name + /// Plugin version + /// The transport to use (i.e. http, https, grpc). Must be a valid UTF-8 NULL-terminated string, or NULL or empty, in which case http will be used. + /// Port for the mock server. If null, one will be assigned automatically + /// Host for the mock server + /// + public static ISynchronousPluginPactBuilderV4 WithSynchronousPluginInteractions(this IPactV4 pact, + string pluginName, string pluginVersion, string transport = null, int? port = null, + IPAddress host = IPAddress.Loopback) + { + pact.Config.LogLevel.LogToBuffer(); + IPactDriver driver = new PactDriver(); + var pluginDriver = driver.NewPluginPact(pact.Consumer, pact.Provider, pluginName, pluginVersion, + PactSpecification.V4); + return new SynchronousPluginPactBuilder(pluginDriver, pact.Config, port, host, transport); + } } } diff --git a/src/PactNet/SynchronousPluginPactBuilder.cs b/src/PactNet/SynchronousPluginPactBuilder.cs new file mode 100644 index 000000000..084b37bfc --- /dev/null +++ b/src/PactNet/SynchronousPluginPactBuilder.cs @@ -0,0 +1,20 @@ +using PactNet.Drivers.Plugins; +using PactNet.Models; + +namespace PactNet; + +internal class SynchronousPluginPactBuilder( + IPluginPactDriver pact, + PactConfig config, + int? port, + IPAddress host, + string transport = null) + : AbstractPactBuilder(pact, config, port, host, transport), ISynchronousPluginPactBuilderV4 +{ + public ISynchronousPluginRequestBuilderV4 UponReceiving(string description) + { + return new SynchronousPluginRequestBuilder(pact.NewSyncInteraction(description)); + } + + public void Dispose() => pact?.Dispose(); +} diff --git a/src/PactNet/SynchronousPluginRequestBuilder.cs b/src/PactNet/SynchronousPluginRequestBuilder.cs new file mode 100644 index 000000000..d3da9c41f --- /dev/null +++ b/src/PactNet/SynchronousPluginRequestBuilder.cs @@ -0,0 +1,43 @@ +using System.Collections.Generic; +using PactNet.Drivers.Plugins; + +namespace PactNet; + +internal class SynchronousPluginRequestBuilder(IPluginInteractionDriver interactionDriver) + : ISynchronousPluginRequestBuilderV4 +{ + + /// + /// Add a provider state + /// + /// Provider state description + /// Fluent builder + public ISynchronousPluginRequestBuilderV4 Given(string description) + { + interactionDriver.Given(description); + return this; + } + + /// + /// Add a provider state with a parameter to the interaction + /// + /// Provider state description + /// Parameter name + /// Parameter value + public ISynchronousPluginRequestBuilderV4 Given(string description, string name, string value) + { + interactionDriver.GivenWithParam(description, name, value); + return this; + } + + /// + /// Add plugin interaction content + /// + /// Content type + /// A dictionary containing the plugin content. + public ISynchronousPluginRequestBuilderV4 WithContent(string contentType, Dictionary content) + { + interactionDriver.WithContent(contentType, content); + return this; + } +} From 85548d15803deecb6759cdfbca6cccc99ee82c60 Mon Sep 17 00:00:00 2001 From: Max Lancaster Date: Tue, 7 Oct 2025 17:47:12 -0400 Subject: [PATCH 07/35] test(grpc): Add Grpc Sample --- PactNet.sln | 69 +++++++++++++ .../GrpcGreeter.Tests.csproj | 23 +++++ .../Grpc/GrpcGreeter.Tests/GrpcGreeterTest.cs | 50 ++++++++++ .../Grpc/GrpcGreeter.Tests/ServerFixture.cs | 28 ++++++ samples/Grpc/GrpcGreeter/GrpcGreeter.csproj | 18 ++++ samples/Grpc/GrpcGreeter/Program.cs | 16 +++ .../Properties/launchSettings.json | 23 +++++ samples/Grpc/GrpcGreeter/Protos/greet.proto | 21 ++++ .../GrpcGreeter/Services/GreeterService.cs | 22 +++++ samples/Grpc/GrpcGreeter/Startup.cs | 37 +++++++ .../GrpcGreeter/appsettings.Development.json | 8 ++ samples/Grpc/GrpcGreeter/appsettings.json | 14 +++ .../GrpcGreeterClient.Tests.csproj | 23 +++++ .../GrpcGreeterClientTest.cs | 97 +++++++++++++++++++ .../GrpcGreeterClient.csproj | 25 +++++ samples/Grpc/GrpcGreeterClient/Program.cs | 32 ++++++ .../Grpc/GrpcGreeterClient/Protos/greet.proto | 21 ++++ .../grpc-greeter-client-grpc-greeter.json | 96 ++++++++++++++++++ .../OrdersApi/Provider.Tests/ProviderTests.cs | 4 +- 19 files changed, 625 insertions(+), 2 deletions(-) create mode 100644 samples/Grpc/GrpcGreeter.Tests/GrpcGreeter.Tests.csproj create mode 100644 samples/Grpc/GrpcGreeter.Tests/GrpcGreeterTest.cs create mode 100644 samples/Grpc/GrpcGreeter.Tests/ServerFixture.cs create mode 100644 samples/Grpc/GrpcGreeter/GrpcGreeter.csproj create mode 100644 samples/Grpc/GrpcGreeter/Program.cs create mode 100644 samples/Grpc/GrpcGreeter/Properties/launchSettings.json create mode 100644 samples/Grpc/GrpcGreeter/Protos/greet.proto create mode 100644 samples/Grpc/GrpcGreeter/Services/GreeterService.cs create mode 100644 samples/Grpc/GrpcGreeter/Startup.cs create mode 100644 samples/Grpc/GrpcGreeter/appsettings.Development.json create mode 100644 samples/Grpc/GrpcGreeter/appsettings.json create mode 100644 samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClient.Tests.csproj create mode 100644 samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClientTest.cs create mode 100644 samples/Grpc/GrpcGreeterClient/GrpcGreeterClient.csproj create mode 100644 samples/Grpc/GrpcGreeterClient/Program.cs create mode 100644 samples/Grpc/GrpcGreeterClient/Protos/greet.proto create mode 100644 samples/Grpc/pacts/grpc-greeter-client-grpc-greeter.json diff --git a/PactNet.sln b/PactNet.sln index 243019fae..a63927829 100644 --- a/PactNet.sln +++ b/PactNet.sln @@ -37,6 +37,21 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PactNet.Output.Xunit", "src\PactNet.Output.Xunit\PactNet.Output.Xunit.csproj", "{02E265A1-A7A2-4106-8F6A-5027FDC3FC50}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Grpc", "Grpc", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GrpcGreeter", "samples\Grpc\GrpcGreeter\GrpcGreeter.csproj", "{529F37CB-CDA0-6553-EAC9-8DAC2195ED69}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GrpcGreeterClient", "samples\Grpc\GrpcGreeterClient\GrpcGreeterClient.csproj", "{917DAC61-55B4-D721-B1ED-B0E352E4CF1A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GrpcGreeterClient.Tests", "samples\Grpc\GrpcGreeterClient.Tests\GrpcGreeterClient.Tests.csproj", "{13756BC3-0750-E2AF-E1F0-565855A3E636}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GrpcGreeter.Tests", "samples\Grpc\GrpcGreeter.Tests\GrpcGreeter.Tests.csproj", "{DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "pacts", "pacts", "{FB3A8B7F-7DA0-40A8-AFD1-FB0992FB9B2C}" + ProjectSection(SolutionItems) = preProject + samples\Grpc\pacts\grpc-greeter-client-grpc-greeter.json = samples\Grpc\pacts\grpc-greeter-client-grpc-greeter.json + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -155,6 +170,54 @@ Global {02E265A1-A7A2-4106-8F6A-5027FDC3FC50}.Release|x64.Build.0 = Release|Any CPU {02E265A1-A7A2-4106-8F6A-5027FDC3FC50}.Release|x86.ActiveCfg = Release|Any CPU {02E265A1-A7A2-4106-8F6A-5027FDC3FC50}.Release|x86.Build.0 = Release|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Debug|Any CPU.Build.0 = Debug|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Debug|x64.ActiveCfg = Debug|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Debug|x64.Build.0 = Debug|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Debug|x86.ActiveCfg = Debug|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Debug|x86.Build.0 = Debug|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Release|Any CPU.ActiveCfg = Release|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Release|Any CPU.Build.0 = Release|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Release|x64.ActiveCfg = Release|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Release|x64.Build.0 = Release|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Release|x86.ActiveCfg = Release|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Release|x86.Build.0 = Release|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Debug|x64.ActiveCfg = Debug|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Debug|x64.Build.0 = Debug|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Debug|x86.ActiveCfg = Debug|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Debug|x86.Build.0 = Debug|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Release|Any CPU.Build.0 = Release|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Release|x64.ActiveCfg = Release|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Release|x64.Build.0 = Release|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Release|x86.ActiveCfg = Release|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Release|x86.Build.0 = Release|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Debug|Any CPU.Build.0 = Debug|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Debug|x64.ActiveCfg = Debug|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Debug|x64.Build.0 = Debug|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Debug|x86.ActiveCfg = Debug|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Debug|x86.Build.0 = Debug|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Release|Any CPU.ActiveCfg = Release|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Release|Any CPU.Build.0 = Release|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Release|x64.ActiveCfg = Release|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Release|x64.Build.0 = Release|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Release|x86.ActiveCfg = Release|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Release|x86.Build.0 = Release|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Debug|x64.ActiveCfg = Debug|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Debug|x64.Build.0 = Debug|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Debug|x86.ActiveCfg = Debug|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Debug|x86.Build.0 = Debug|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Release|Any CPU.Build.0 = Release|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Release|x64.ActiveCfg = Release|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Release|x64.Build.0 = Release|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Release|x86.ActiveCfg = Release|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -170,6 +233,12 @@ Global {5E915D66-917B-4730-B31A-C9727C196346} = {6663C12E-9912-40D0-9310-D119D1F6B023} {D8B75E48-6E45-468B-8049-B73823C14CB8} = {6663C12E-9912-40D0-9310-D119D1F6B023} {02E265A1-A7A2-4106-8F6A-5027FDC3FC50} = {CF67D7A1-AE96-420B-9971-65E535B903E8} + {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} = {547DB478-460A-428F-9371-1D653CE85DB5} + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {13756BC3-0750-E2AF-E1F0-565855A3E636} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {FB3A8B7F-7DA0-40A8-AFD1-FB0992FB9B2C} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {C2CBC30C-92D4-4E3A-A5B8-1E5D4E938DFC} diff --git a/samples/Grpc/GrpcGreeter.Tests/GrpcGreeter.Tests.csproj b/samples/Grpc/GrpcGreeter.Tests/GrpcGreeter.Tests.csproj new file mode 100644 index 000000000..1fdf3de2f --- /dev/null +++ b/samples/Grpc/GrpcGreeter.Tests/GrpcGreeter.Tests.csproj @@ -0,0 +1,23 @@ + + + net8.0 + false + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + diff --git a/samples/Grpc/GrpcGreeter.Tests/GrpcGreeterTest.cs b/samples/Grpc/GrpcGreeter.Tests/GrpcGreeterTest.cs new file mode 100644 index 000000000..27a6806e5 --- /dev/null +++ b/samples/Grpc/GrpcGreeter.Tests/GrpcGreeterTest.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.IO; +using PactNet; +using PactNet.Exceptions; +using PactNet.Infrastructure.Outputters; +using Xunit; +using PactNet.Output.Xunit; +using PactNet.Verifier; +using Xunit.Abstractions; + +namespace GrpcGreeter.Tests +{ + public class GrpcGreeterTests(ITestOutputHelper output, ServerFixture serverFixture) : IClassFixture, IDisposable + { + private readonly PactVerifier verifier = new("Grpc Greeter Api", new PactVerifierConfig + { + LogLevel = PactLogLevel.Information, + Outputters = new List + { + new XunitOutput(output) + } + }); + + private readonly string pactPath = Path.Combine("..", "..", "..", "..", "..", "Grpc", "pacts", + "grpc-greeter-client-grpc-greeter.json"); + + [Fact] + public void VerificationThrowsExceptionWhenNoRunningProvider() + { + Assert.Throws(() => verifier + .WithHttpEndpoint(new Uri("http://localhost:5060")) + .WithFileSource(new FileInfo(pactPath)) + .Verify()); + } + + [Fact] + public void VerificationSuccessForRunningProvider() + { + verifier.WithHttpEndpoint(serverFixture.ProviderUri) + .WithFileSource(new FileInfo(pactPath)) + .Verify(); + } + + public void Dispose() + { + this.verifier?.Dispose(); + } + } +} diff --git a/samples/Grpc/GrpcGreeter.Tests/ServerFixture.cs b/samples/Grpc/GrpcGreeter.Tests/ServerFixture.cs new file mode 100644 index 000000000..f2f64b202 --- /dev/null +++ b/samples/Grpc/GrpcGreeter.Tests/ServerFixture.cs @@ -0,0 +1,28 @@ +using System; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; +using PactNet; +using PactNet.Interop; + +namespace GrpcGreeter.Tests; + +public class ServerFixture : IDisposable +{ + public readonly Uri ProviderUri = new("http://localhost:5000"); + private readonly IHost server; + + public ServerFixture() + { + this.server = Host.CreateDefaultBuilder() + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseUrls(this.ProviderUri.ToString()); + webBuilder.UseStartup(); + }) + .Build(); + + this.server.Start(); + } + + public void Dispose() => this.server?.Dispose(); +} diff --git a/samples/Grpc/GrpcGreeter/GrpcGreeter.csproj b/samples/Grpc/GrpcGreeter/GrpcGreeter.csproj new file mode 100644 index 000000000..ef753ccdf --- /dev/null +++ b/samples/Grpc/GrpcGreeter/GrpcGreeter.csproj @@ -0,0 +1,18 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + diff --git a/samples/Grpc/GrpcGreeter/Program.cs b/samples/Grpc/GrpcGreeter/Program.cs new file mode 100644 index 000000000..21afa97ab --- /dev/null +++ b/samples/Grpc/GrpcGreeter/Program.cs @@ -0,0 +1,16 @@ +namespace GrpcGreeter; + +public class GrpcGreeterService +{ + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); +} diff --git a/samples/Grpc/GrpcGreeter/Properties/launchSettings.json b/samples/Grpc/GrpcGreeter/Properties/launchSettings.json new file mode 100644 index 000000000..f67a267d9 --- /dev/null +++ b/samples/Grpc/GrpcGreeter/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5251", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7272;http://localhost:5251", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/samples/Grpc/GrpcGreeter/Protos/greet.proto b/samples/Grpc/GrpcGreeter/Protos/greet.proto new file mode 100644 index 000000000..02343fa08 --- /dev/null +++ b/samples/Grpc/GrpcGreeter/Protos/greet.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; + +option csharp_namespace = "GrpcGreeter"; + +package greet; + +// The greeting service definition. +service Greeter { + // Sends a greeting + rpc SayHello (HelloRequest) returns (HelloReply); +} + +// The request message containing the user's name. +message HelloRequest { + string name = 1; +} + +// The response message containing the greetings. +message HelloReply { + string message = 1; +} diff --git a/samples/Grpc/GrpcGreeter/Services/GreeterService.cs b/samples/Grpc/GrpcGreeter/Services/GreeterService.cs new file mode 100644 index 000000000..590619120 --- /dev/null +++ b/samples/Grpc/GrpcGreeter/Services/GreeterService.cs @@ -0,0 +1,22 @@ +using Grpc.Core; +using GrpcGreeter; + +namespace GrpcGreeter.Services +{ + public class GreeterService : Greeter.GreeterBase + { + private readonly ILogger _logger; + public GreeterService(ILogger logger) + { + _logger = logger; + } + + public override Task SayHello(HelloRequest request, ServerCallContext context) + { + return Task.FromResult(new HelloReply + { + Message = "Hello " + request.Name + }); + } + } +} diff --git a/samples/Grpc/GrpcGreeter/Startup.cs b/samples/Grpc/GrpcGreeter/Startup.cs new file mode 100644 index 000000000..4d4196e85 --- /dev/null +++ b/samples/Grpc/GrpcGreeter/Startup.cs @@ -0,0 +1,37 @@ +using GrpcGreeter.Services; + +namespace GrpcGreeter; + +public class Startup +{ + public IConfiguration Configuration { get; } + + public Startup(IConfiguration configuration) + { + this.Configuration = configuration; + } + + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + // Add services to the container. + services.AddGrpc(); + services.AddGrpcReflection(); + + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + app.UseRouting(); + app.UseEndpoints(b => + { + // Configure the HTTP request pipeline. + b.MapGrpcService(); + b.MapGet("/", + () => + "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909"); + b.MapGrpcReflectionService(); + }); + } +} diff --git a/samples/Grpc/GrpcGreeter/appsettings.Development.json b/samples/Grpc/GrpcGreeter/appsettings.Development.json new file mode 100644 index 000000000..0c208ae91 --- /dev/null +++ b/samples/Grpc/GrpcGreeter/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/samples/Grpc/GrpcGreeter/appsettings.json b/samples/Grpc/GrpcGreeter/appsettings.json new file mode 100644 index 000000000..1aef5074f --- /dev/null +++ b/samples/Grpc/GrpcGreeter/appsettings.json @@ -0,0 +1,14 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Kestrel": { + "EndpointDefaults": { + "Protocols": "Http2" + } + } +} diff --git a/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClient.Tests.csproj b/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClient.Tests.csproj new file mode 100644 index 000000000..e51c7d079 --- /dev/null +++ b/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClient.Tests.csproj @@ -0,0 +1,23 @@ + + + net8.0 + false + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + diff --git a/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClientTest.cs b/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClientTest.cs new file mode 100644 index 000000000..8e3bdf722 --- /dev/null +++ b/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClientTest.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Threading.Tasks; +using FluentAssertions; +using Xunit; +using System.IO; +using System.Text.Json.Serialization; +using PactNet; +using PactNet.Exceptions; +using PactNet.Output.Xunit; +using Xunit.Abstractions; + +namespace GrpcGreeterClient.Tests +{ + public class GrpcGreeterClientTests : IDisposable + { + private readonly ISynchronousPluginPactBuilderV4 pact; + + public GrpcGreeterClientTests(ITestOutputHelper output) + { + var config = new PactConfig + { + PactDir = "../../../../pacts/", + Outputters = new[] { new XunitOutput(output) }, + DefaultJsonSettings = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter() } + }, + LogLevel = PactLogLevel.Information + }; + + this.pact = Pact.V4("grpc-greeter-client", "grpc-greeter", config) + .WithSynchronousPluginInteractions("protobuf", "0.4.0", transport: "grpc"); + } + + [Fact] + public void ThrowsExceptionWhenNoGrpcClientRequestMade() + { + string protoFilePath = Path.Join(Directory.GetCurrentDirectory(), "..", "..", "..", "..", "GrpcGreeterClient", "Protos", "greet.proto"); + var content = new Dictionary + { + { + "pact:proto", protoFilePath + }, + { "pact:proto-service", "Greeter/SayHello" }, + { "pact:content-type", "application/protobuf" }, + { "request", new { name = "matching(equalTo, 'foo')" } }, + { "response", new { message = "matching(equalTo, 'Hello foo')" } } + }; + + this.pact.UponReceiving("A greeting request to say hello.").WithContent("application/grpc", content); + + Assert.Throws(() => + this.pact.Verify(_ => + { + // No grpc call here results in failure. + })); + } + + [Fact] + public async Task WritesPactForGreeterSayHelloRequest() + { + string protoFilePath = Path.Join(Directory.GetCurrentDirectory(), "..", "..", "..", "..", "GrpcGreeterClient", "Protos", "greet.proto"); + var content = new Dictionary + { + { + "pact:proto", protoFilePath + }, + { "pact:proto-service", "Greeter/SayHello" }, + { "pact:content-type", "application/protobuf" }, + { "request", new { name = "matching(equalTo, 'foo')" } }, + { "response", new { message = "matching(equalTo, 'Hello foo')" } } + }; + + + this.pact.UponReceiving("A greeting request to say hello.").WithContent("application/grpc", content); + + await this.pact.VerifyAsync(async ctx => + { + + // Arrange + var client = new GreeterClientWrapper(ctx.MockServerUri.AbsoluteUri); + + // Act + var greeting = await client.SayHello("foo"); + + // Assert + greeting.Should().Be("Hello foo"); + }); + } + + public void Dispose() => this.pact?.Dispose(); + } +} diff --git a/samples/Grpc/GrpcGreeterClient/GrpcGreeterClient.csproj b/samples/Grpc/GrpcGreeterClient/GrpcGreeterClient.csproj new file mode 100644 index 000000000..94331d73f --- /dev/null +++ b/samples/Grpc/GrpcGreeterClient/GrpcGreeterClient.csproj @@ -0,0 +1,25 @@ + + + + Exe + net8.0 + enable + enable + + + false + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + diff --git a/samples/Grpc/GrpcGreeterClient/Program.cs b/samples/Grpc/GrpcGreeterClient/Program.cs new file mode 100644 index 000000000..7beb6292f --- /dev/null +++ b/samples/Grpc/GrpcGreeterClient/Program.cs @@ -0,0 +1,32 @@ +using Grpc.Net.Client; +using GrpcGreeterClient; + +public class GreeterClientWrapper +{ + private readonly Greeter.GreeterClient _client; + + public GreeterClientWrapper(string url) + { + var channel = GrpcChannel.ForAddress(url); + _client = new Greeter.GreeterClient(channel); + } + + public async Task SayHello(string name) + { + var reply = await _client.SayHelloAsync(new HelloRequest { Name = name }); + return reply.Message; + } +} + +public class Program +{ + public static async Task Main(string[] args) + { + var client = new GreeterClientWrapper("http://localhost:5099"); + // var client = new GreeterClientWrapper("https://localhost:5099"); + var greeting = await client.SayHello("GreeterClient"); + Console.WriteLine("Greeting: " + greeting); + Console.WriteLine("Press any key to exit..."); + Console.ReadKey(); + } +} diff --git a/samples/Grpc/GrpcGreeterClient/Protos/greet.proto b/samples/Grpc/GrpcGreeterClient/Protos/greet.proto new file mode 100644 index 000000000..1a0159522 --- /dev/null +++ b/samples/Grpc/GrpcGreeterClient/Protos/greet.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; + +option csharp_namespace = "GrpcGreeterClient"; + +package greet; + +// The greeting service definition. +service Greeter { + // Sends a greeting + rpc SayHello (HelloRequest) returns (HelloReply); +} + +// The request message containing the user's name. +message HelloRequest { + string name = 1; +} + +// The response message containing the greetings. +message HelloReply { + string message = 1; +} diff --git a/samples/Grpc/pacts/grpc-greeter-client-grpc-greeter.json b/samples/Grpc/pacts/grpc-greeter-client-grpc-greeter.json new file mode 100644 index 000000000..c2318c69d --- /dev/null +++ b/samples/Grpc/pacts/grpc-greeter-client-grpc-greeter.json @@ -0,0 +1,96 @@ +{ + "consumer": { + "name": "grpc-greeter-client" + }, + "interactions": [ + { + "description": "A greeting request to say hello.", + "interactionMarkup": { + "markup": "```protobuf\nmessage HelloReply {\n string message = 1;\n}\n```\n", + "markupType": "COMMON_MARK" + }, + "pending": false, + "pluginConfiguration": { + "protobuf": { + "descriptorKey": "e8e1fe144f808b9b0faecd7b2605efea", + "service": "Greeter/SayHello" + } + }, + "request": { + "contents": { + "content": "CgNmb28=", + "contentType": "application/protobuf;message=HelloRequest", + "contentTypeHint": "BINARY", + "encoded": "base64" + }, + "matchingRules": { + "body": { + "$.name": { + "combine": "AND", + "matchers": [ + { + "match": "equality" + } + ] + } + } + }, + "metadata": { + "contentType": "application/protobuf;message=HelloRequest" + } + }, + "response": [ + { + "contents": { + "content": "CglIZWxsbyBmb28=", + "contentType": "application/protobuf;message=HelloReply", + "contentTypeHint": "BINARY", + "encoded": "base64" + }, + "matchingRules": { + "body": { + "$.message": { + "combine": "AND", + "matchers": [ + { + "match": "equality" + } + ] + } + } + }, + "metadata": { + "contentType": "application/protobuf;message=HelloReply" + } + } + ], + "transport": "grpc", + "type": "Synchronous/Messages" + } + ], + "metadata": { + "pactRust": { + "ffi": "0.4.27", + "mockserver": "1.2.11", + "models": "1.2.8" + }, + "pactSpecification": { + "version": "4.0" + }, + "plugins": [ + { + "configuration": { + "e8e1fe144f808b9b0faecd7b2605efea": { + "protoDescriptors": "Cr0BCgtncmVldC5wcm90bxIFZ3JlZXQiIgoMSGVsbG9SZXF1ZXN0EhIKBG5hbWUYASABKAlSBG5hbWUiJgoKSGVsbG9SZXBseRIYCgdtZXNzYWdlGAEgASgJUgdtZXNzYWdlMj0KB0dyZWV0ZXISMgoIU2F5SGVsbG8SEy5ncmVldC5IZWxsb1JlcXVlc3QaES5ncmVldC5IZWxsb1JlcGx5QhSqAhFHcnBjR3JlZXRlckNsaWVudGIGcHJvdG8z", + "protoFile": "syntax = \"proto3\";\r\n\r\noption csharp_namespace = \"GrpcGreeterClient\";\r\n\r\npackage greet;\r\n\r\n// The greeting service definition.\r\nservice Greeter {\r\n // Sends a greeting\r\n rpc SayHello (HelloRequest) returns (HelloReply);\r\n}\r\n\r\n// The request message containing the user's name.\r\nmessage HelloRequest {\r\n string name = 1;\r\n}\r\n\r\n// The response message containing the greetings.\r\nmessage HelloReply {\r\n string message = 1;\r\n}\r\n" + } + }, + "name": "protobuf", + "version": "0.4.0" + } + ] + }, + "provider": { + "name": "grpc-greeter" + } +} \ No newline at end of file diff --git a/samples/OrdersApi/Provider.Tests/ProviderTests.cs b/samples/OrdersApi/Provider.Tests/ProviderTests.cs index 1feb302ef..e8c6e8ec1 100644 --- a/samples/OrdersApi/Provider.Tests/ProviderTests.cs +++ b/samples/OrdersApi/Provider.Tests/ProviderTests.cs @@ -16,7 +16,7 @@ namespace Provider.Tests { public class ProviderTests : IDisposable { - private static readonly Uri ProviderUri = new("http://localhost:5000"); + private static readonly Uri ProviderUri = new("http://localhost:65098"); private static readonly JsonSerializerOptions Options = new() { @@ -38,7 +38,7 @@ public ProviderTests(ITestOutputHelper output) .Build(); this.server.Start(); - + this.verifier = new PactVerifier("Orders API", new PactVerifierConfig { LogLevel = PactLogLevel.Debug, From 5a97adcf3264d5c4ccd1fa22cd1faaf09dd04cc0 Mon Sep 17 00:00:00 2001 From: Max Lancaster Date: Wed, 8 Oct 2025 15:11:10 -0400 Subject: [PATCH 08/35] refactor: Fetch logs from buffer to display plugin output in pact tests --- src/PactNet/Drivers/MockServerDriver.cs | 7 ++----- src/PactNet/Interop/NativeInterop.cs | 3 --- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/src/PactNet/Drivers/MockServerDriver.cs b/src/PactNet/Drivers/MockServerDriver.cs index 984fd6d07..f146404d2 100644 --- a/src/PactNet/Drivers/MockServerDriver.cs +++ b/src/PactNet/Drivers/MockServerDriver.cs @@ -53,12 +53,9 @@ public string MockServerMismatches() /// Log string public string MockServerLogs() { - IntPtr logsPtr = NativeInterop.MockServerLogs(this.Port); - - return logsPtr == IntPtr.Zero - ? "ERROR: Unable to retrieve mock server logs" - : Marshal.PtrToStringAnsi(logsPtr); + return NativeInterop.FetchLogBuffer(null); } + /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// diff --git a/src/PactNet/Interop/NativeInterop.cs b/src/PactNet/Interop/NativeInterop.cs index 65ecd790c..803b530a6 100644 --- a/src/PactNet/Interop/NativeInterop.cs +++ b/src/PactNet/Interop/NativeInterop.cs @@ -21,9 +21,6 @@ internal static class NativeInterop [DllImport(DllName, EntryPoint = "pactffi_mock_server_mismatches")] public static extern IntPtr MockServerMismatches(int mockServerPort); - [DllImport(DllName, EntryPoint = "pactffi_mock_server_logs")] - public static extern IntPtr MockServerLogs(int mockServerPort); - [DllImport(DllName, EntryPoint = "pactffi_cleanup_mock_server")] public static extern bool CleanupMockServer(int mockServerPort); From 82387edd48b3e2ec5e998331c28c6944cd756b05 Mon Sep 17 00:00:00 2001 From: Max Lancaster Date: Wed, 8 Oct 2025 15:40:59 -0400 Subject: [PATCH 09/35] refactor: Make AbstractPactBuilder public so it can be extended by plugin libraries --- .../Drivers/ICompletedPactDriver.cs | 2 +- .../Drivers/IMockServerDriver.cs | 2 +- .../ISynchronousPluginPactBuilder.cs | 11 +++++++++++ src/PactNet/AbstractPactBuilder.cs | 15 +++++++++------ src/PactNet/PactBuilder.cs | 2 ++ src/PactNet/SynchronousPluginPactBuilder.cs | 6 ++++++ 6 files changed, 30 insertions(+), 8 deletions(-) rename src/{PactNet => PactNet.Abstractions}/Drivers/ICompletedPactDriver.cs (97%) rename src/{PactNet => PactNet.Abstractions}/Drivers/IMockServerDriver.cs (93%) diff --git a/src/PactNet/Drivers/ICompletedPactDriver.cs b/src/PactNet.Abstractions/Drivers/ICompletedPactDriver.cs similarity index 97% rename from src/PactNet/Drivers/ICompletedPactDriver.cs rename to src/PactNet.Abstractions/Drivers/ICompletedPactDriver.cs index eb102950a..b62db3191 100644 --- a/src/PactNet/Drivers/ICompletedPactDriver.cs +++ b/src/PactNet.Abstractions/Drivers/ICompletedPactDriver.cs @@ -5,7 +5,7 @@ namespace PactNet.Drivers /// /// Driver for writing completed pact files containing interactions /// - internal interface ICompletedPactDriver + public interface ICompletedPactDriver { /// /// Write the pact file to disk diff --git a/src/PactNet/Drivers/IMockServerDriver.cs b/src/PactNet.Abstractions/Drivers/IMockServerDriver.cs similarity index 93% rename from src/PactNet/Drivers/IMockServerDriver.cs rename to src/PactNet.Abstractions/Drivers/IMockServerDriver.cs index 3d93742e5..8d8cadfd1 100644 --- a/src/PactNet/Drivers/IMockServerDriver.cs +++ b/src/PactNet.Abstractions/Drivers/IMockServerDriver.cs @@ -5,7 +5,7 @@ namespace PactNet.Drivers /// /// Driver for managing a HTTP mock server /// - internal interface IMockServerDriver : IDisposable + public interface IMockServerDriver : IDisposable { /// /// Mock server port diff --git a/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs b/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs index 0ac60ae17..6b5a9a5ed 100644 --- a/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs +++ b/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs @@ -1,8 +1,19 @@ using System; +using PactNet.Drivers; namespace PactNet; public interface ISynchronousPluginPactBuilderV4 : IPactBuilder, IDisposable { + /// + /// Add a new interaction to the pact + /// + /// Interaction description + /// Fluent builder ISynchronousPluginRequestBuilderV4 UponReceiving(string description); + + /// + /// Driver for writing completed pact files containing interactions + /// + ICompletedPactDriver CompletedPactDriver { get; } } diff --git a/src/PactNet/AbstractPactBuilder.cs b/src/PactNet/AbstractPactBuilder.cs index 95a666440..45aa3be2b 100644 --- a/src/PactNet/AbstractPactBuilder.cs +++ b/src/PactNet/AbstractPactBuilder.cs @@ -7,12 +7,15 @@ namespace PactNet; -internal abstract class AbstractPactBuilder : IPactBuilder +/// +/// Abstract pact builder that contains shared functionality of different types of pact interactions. +/// +public abstract class AbstractPactBuilder : IPactBuilder { private readonly ICompletedPactDriver pact; - protected readonly PactConfig config; - protected readonly int? port; - protected readonly IPAddress host; + private readonly PactConfig config; + private readonly int? port; + private readonly IPAddress host; private readonly string transport; /// @@ -38,7 +41,7 @@ protected AbstractPactBuilder(ICompletedPactDriver pact, PactConfig config, int? /// /// Action to perform the real interactions against the mock driver /// Failed to verify the interactions - public void Verify(Action interact) + public virtual void Verify(Action interact) { Guard.NotNull(interact, nameof(interact)); @@ -61,7 +64,7 @@ public void Verify(Action interact) /// /// Action to perform the real interactions against the mock driver /// Failed to verify the interactions - public async Task VerifyAsync(Func interact) + public virtual async Task VerifyAsync(Func interact) { Guard.NotNull(interact, nameof(interact)); diff --git a/src/PactNet/PactBuilder.cs b/src/PactNet/PactBuilder.cs index 3e1ac07fc..aea4b1aad 100644 --- a/src/PactNet/PactBuilder.cs +++ b/src/PactNet/PactBuilder.cs @@ -9,6 +9,7 @@ namespace PactNet internal class PactBuilder : AbstractPactBuilder, IPactBuilderV2, IPactBuilderV3, IPactBuilderV4 { private readonly IHttpPactDriver pact; + private readonly PactConfig config; /// /// Initialises a new instance of the class. @@ -21,6 +22,7 @@ internal PactBuilder(IHttpPactDriver pact, PactConfig config, int? port = null, IPAddress host = IPAddress.Loopback) : base(pact, config, port, host, "http") { this.pact = pact; + this.config = config; } /// diff --git a/src/PactNet/SynchronousPluginPactBuilder.cs b/src/PactNet/SynchronousPluginPactBuilder.cs index 084b37bfc..0c3bc031e 100644 --- a/src/PactNet/SynchronousPluginPactBuilder.cs +++ b/src/PactNet/SynchronousPluginPactBuilder.cs @@ -1,3 +1,4 @@ +using PactNet.Drivers; using PactNet.Drivers.Plugins; using PactNet.Models; @@ -16,5 +17,10 @@ public ISynchronousPluginRequestBuilderV4 UponReceiving(string description) return new SynchronousPluginRequestBuilder(pact.NewSyncInteraction(description)); } + /// + /// Driver for writing completed pact files containing interactions + /// + public ICompletedPactDriver CompletedPactDriver { get { return pact; } } + public void Dispose() => pact?.Dispose(); } From be20e84dfb770516a5ed1d272726c269dd728bb3 Mon Sep 17 00:00:00 2001 From: Adam Rodger Date: Thu, 22 Jan 2026 21:07:02 +0000 Subject: [PATCH 10/35] chore: Some style and consistency tidy ups --- .../Grpc/GrpcGreeter.Tests/GrpcGreeterTest.cs | 8 +- .../GrpcGreeter/Services/GreeterService.cs | 6 +- .../GrpcGreeterClientTest.cs | 6 +- .../ISynchronousPluginPactBuilder.cs | 26 ++- .../ISynchronousPluginRequestBuilder.cs | 44 ++-- src/PactNet/AbstractPactBuilder.cs | 207 +++++++++--------- src/PactNet/Drivers/AbstractPactDriver.cs | 4 +- src/PactNet/Drivers/IPactDriver.cs | 14 +- src/PactNet/Drivers/PactDriver.cs | 3 +- .../Drivers/Plugins/PluginPactDriver.cs | 2 +- src/PactNet/Interop/LogLevelExtensions.cs | 59 ++--- src/PactNet/PactBuilder.cs | 7 +- src/PactNet/PactExtensions.cs | 21 +- src/PactNet/SynchronousPluginPactBuilder.cs | 57 +++-- .../SynchronousPluginRequestBuilder.cs | 77 ++++--- 15 files changed, 294 insertions(+), 247 deletions(-) diff --git a/samples/Grpc/GrpcGreeter.Tests/GrpcGreeterTest.cs b/samples/Grpc/GrpcGreeter.Tests/GrpcGreeterTest.cs index 27a6806e5..038aac3b7 100644 --- a/samples/Grpc/GrpcGreeter.Tests/GrpcGreeterTest.cs +++ b/samples/Grpc/GrpcGreeter.Tests/GrpcGreeterTest.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using FluentAssertions; using PactNet; using PactNet.Exceptions; using PactNet.Infrastructure.Outputters; @@ -28,10 +29,11 @@ public class GrpcGreeterTests(ITestOutputHelper output, ServerFixture serverFixt [Fact] public void VerificationThrowsExceptionWhenNoRunningProvider() { - Assert.Throws(() => verifier + var source = this.verifier .WithHttpEndpoint(new Uri("http://localhost:5060")) - .WithFileSource(new FileInfo(pactPath)) - .Verify()); + .WithFileSource(new FileInfo(this.pactPath)); + + source.Invoking(s => s.Verify()).Should().Throw(); } [Fact] diff --git a/samples/Grpc/GrpcGreeter/Services/GreeterService.cs b/samples/Grpc/GrpcGreeter/Services/GreeterService.cs index 590619120..bf7a1d324 100644 --- a/samples/Grpc/GrpcGreeter/Services/GreeterService.cs +++ b/samples/Grpc/GrpcGreeter/Services/GreeterService.cs @@ -1,14 +1,14 @@ using Grpc.Core; -using GrpcGreeter; namespace GrpcGreeter.Services { public class GreeterService : Greeter.GreeterBase { - private readonly ILogger _logger; + private readonly ILogger logger; + public GreeterService(ILogger logger) { - _logger = logger; + this.logger = logger; } public override Task SayHello(HelloRequest request, ServerCallContext context) diff --git a/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClientTest.cs b/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClientTest.cs index 8e3bdf722..7ac50bb7d 100644 --- a/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClientTest.cs +++ b/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClientTest.cs @@ -53,11 +53,7 @@ public void ThrowsExceptionWhenNoGrpcClientRequestMade() this.pact.UponReceiving("A greeting request to say hello.").WithContent("application/grpc", content); - Assert.Throws(() => - this.pact.Verify(_ => - { - // No grpc call here results in failure. - })); + this.pact.Invoking(p => p.Verify(_ => { })).Should().Throw(); } [Fact] diff --git a/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs b/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs index 6b5a9a5ed..1ef4901e3 100644 --- a/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs +++ b/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs @@ -1,19 +1,23 @@ using System; using PactNet.Drivers; -namespace PactNet; - -public interface ISynchronousPluginPactBuilderV4 : IPactBuilder, IDisposable +namespace PactNet { /// - /// Add a new interaction to the pact + /// Synchronous plugin-based pact builder /// - /// Interaction description - /// Fluent builder - ISynchronousPluginRequestBuilderV4 UponReceiving(string description); + public interface ISynchronousPluginPactBuilderV4 : IPactBuilder, IDisposable + { + /// + /// Add a new interaction to the pact + /// + /// Interaction description + /// Fluent builder + ISynchronousPluginRequestBuilderV4 UponReceiving(string description); - /// - /// Driver for writing completed pact files containing interactions - /// - ICompletedPactDriver CompletedPactDriver { get; } + /// + /// Driver for writing completed pact files containing interactions + /// + ICompletedPactDriver CompletedPactDriver { get; } + } } diff --git a/src/PactNet.Abstractions/ISynchronousPluginRequestBuilder.cs b/src/PactNet.Abstractions/ISynchronousPluginRequestBuilder.cs index eefe5b514..3e2e5dff0 100644 --- a/src/PactNet.Abstractions/ISynchronousPluginRequestBuilder.cs +++ b/src/PactNet.Abstractions/ISynchronousPluginRequestBuilder.cs @@ -1,28 +1,32 @@ using System.Collections.Generic; -namespace PactNet; - -public interface ISynchronousPluginRequestBuilderV4 +namespace PactNet { /// - /// Add a provider state + /// Synchronous plugin request builder for V4 pacts /// - /// Provider state description - /// Fluent builder - ISynchronousPluginRequestBuilderV4 Given(string description); + public interface ISynchronousPluginRequestBuilderV4 + { + /// + /// Add a provider state + /// + /// Provider state description + /// Fluent builder + ISynchronousPluginRequestBuilderV4 Given(string description); - /// - /// Add a provider state with a parameter to the interaction - /// - /// Provider state description - /// Parameter name - /// Parameter value - ISynchronousPluginRequestBuilderV4 Given(string description, string name, string value); + /// + /// Add a provider state with a parameter to the interaction + /// + /// Provider state description + /// Parameter name + /// Parameter value + ISynchronousPluginRequestBuilderV4 Given(string description, string name, string value); - /// - /// Add plugin interaction content - /// - /// Content type - /// A dictionary containing the plugin content. - ISynchronousPluginRequestBuilderV4 WithContent(string contentType, Dictionary content); + /// + /// Add plugin interaction content + /// + /// Content type + /// A dictionary containing the plugin content. + ISynchronousPluginRequestBuilderV4 WithContent(string contentType, Dictionary content); + } } diff --git a/src/PactNet/AbstractPactBuilder.cs b/src/PactNet/AbstractPactBuilder.cs index 45aa3be2b..5cea20f93 100644 --- a/src/PactNet/AbstractPactBuilder.cs +++ b/src/PactNet/AbstractPactBuilder.cs @@ -5,132 +5,133 @@ using PactNet.Internal; using PactNet.Models; -namespace PactNet; - -/// -/// Abstract pact builder that contains shared functionality of different types of pact interactions. -/// -public abstract class AbstractPactBuilder : IPactBuilder +namespace PactNet { - private readonly ICompletedPactDriver pact; - private readonly PactConfig config; - private readonly int? port; - private readonly IPAddress host; - private readonly string transport; - /// - /// Initialises a new instance of the class. + /// Abstract pact builder that contains shared functionality of different types of pact interactions. /// - /// Pact driver - /// Pact config - /// Optional port, otherwise one is dynamically allocated - /// Optional host, otherwise loopback is used - /// The transport to use (i.e. http, https, grpc). Must be a valid UTF-8 NULL-terminated string, or NULL or empty, in which case http will be used. - protected AbstractPactBuilder(ICompletedPactDriver pact, PactConfig config, int? port, IPAddress host, - string transport = null) + public abstract class AbstractPactBuilder : IPactBuilder { - this.pact = pact; - this.config = config; - this.port = port; - this.host = host; - this.transport = transport; - } + private readonly ICompletedPactDriver pact; + private readonly PactConfig config; + private readonly int? port; + private readonly IPAddress host; + private readonly string transport; + + /// + /// Initialises a new instance of the class. + /// + /// Pact driver + /// Pact config + /// Optional port, otherwise one is dynamically allocated + /// Optional host, otherwise loopback is used + /// The transport to use (i.e. http, https, grpc). Must be a valid UTF-8 NULL-terminated string, or NULL or empty, in which case http will be used. + protected AbstractPactBuilder(ICompletedPactDriver pact, PactConfig config, int? port, IPAddress host, + string transport = null) + { + this.pact = pact; + this.config = config; + this.port = port; + this.host = host; + this.transport = transport; + } - /// - /// Verify the configured interactions - /// - /// Action to perform the real interactions against the mock driver - /// Failed to verify the interactions - public virtual void Verify(Action interact) - { - Guard.NotNull(interact, nameof(interact)); + /// + /// Verify the configured interactions + /// + /// Action to perform the real interactions against the mock driver + /// Failed to verify the interactions + public virtual void Verify(Action interact) + { + Guard.NotNull(interact, nameof(interact)); - using IMockServerDriver mockServer = this.StartMockServer(); + using IMockServerDriver mockServer = this.StartMockServer(); - try - { - interact(new ConsumerContext { MockServerUri = mockServer.Uri }); + try + { + interact(new ConsumerContext { MockServerUri = mockServer.Uri }); - this.VerifyInternal(mockServer); - } - finally - { - this.PrintLogs(mockServer); + this.VerifyInternal(mockServer); + } + finally + { + this.PrintLogs(mockServer); + } } - } - /// - /// Verify the configured interactions - /// - /// Action to perform the real interactions against the mock driver - /// Failed to verify the interactions - public virtual async Task VerifyAsync(Func interact) - { - Guard.NotNull(interact, nameof(interact)); + /// + /// Verify the configured interactions + /// + /// Action to perform the real interactions against the mock driver + /// Failed to verify the interactions + public virtual async Task VerifyAsync(Func interact) + { + Guard.NotNull(interact, nameof(interact)); - using IMockServerDriver mockServer = this.StartMockServer(); + using IMockServerDriver mockServer = this.StartMockServer(); - try - { - await interact(new ConsumerContext { MockServerUri = mockServer.Uri }); + try + { + await interact(new ConsumerContext { MockServerUri = mockServer.Uri }); - this.VerifyInternal(mockServer); + this.VerifyInternal(mockServer); + } + finally + { + this.PrintLogs(mockServer); + } } - finally + + /// + /// Start the mock driver + /// + /// Mock driver + private IMockServerDriver StartMockServer() { - this.PrintLogs(mockServer); + string hostIp = this.host switch + { + IPAddress.Loopback => "127.0.0.1", + IPAddress.Any => "0.0.0.0", + _ => throw new ArgumentOutOfRangeException(nameof(this.host), this.host, "Unsupported IPAddress value") + }; + + // TODO: add TLS support + return this.pact.CreateMockServer(hostIp, this.port, false, transport); } - } - /// - /// Start the mock driver - /// - /// Mock driver - private IMockServerDriver StartMockServer() - { - string hostIp = this.host switch + /// + /// Verify the interactions after the consumer client has been invoked + /// + /// Mock server + private void VerifyInternal(IMockServerDriver mockServer) { - IPAddress.Loopback => "127.0.0.1", - IPAddress.Any => "0.0.0.0", - _ => throw new ArgumentOutOfRangeException(nameof(this.host), this.host, "Unsupported IPAddress value") - }; + string errors = mockServer.MockServerMismatches(); - // TODO: add TLS support - return this.pact.CreateMockServer(hostIp, this.port, false, transport); - } + if (string.IsNullOrWhiteSpace(errors) || errors == "[]") + { + this.pact.WritePactFile(mockServer.Port, this.config.PactDir); + return; + } - /// - /// Verify the interactions after the consumer client has been invoked - /// - /// Mock server - private void VerifyInternal(IMockServerDriver mockServer) - { - string errors = mockServer.MockServerMismatches(); + this.config.WriteLine(string.Empty); + this.config.WriteLine("Verification mismatches:"); + this.config.WriteLine(string.Empty); + this.config.WriteLine(errors); - if (string.IsNullOrWhiteSpace(errors) || errors == "[]") - { - this.pact.WritePactFile(mockServer.Port, this.config.PactDir); - return; + throw new PactFailureException("Pact verification failed. See output for details"); } - this.config.WriteLine(string.Empty); - this.config.WriteLine("Verification mismatches:"); - this.config.WriteLine(string.Empty); - this.config.WriteLine(errors); - - throw new PactFailureException("Pact verification failed. See output for details"); - } - - /// - /// Print logs to the configured outputs - /// - /// Mock server - private void PrintLogs(IMockServerDriver mockServer) - { - string logs = mockServer.MockServerLogs(); + /// + /// Print logs to the configured outputs + /// + /// Mock server + private void PrintLogs(IMockServerDriver mockServer) + { + string logs = mockServer.MockServerLogs(); - this.config.WriteLine("Mock driver logs:"); - this.config.WriteLine(string.Empty); - this.config.WriteLine(logs); + this.config.WriteLine("Mock driver logs:"); + this.config.WriteLine(string.Empty); + this.config.WriteLine(logs); + } } } diff --git a/src/PactNet/Drivers/AbstractPactDriver.cs b/src/PactNet/Drivers/AbstractPactDriver.cs index 060d81778..36d1124b5 100644 --- a/src/PactNet/Drivers/AbstractPactDriver.cs +++ b/src/PactNet/Drivers/AbstractPactDriver.cs @@ -27,7 +27,7 @@ protected AbstractPactDriver(PactHandle pact) /// Failed to write pact file public void WritePactFile(string directory) { - var result = NativeInterop.WritePactFile(this.pact, directory, false); + int result = NativeInterop.WritePactFile(this.pact, directory, false); ThrowExceptionOnWritePactFileFailure(result); } @@ -38,7 +38,7 @@ public void WritePactFile(string directory) /// Directory of the pact file public void WritePactFile(int port, string directory) { - var result = NativeInterop.WritePactFileForPort(port, directory, false); + int result = NativeInterop.WritePactFileForPort(port, directory, false); ThrowExceptionOnWritePactFileFailure(result); } diff --git a/src/PactNet/Drivers/IPactDriver.cs b/src/PactNet/Drivers/IPactDriver.cs index a3eaa1f7d..a5ce11483 100644 --- a/src/PactNet/Drivers/IPactDriver.cs +++ b/src/PactNet/Drivers/IPactDriver.cs @@ -25,15 +25,9 @@ internal interface IPactDriver /// Consumer name /// Provider name /// Specification version - /// Message pact driver driver + /// Message pact driver IMessagePactDriver NewMessagePact(string consumerName, string providerName, PactSpecification version); - /// - /// Get the driver logs - /// - /// Logs - string DriverLogs(); - /// /// Create a new plugin pact /// @@ -44,5 +38,11 @@ internal interface IPactDriver /// Specification version /// Plugin pact driver IPluginPactDriver NewPluginPact(string consumerName, string providerName, string pluginName, string pluginVersion, PactSpecification version); + + /// + /// Get the driver logs + /// + /// Logs + string DriverLogs(); } } diff --git a/src/PactNet/Drivers/PactDriver.cs b/src/PactNet/Drivers/PactDriver.cs index 8cb8624cf..c65e54670 100644 --- a/src/PactNet/Drivers/PactDriver.cs +++ b/src/PactNet/Drivers/PactDriver.cs @@ -48,8 +48,7 @@ public IMessagePactDriver NewMessagePact(string consumerName, string providerNam /// Plugin pact driver public IPluginPactDriver NewPluginPact(string consumerName, string providerName, string pluginName, string pluginVersion, PactSpecification version) { - PactHandle pact = NativeInterop.NewPact(consumerName, providerName); - NativeInterop.WithSpecification(pact, version).CheckInteropSuccess(); + PactHandle pact = CreatePactHandle(consumerName, providerName, version); uint code = NativeInterop.UsingPlugin(pact, pluginName, pluginVersion); diff --git a/src/PactNet/Drivers/Plugins/PluginPactDriver.cs b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs index 45c28f1f4..e0e5da9aa 100644 --- a/src/PactNet/Drivers/Plugins/PluginPactDriver.cs +++ b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs @@ -6,7 +6,7 @@ namespace PactNet.Drivers.Plugins /// /// Driver for plugin-based pacts /// - internal class PluginPactDriver : AbstractPactDriver, IPluginPactDriver, IDisposable + internal class PluginPactDriver : AbstractPactDriver, IPluginPactDriver { /// /// Initialize a new instance of the class. diff --git a/src/PactNet/Interop/LogLevelExtensions.cs b/src/PactNet/Interop/LogLevelExtensions.cs index acc77f38d..57c18079b 100644 --- a/src/PactNet/Interop/LogLevelExtensions.cs +++ b/src/PactNet/Interop/LogLevelExtensions.cs @@ -1,42 +1,43 @@ using System; -namespace PactNet.Interop; - -/// -/// PactLogLevel extension methods -/// -internal static class LogLevelExtensions +namespace PactNet.Interop { - private static readonly object LogLocker = new object(); - private static bool LogInitialised = false; - /// - /// Direct all logging in the native library to a task local memory buffer. + /// PactLogLevel extension methods /// - /// Log level - /// Invalid log level - /// Logging can only be initialised **once**. Subsequent calls will have no effect - public static void LogToBuffer(this PactLogLevel level) + internal static class LogLevelExtensions { - lock (LogLocker) + private static readonly object LogLocker = new object(); + private static bool LogInitialised = false; + + /// + /// Direct all logging in the native library to a task local memory buffer. + /// + /// Log level + /// Invalid log level + /// Logging can only be initialised **once**. Subsequent calls will have no effect + public static void LogToBuffer(this PactLogLevel level) { - if (LogInitialised) + lock (LogLocker) { - return; - } + if (LogInitialised) + { + return; + } - NativeInterop.LogToBuffer(level switch - { - PactLogLevel.Trace => LevelFilter.Trace, - PactLogLevel.Debug => LevelFilter.Debug, - PactLogLevel.Information => LevelFilter.Info, - PactLogLevel.Warn => LevelFilter.Warn, - PactLogLevel.Error => LevelFilter.Error, - PactLogLevel.None => LevelFilter.Off, - _ => throw new ArgumentOutOfRangeException(nameof(level), level, "Invalid log level") - }); + NativeInterop.LogToBuffer(level switch + { + PactLogLevel.Trace => LevelFilter.Trace, + PactLogLevel.Debug => LevelFilter.Debug, + PactLogLevel.Information => LevelFilter.Info, + PactLogLevel.Warn => LevelFilter.Warn, + PactLogLevel.Error => LevelFilter.Error, + PactLogLevel.None => LevelFilter.Off, + _ => throw new ArgumentOutOfRangeException(nameof(level), level, "Invalid log level") + }); - LogInitialised = true; + LogInitialised = true; + } } } } diff --git a/src/PactNet/PactBuilder.cs b/src/PactNet/PactBuilder.cs index aea4b1aad..e0eb138a7 100644 --- a/src/PactNet/PactBuilder.cs +++ b/src/PactNet/PactBuilder.cs @@ -18,8 +18,11 @@ internal class PactBuilder : AbstractPactBuilder, IPactBuilderV2, IPactBuilderV3 /// Pact config /// Optional port, otherwise one is dynamically allocated /// Optional host, otherwise loopback is used - internal PactBuilder(IHttpPactDriver pact, PactConfig config, int? port = null, - IPAddress host = IPAddress.Loopback) : base(pact, config, port, host, "http") + internal PactBuilder(IHttpPactDriver pact, + PactConfig config, + int? port = null, + IPAddress host = IPAddress.Loopback) + : base(pact, config, port, host, "http") { this.pact = pact; this.config = config; diff --git a/src/PactNet/PactExtensions.cs b/src/PactNet/PactExtensions.cs index b1432baf0..24f7575d4 100644 --- a/src/PactNet/PactExtensions.cs +++ b/src/PactNet/PactExtensions.cs @@ -24,8 +24,7 @@ public static class PactExtensions /// It is advised that the port is not specified whenever possible to allow PactNet to allocate a port dynamically /// and ensure there are no port clashes /// - public static IPactBuilderV2 WithHttpInteractions(this IPactV2 pact, int? port = null, - IPAddress host = IPAddress.Loopback) + public static IPactBuilderV2 WithHttpInteractions(this IPactV2 pact, int? port = null, IPAddress host = IPAddress.Loopback) { pact.Config.LogLevel.LogToBuffer(); @@ -48,8 +47,7 @@ public static IPactBuilderV2 WithHttpInteractions(this IPactV2 pact, int? port = /// It is advised that the port is not specified whenever possible to allow PactNet to allocate a port dynamically /// and ensure there are no port clashes /// - public static IPactBuilderV3 WithHttpInteractions(this IPactV3 pact, int? port = null, - IPAddress host = IPAddress.Loopback) + public static IPactBuilderV3 WithHttpInteractions(this IPactV3 pact, int? port = null, IPAddress host = IPAddress.Loopback) { pact.Config.LogLevel.LogToBuffer(); @@ -72,8 +70,7 @@ public static IPactBuilderV3 WithHttpInteractions(this IPactV3 pact, int? port = /// It is advised that the port is not specified whenever possible to allow PactNet to allocate a port dynamically /// and ensure there are no port clashes /// - public static IPactBuilderV4 WithHttpInteractions(this IPactV4 pact, int? port = null, - IPAddress host = IPAddress.Loopback) + public static IPactBuilderV4 WithHttpInteractions(this IPactV4 pact, int? port = null, IPAddress host = IPAddress.Loopback) { pact.Config.LogLevel.LogToBuffer(); @@ -125,15 +122,19 @@ public static IMessagePactBuilderV4 WithMessageInteractions(this IPactV4 pact) /// The transport to use (i.e. http, https, grpc). Must be a valid UTF-8 NULL-terminated string, or NULL or empty, in which case http will be used. /// Port for the mock server. If null, one will be assigned automatically /// Host for the mock server - /// + /// Synchronous plugin builder public static ISynchronousPluginPactBuilderV4 WithSynchronousPluginInteractions(this IPactV4 pact, - string pluginName, string pluginVersion, string transport = null, int? port = null, + string pluginName, + string pluginVersion, + string transport = null, + int? port = null, IPAddress host = IPAddress.Loopback) { pact.Config.LogLevel.LogToBuffer(); + IPactDriver driver = new PactDriver(); - var pluginDriver = driver.NewPluginPact(pact.Consumer, pact.Provider, pluginName, pluginVersion, - PactSpecification.V4); + IPluginPactDriver pluginDriver = driver.NewPluginPact(pact.Consumer, pact.Provider, pluginName, pluginVersion, PactSpecification.V4); + return new SynchronousPluginPactBuilder(pluginDriver, pact.Config, port, host, transport); } } diff --git a/src/PactNet/SynchronousPluginPactBuilder.cs b/src/PactNet/SynchronousPluginPactBuilder.cs index 0c3bc031e..30f74a191 100644 --- a/src/PactNet/SynchronousPluginPactBuilder.cs +++ b/src/PactNet/SynchronousPluginPactBuilder.cs @@ -2,25 +2,48 @@ using PactNet.Drivers.Plugins; using PactNet.Models; -namespace PactNet; - -internal class SynchronousPluginPactBuilder( - IPluginPactDriver pact, - PactConfig config, - int? port, - IPAddress host, - string transport = null) - : AbstractPactBuilder(pact, config, port, host, transport), ISynchronousPluginPactBuilderV4 +namespace PactNet { - public ISynchronousPluginRequestBuilderV4 UponReceiving(string description) - { - return new SynchronousPluginRequestBuilder(pact.NewSyncInteraction(description)); - } - /// - /// Driver for writing completed pact files containing interactions + /// Synchronous plugin pact builder /// - public ICompletedPactDriver CompletedPactDriver { get { return pact; } } + internal class SynchronousPluginPactBuilder : AbstractPactBuilder, ISynchronousPluginPactBuilderV4 + { + private readonly IPluginPactDriver pact; - public void Dispose() => pact?.Dispose(); + /// + /// Intialises a new instance of the class. + /// + /// Pact handle + /// Pact configuration + /// Mock server port + /// Mock server host + /// Plugin transport + public SynchronousPluginPactBuilder(IPluginPactDriver pact, + PactConfig config, + int? port, + IPAddress host, + string transport = null) + : base(pact, config, port, host, transport) + { + this.pact = pact; + } + + /// + /// Add a new interaction to the pact + /// + /// Interaction description + /// Fluent builder + public ISynchronousPluginRequestBuilderV4 UponReceiving(string description) + { + return new SynchronousPluginRequestBuilder(this.pact.NewSyncInteraction(description)); + } + + /// + /// Driver for writing completed pact files containing interactions + /// + public ICompletedPactDriver CompletedPactDriver => this.pact; + + public void Dispose() => this.pact?.Dispose(); + } } diff --git a/src/PactNet/SynchronousPluginRequestBuilder.cs b/src/PactNet/SynchronousPluginRequestBuilder.cs index d3da9c41f..3ec7ef9b8 100644 --- a/src/PactNet/SynchronousPluginRequestBuilder.cs +++ b/src/PactNet/SynchronousPluginRequestBuilder.cs @@ -1,43 +1,56 @@ using System.Collections.Generic; using PactNet.Drivers.Plugins; -namespace PactNet; - -internal class SynchronousPluginRequestBuilder(IPluginInteractionDriver interactionDriver) - : ISynchronousPluginRequestBuilderV4 +namespace PactNet { - /// - /// Add a provider state + /// Synchronous plugin request builder /// - /// Provider state description - /// Fluent builder - public ISynchronousPluginRequestBuilderV4 Given(string description) + internal class SynchronousPluginRequestBuilder : ISynchronousPluginRequestBuilderV4 { - interactionDriver.Given(description); - return this; - } + private readonly IPluginInteractionDriver interactionDriver; - /// - /// Add a provider state with a parameter to the interaction - /// - /// Provider state description - /// Parameter name - /// Parameter value - public ISynchronousPluginRequestBuilderV4 Given(string description, string name, string value) - { - interactionDriver.GivenWithParam(description, name, value); - return this; - } + /// + /// Initialises a new instance of the class. + /// + /// Interaction driver + public SynchronousPluginRequestBuilder(IPluginInteractionDriver interactionDriver) + { + this.interactionDriver = interactionDriver; + } - /// - /// Add plugin interaction content - /// - /// Content type - /// A dictionary containing the plugin content. - public ISynchronousPluginRequestBuilderV4 WithContent(string contentType, Dictionary content) - { - interactionDriver.WithContent(contentType, content); - return this; + /// + /// Add a provider state + /// + /// Provider state description + /// Fluent builder + public ISynchronousPluginRequestBuilderV4 Given(string description) + { + this.interactionDriver.Given(description); + return this; + } + + /// + /// Add a provider state with a parameter to the interaction + /// + /// Provider state description + /// Parameter name + /// Parameter value + public ISynchronousPluginRequestBuilderV4 Given(string description, string name, string value) + { + this.interactionDriver.GivenWithParam(description, name, value); + return this; + } + + /// + /// Add plugin interaction content + /// + /// Content type + /// A dictionary containing the plugin content. + public ISynchronousPluginRequestBuilderV4 WithContent(string contentType, Dictionary content) + { + this.interactionDriver.WithContent(contentType, content); + return this; + } } } From 275da9f0b7cf1e73d4312dbb003c2df964cae471 Mon Sep 17 00:00:00 2001 From: Max Lancaster Date: Mon, 26 Jan 2026 17:44:51 -0500 Subject: [PATCH 11/35] refactor: Make AbstractPactBuilder internal again --- src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs | 6 ------ src/PactNet/AbstractPactBuilder.cs | 2 +- .../Drivers/ICompletedPactDriver.cs | 2 +- .../Drivers/IMockServerDriver.cs | 2 +- src/PactNet/SynchronousPluginPactBuilder.cs | 6 ------ 5 files changed, 3 insertions(+), 15 deletions(-) rename src/{PactNet.Abstractions => PactNet}/Drivers/ICompletedPactDriver.cs (97%) rename src/{PactNet.Abstractions => PactNet}/Drivers/IMockServerDriver.cs (93%) diff --git a/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs b/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs index 1ef4901e3..cb13585e8 100644 --- a/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs +++ b/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs @@ -1,5 +1,4 @@ using System; -using PactNet.Drivers; namespace PactNet { @@ -14,10 +13,5 @@ public interface ISynchronousPluginPactBuilderV4 : IPactBuilder, IDisposable /// Interaction description /// Fluent builder ISynchronousPluginRequestBuilderV4 UponReceiving(string description); - - /// - /// Driver for writing completed pact files containing interactions - /// - ICompletedPactDriver CompletedPactDriver { get; } } } diff --git a/src/PactNet/AbstractPactBuilder.cs b/src/PactNet/AbstractPactBuilder.cs index 5cea20f93..6b2cdca00 100644 --- a/src/PactNet/AbstractPactBuilder.cs +++ b/src/PactNet/AbstractPactBuilder.cs @@ -10,7 +10,7 @@ namespace PactNet /// /// Abstract pact builder that contains shared functionality of different types of pact interactions. /// - public abstract class AbstractPactBuilder : IPactBuilder + internal abstract class AbstractPactBuilder : IPactBuilder { private readonly ICompletedPactDriver pact; private readonly PactConfig config; diff --git a/src/PactNet.Abstractions/Drivers/ICompletedPactDriver.cs b/src/PactNet/Drivers/ICompletedPactDriver.cs similarity index 97% rename from src/PactNet.Abstractions/Drivers/ICompletedPactDriver.cs rename to src/PactNet/Drivers/ICompletedPactDriver.cs index b62db3191..eb102950a 100644 --- a/src/PactNet.Abstractions/Drivers/ICompletedPactDriver.cs +++ b/src/PactNet/Drivers/ICompletedPactDriver.cs @@ -5,7 +5,7 @@ namespace PactNet.Drivers /// /// Driver for writing completed pact files containing interactions /// - public interface ICompletedPactDriver + internal interface ICompletedPactDriver { /// /// Write the pact file to disk diff --git a/src/PactNet.Abstractions/Drivers/IMockServerDriver.cs b/src/PactNet/Drivers/IMockServerDriver.cs similarity index 93% rename from src/PactNet.Abstractions/Drivers/IMockServerDriver.cs rename to src/PactNet/Drivers/IMockServerDriver.cs index 8d8cadfd1..3d93742e5 100644 --- a/src/PactNet.Abstractions/Drivers/IMockServerDriver.cs +++ b/src/PactNet/Drivers/IMockServerDriver.cs @@ -5,7 +5,7 @@ namespace PactNet.Drivers /// /// Driver for managing a HTTP mock server /// - public interface IMockServerDriver : IDisposable + internal interface IMockServerDriver : IDisposable { /// /// Mock server port diff --git a/src/PactNet/SynchronousPluginPactBuilder.cs b/src/PactNet/SynchronousPluginPactBuilder.cs index 30f74a191..438020650 100644 --- a/src/PactNet/SynchronousPluginPactBuilder.cs +++ b/src/PactNet/SynchronousPluginPactBuilder.cs @@ -1,4 +1,3 @@ -using PactNet.Drivers; using PactNet.Drivers.Plugins; using PactNet.Models; @@ -39,11 +38,6 @@ public ISynchronousPluginRequestBuilderV4 UponReceiving(string description) return new SynchronousPluginRequestBuilder(this.pact.NewSyncInteraction(description)); } - /// - /// Driver for writing completed pact files containing interactions - /// - public ICompletedPactDriver CompletedPactDriver => this.pact; - public void Dispose() => this.pact?.Dispose(); } } From 8b6d35e46998aa3b4b583968942d22f258ce8217 Mon Sep 17 00:00:00 2001 From: Max Lancaster Date: Mon, 14 Sep 2026 11:51:37 -0400 Subject: [PATCH 12/35] refactor: Make WithContent the terminal call on the plugin request builder Setting the plugin contents completes a synchronous plugin interaction, so WithContent now returns void instead of the same builder. The plugin splits one contents document into the request and its responses itself: a second call would replace the request but append another response, which is why the builder no longer allows it. Provider states stay chainable via Given. Adds unit tests for the plugin request and pact builders and a docs page for the raw plugin API, linked from the README. Co-Authored-By: Claude Fable 5.1 --- README.md | 6 + docs/plugin-interactions.md | 127 ++++++++++++++++++ .../ISynchronousPluginRequestBuilder.cs | 11 +- .../SynchronousPluginRequestBuilder.cs | 7 +- .../SynchronousPluginPactBuilderTests.cs | 102 ++++++++++++++ .../SynchronousPluginRequestBuilderTests.cs | 71 ++++++++++ 6 files changed, 317 insertions(+), 7 deletions(-) create mode 100644 docs/plugin-interactions.md create mode 100644 tests/PactNet.Tests/SynchronousPluginPactBuilderTests.cs create mode 100644 tests/PactNet.Tests/SynchronousPluginRequestBuilderTests.cs diff --git a/README.md b/README.md index c70c541bb..edf9deb12 100644 --- a/README.md +++ b/README.md @@ -226,6 +226,12 @@ For writing messaging pacts instead of requests/response pacts, see the [messagi ![----------](https://raw.githubusercontent.com/pactumjs/pactum/master/assets/rainbow.png) +### Plugin Interactions + +For protocols handled by a Pact plugin, such as gRPC, see the [plugin interactions guide](docs/plugin-interactions.md). + +![----------](https://raw.githubusercontent.com/pactumjs/pactum/master/assets/rainbow.png) + ## Compatibility ### Operating System diff --git a/docs/plugin-interactions.md b/docs/plugin-interactions.md new file mode 100644 index 000000000..269b41105 --- /dev/null +++ b/docs/plugin-interactions.md @@ -0,0 +1,127 @@ +Plugin Interactions +=================== + +Pact [plugins](https://docs.pact.io/plugins) extend Pact to protocols and content types beyond HTTP and +plain messaging, for example gRPC/protobuf or CSV. PactNet exposes a "raw" plugin API which works with any +plugin, so that a new plugin can be used before a friendlier wrapper library exists for it. + +Currently only **synchronous** plugin interactions are supported: a single request with one or more +responses, such as a gRPC unary call. Asynchronous (message-style) plugin interactions are not yet exposed. + +Prerequisites +------------- + +The plugin itself must be installed on the machine running the tests, on both the consumer and provider side. +Plugins live under `~/.pact/plugins/-` and are installed with the +[plugin CLI](https://docs.pact.io/implementation_guides/pact_plugins/cli), for example: + +```shell +pact-plugin-cli install https://github.com/pact-foundation/pact-protobuf-plugin/releases/tag/v-0.4.0 +``` + +Sample +------ + +See the [gRPC sample](../samples/Grpc/) for a working consumer and provider using the protobuf plugin. + +Consumer Tests +-------------- + +A plugin pact is created from a V4 pact by naming the plugin, its version and the transport the mock +server should use. Each interaction is then defined by handing the plugin a content type it understands +plus a dictionary describing the interaction. The plugin, not PactNet, decides what that dictionary must +contain and how it is split into a request and its responses. + +```csharp +public class GreeterClientTests : IDisposable +{ + private readonly ISynchronousPluginPactBuilderV4 pact; + + public GreeterClientTests(ITestOutputHelper output) + { + IPactV4 v4 = Pact.V4("Greeter Client", "Greeter Service", new PactConfig + { + PactDir = "../../../pacts/", + Outputters = new[] { new XunitOutput(output) } + }); + + this.pact = v4.WithSynchronousPluginInteractions("protobuf", "0.4.0", transport: "grpc"); + } + + [Fact] + public async Task SayHello_ReturnsGreeting() + { + var content = new Dictionary + { + ["pact:proto"] = Path.GetFullPath("../../../Protos/greet.proto"), + ["pact:proto-service"] = "Greeter/SayHello", + ["pact:content-type"] = "application/protobuf", + ["request"] = new { name = "matching(equalTo, 'foo')" }, + ["response"] = new { message = "matching(equalTo, 'Hello foo')" } + }; + + this.pact + .UponReceiving("a request to say hello") + .Given("the greeter is available") + .WithContent("application/grpc", content); + + await this.pact.VerifyAsync(async ctx => + { + var client = new GreeterClient(ctx.MockServerUri); + + string greeting = await client.SayHello("foo"); + + greeting.Should().Be("Hello foo"); + }); + } + + public void Dispose() => this.pact.Dispose(); +} +``` + +`Verify`/`VerifyAsync` starts a mock server using the requested transport, runs your client against it, checks +every interaction was matched, writes the pact file and prints the mock server logs, exactly as for HTTP pacts. +Dispose the builder when the test finishes so the underlying plugin resources are released. + +### Building an interaction + +Each call to `UponReceiving` starts a new interaction and a pact may contain as many as you need. The builder +has two kinds of call: + +- `Given(...)` adds provider states and may be repeated. +- `WithContent(contentType, content)` sets the plugin contents. **It completes the interaction and must be the + last call.** It returns nothing, so it cannot be chained further. + +`WithContent` is deliberately single-shot. The plugin splits one contents dictionary into the request and its +responses. If contents were set a second time on the same interaction the request would be replaced but the +response would be appended, leaving the interaction with two responses, so PactNet does not allow it. Define a +second `UponReceiving` instead. + +### Multiple interactions on one method + +The gRPC mock server tracks whether each service method was called, not each interaction. If two interactions +target the same `Service/Method` and your client only exercises one of them, verification still passes. Give +interactions on the same method distinguishable requests and make sure your test calls each of them. + +Provider Tests +-------------- + +Provider verification uses the normal `PactVerifier`. Point it at the running gRPC server as the HTTP endpoint; +the transport recorded in the pact file tells the verifier to hand the interaction to the plugin. + +```csharp +this.verifier + .WithHttpEndpoint(new Uri("http://localhost:5000")) + .WithFileSource(new FileInfo(pactPath)) + .Verify(); +``` + +Writing a plugin wrapper +------------------------ + +A wrapper library gives a plugin a protocol-specific fluent API on top of the raw builders, without needing +any access to PactNet internals. Wrap `ISynchronousPluginPactBuilderV4`, have your own request/response builders +assemble the contents dictionary, and call `WithContent` once when the user has finished describing the +interaction. Delegate `Verify`, `VerifyAsync` and `Dispose` straight through. The +[`PactNet.Extensions.Grpc`](https://github.com/pact-foundation/pact-net/pull/548) package is the reference +implementation of this pattern. diff --git a/src/PactNet.Abstractions/ISynchronousPluginRequestBuilder.cs b/src/PactNet.Abstractions/ISynchronousPluginRequestBuilder.cs index 3e2e5dff0..ef2c40fdc 100644 --- a/src/PactNet.Abstractions/ISynchronousPluginRequestBuilder.cs +++ b/src/PactNet.Abstractions/ISynchronousPluginRequestBuilder.cs @@ -23,10 +23,15 @@ public interface ISynchronousPluginRequestBuilderV4 ISynchronousPluginRequestBuilderV4 Given(string description, string name, string value); /// - /// Add plugin interaction content + /// Set the plugin interaction contents. This completes the interaction and must be the last call. /// - /// Content type + /// + /// The plugin interprets the contents and splits them into the request and response(s) itself, so + /// this is called exactly once per interaction. Setting the contents again would replace the request + /// but append a further response, which is why the builder does not allow a second call. + /// + /// Content type understood by the plugin, e.g. application/grpc /// A dictionary containing the plugin content. - ISynchronousPluginRequestBuilderV4 WithContent(string contentType, Dictionary content); + void WithContent(string contentType, Dictionary content); } } diff --git a/src/PactNet/SynchronousPluginRequestBuilder.cs b/src/PactNet/SynchronousPluginRequestBuilder.cs index 3ec7ef9b8..7bf567f7f 100644 --- a/src/PactNet/SynchronousPluginRequestBuilder.cs +++ b/src/PactNet/SynchronousPluginRequestBuilder.cs @@ -43,14 +43,13 @@ public ISynchronousPluginRequestBuilderV4 Given(string description, string name, } /// - /// Add plugin interaction content + /// Set the plugin interaction contents. This completes the interaction and must be the last call. /// - /// Content type + /// Content type understood by the plugin /// A dictionary containing the plugin content. - public ISynchronousPluginRequestBuilderV4 WithContent(string contentType, Dictionary content) + public void WithContent(string contentType, Dictionary content) { this.interactionDriver.WithContent(contentType, content); - return this; } } } diff --git a/tests/PactNet.Tests/SynchronousPluginPactBuilderTests.cs b/tests/PactNet.Tests/SynchronousPluginPactBuilderTests.cs new file mode 100644 index 000000000..0c6438681 --- /dev/null +++ b/tests/PactNet.Tests/SynchronousPluginPactBuilderTests.cs @@ -0,0 +1,102 @@ +using System; +using FluentAssertions; +using Moq; +using PactNet.Drivers; +using PactNet.Drivers.Plugins; +using PactNet.Infrastructure.Outputters; +using PactNet.Models; +using Xunit; + +namespace PactNet.Tests +{ + public class SynchronousPluginPactBuilderTests + { + private const int MockServerPort = 5000; + private readonly SynchronousPluginPactBuilder builder; + + private readonly Mock mockDriver; + private readonly Mock mockInteractions; + private readonly Mock mockServer; + private readonly Mock mockOutput; + + private readonly PactConfig config; + + public SynchronousPluginPactBuilderTests() + { + this.mockDriver = new Mock(MockBehavior.Strict); + this.mockInteractions = new Mock(MockBehavior.Strict); + this.mockServer = new Mock(MockBehavior.Strict); + this.mockServer.Setup(s => s.Port).Returns(MockServerPort); + this.mockOutput = new Mock(); + + this.config = new PactConfig + { + Outputters = new[] { this.mockOutput.Object } + }; + + this.mockDriver.Setup(s => s.CreateMockServer("127.0.0.1", null, false, "grpc")).Returns(this.mockServer.Object); + this.mockDriver.Setup(s => s.NewSyncInteraction(It.IsAny())).Returns(this.mockInteractions.Object); + this.mockDriver.Setup(s => s.WritePactFile(MockServerPort, this.config.PactDir)); + this.mockDriver.Setup(s => s.Dispose()); + + this.mockServer.Setup(s => s.Uri).Returns(new Uri("http://127.0.0.1:5000")); + this.mockServer.Setup(s => s.MockServerLogs()).Returns(string.Empty); + this.mockServer.Setup(s => s.MockServerMismatches()).Returns(string.Empty); + this.mockServer.Setup(s => s.Dispose()); + + this.builder = new SynchronousPluginPactBuilder(this.mockDriver.Object, this.config, null, IPAddress.Loopback, "grpc"); + } + + [Fact] + public void UponReceiving_WhenCalled_CreatesNewSyncInteraction() + { + this.builder.UponReceiving("a plugin interaction"); + + this.mockDriver.Verify(d => d.NewSyncInteraction("a plugin interaction")); + } + + [Fact] + public void UponReceiving_CalledTwice_CreatesTwoInteractions() + { + this.builder.UponReceiving("first interaction"); + this.builder.UponReceiving("second interaction"); + + this.mockDriver.Verify(d => d.NewSyncInteraction("first interaction"), Times.Once); + this.mockDriver.Verify(d => d.NewSyncInteraction("second interaction"), Times.Once); + } + + [Fact] + public void Verify_WhenCalled_StartsMockServerWithPluginTransport() + { + this.builder.Verify(_ => { }); + + this.mockDriver.Verify(d => d.CreateMockServer("127.0.0.1", null, false, "grpc")); + } + + [Fact] + public void Verify_NoMismatches_WritesPactFile() + { + this.builder.Verify(_ => { }); + + this.mockDriver.Verify(d => d.WritePactFile(MockServerPort, this.config.PactDir)); + } + + [Fact] + public void Verify_WhenCalled_PassesMockServerUriToConsumer() + { + Uri actual = null; + + this.builder.Verify(ctx => actual = ctx.MockServerUri); + + actual.Should().Be(new Uri("http://127.0.0.1:5000")); + } + + [Fact] + public void Dispose_WhenCalled_DisposesPact() + { + this.builder.Dispose(); + + this.mockDriver.Verify(d => d.Dispose()); + } + } +} diff --git a/tests/PactNet.Tests/SynchronousPluginRequestBuilderTests.cs b/tests/PactNet.Tests/SynchronousPluginRequestBuilderTests.cs new file mode 100644 index 000000000..0915c6796 --- /dev/null +++ b/tests/PactNet.Tests/SynchronousPluginRequestBuilderTests.cs @@ -0,0 +1,71 @@ +using System.Collections.Generic; +using FluentAssertions; +using Moq; +using PactNet.Drivers.Plugins; +using Xunit; + +namespace PactNet.Tests +{ + public class SynchronousPluginRequestBuilderTests + { + private readonly ISynchronousPluginRequestBuilderV4 builder; + + private readonly Mock mockDriver; + + public SynchronousPluginRequestBuilderTests() + { + this.mockDriver = new Mock(); + + this.builder = new SynchronousPluginRequestBuilder(this.mockDriver.Object); + } + + [Fact] + public void Given_WhenCalled_AddsProviderState() + { + this.builder.Given("provider state"); + + this.mockDriver.Verify(d => d.Given("provider state")); + } + + [Fact] + public void Given_WhenCalled_ReturnsSameBuilder() + { + ISynchronousPluginRequestBuilderV4 result = this.builder.Given("provider state"); + + result.Should().BeSameAs(this.builder); + } + + [Fact] + public void Given_WithParam_AddsProviderState() + { + this.builder.Given("provider state", "foo", "bar"); + + this.mockDriver.Verify(d => d.GivenWithParam("provider state", "foo", "bar")); + } + + [Fact] + public void Given_WithParam_ReturnsSameBuilder() + { + ISynchronousPluginRequestBuilderV4 result = this.builder.Given("provider state", "foo", "bar"); + + result.Should().BeSameAs(this.builder); + } + + [Fact] + public void WithContent_WhenCalled_SetsInteractionContents() + { + var content = new Dictionary + { + ["pact:proto"] = "greet.proto", + ["pact:proto-service"] = "Greeter/SayHello", + ["pact:content-type"] = "application/protobuf", + ["request"] = new { name = "matching(type, 'foo')" }, + ["response"] = new { message = "matching(type, 'Hello foo')" } + }; + + this.builder.WithContent("application/grpc", content); + + this.mockDriver.Verify(d => d.WithContent("application/grpc", content), Times.Once); + } + } +} From bd9bd3610ef13595288eea331a811db42c59172c Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Fri, 9 Oct 2026 15:10:52 +0100 Subject: [PATCH 13/35] feat: prototype public HTTP content plugin interactions Add a public HTTP plugin pact/request/response API on top of the synchronous plugin prerequisite. Load content plugins through the existing factory, create HTTP rather than synchronous-message interactions, and route plugin contents independently to request and response parts. Reuse HTTP drivers for methods, paths, headers, queries and status; retain mock-server verification, logging, pact writing and plugin cleanup inside PactNet. Keep native handles and drivers internal. Reject repeated contents and response-stage reuse, validate HTTP status, and preserve header/query indexing. Add focused tests and HTTP plugin guidance. Asynchronous binary plugin message reification remains a separate contribution. Validation: 60 affected builder tests passed, including existing synchronous and HTTP behavior; the external Avro example passed native request/response and provider/mismatch verification with hominux avro 0.1.3 and FFI 0.4.27. --- docs/http-plugin-interactions.md | 31 ++++ .../IHttpPluginPactBuilder.cs | 41 ++++++ .../Plugins/HttpPluginInteractionDriver.cs | 35 +++++ .../Drivers/Plugins/IPluginPactDriver.cs | 1 + .../Plugins/PluginInteractionDriver.cs | 5 +- .../Drivers/Plugins/PluginPactDriver.cs | 5 + src/PactNet/HttpPluginPactBuilder.cs | 134 ++++++++++++++++++ src/PactNet/PactExtensions.cs | 18 +++ .../HttpPluginPactBuilderTests.cs | 79 +++++++++++ 9 files changed, 348 insertions(+), 1 deletion(-) create mode 100644 docs/http-plugin-interactions.md create mode 100644 src/PactNet.Abstractions/IHttpPluginPactBuilder.cs create mode 100644 src/PactNet/Drivers/Plugins/HttpPluginInteractionDriver.cs create mode 100644 src/PactNet/HttpPluginPactBuilder.cs create mode 100644 tests/PactNet.Tests/HttpPluginPactBuilderTests.cs diff --git a/docs/http-plugin-interactions.md b/docs/http-plugin-interactions.md new file mode 100644 index 000000000..ce5d14888 --- /dev/null +++ b/docs/http-plugin-interactions.md @@ -0,0 +1,31 @@ +# HTTP Plugin Interactions + +Content plugins can configure binary HTTP request and response bodies without +providing their own transport. The public `WithHttpPluginInteractions` entry point +creates HTTP interactions on a plugin-loaded pact and keeps native handles private. + +```csharp +using var pact = Pact.V4("consumer", "provider", config) + .WithHttpPluginInteractions("avro", "0.1.3"); + +pact.UponReceiving("an Avro response") + .WithRequest(HttpMethod.Get, "/avro") + .WillRespondWithStatus(200) + .WithHeader("Content-Type", "avro/binary;record=User") + .WithContent("avro/binary", new Dictionary + { + ["pact:avro"] = schemaPath, + ["pact:record-name"] = "User", + ["id"] = "matching(integer, 1)", + ["username"] = "matching(equalTo, 'alice')" + }); +``` + +Use `Verify`/`VerifyAsync` with the real HTTP client and dispose the builder. +Request contents can be configured once before the response stage. Response +contents complete the interaction and can be configured once; later headers or +contents are rejected. The plugin owns its configuration schema and binary encoding. + +PactNet still owns HTTP server startup, mismatches, logs, pact writing and plugin +cleanup. Provider verification uses the ordinary `PactVerifier`. This prototype +does not add asynchronous plugin message reification or expose FFI internals. \ No newline at end of file diff --git a/src/PactNet.Abstractions/IHttpPluginPactBuilder.cs b/src/PactNet.Abstractions/IHttpPluginPactBuilder.cs new file mode 100644 index 000000000..bb9f08308 --- /dev/null +++ b/src/PactNet.Abstractions/IHttpPluginPactBuilder.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; + +namespace PactNet +{ + /// HTTP interactions using a plugin to configure and match their contents. + public interface IHttpPluginPactBuilderV4 : IPactBuilder, IDisposable + { + /// Start an HTTP interaction. + IHttpPluginRequestBuilderV4 UponReceiving(string description); + } + + /// Configure an HTTP request before defining its response. + public interface IHttpPluginRequestBuilderV4 + { + /// Add a provider state. + IHttpPluginRequestBuilderV4 Given(string description); + /// Add a parameterized provider state. + IHttpPluginRequestBuilderV4 Given(string description, string name, string value); + /// Set the HTTP method and path. + IHttpPluginRequestBuilderV4 WithRequest(HttpMethod method, string path); + /// Add a query parameter. + IHttpPluginRequestBuilderV4 WithQuery(string name, string value); + /// Add a request header. + IHttpPluginRequestBuilderV4 WithHeader(string name, string value); + /// Configure request contents once using the plugin's contents schema. + IHttpPluginRequestBuilderV4 WithContent(string contentType, Dictionary content); + /// Complete the request and begin the response. + IHttpPluginResponseBuilderV4 WillRespondWithStatus(int status); + } + + /// Configure an HTTP response using plugin contents. + public interface IHttpPluginResponseBuilderV4 + { + /// Add a response header before setting contents. + IHttpPluginResponseBuilderV4 WithHeader(string name, string value); + /// Configure response contents once, completing this interaction. + void WithContent(string contentType, Dictionary content); + } +} \ No newline at end of file diff --git a/src/PactNet/Drivers/Plugins/HttpPluginInteractionDriver.cs b/src/PactNet/Drivers/Plugins/HttpPluginInteractionDriver.cs new file mode 100644 index 000000000..bc8c0d979 --- /dev/null +++ b/src/PactNet/Drivers/Plugins/HttpPluginInteractionDriver.cs @@ -0,0 +1,35 @@ +using System.Collections.Generic; +using PactNet.Drivers.Http; +using PactNet.Interop; + +namespace PactNet.Drivers.Plugins +{ + internal interface IHttpPluginInteractionDriver : IHttpInteractionDriver + { + void WithPluginContent(InteractionPart part, string contentType, Dictionary content); + } + + internal class HttpPluginInteractionDriver : IHttpPluginInteractionDriver + { + private readonly HttpInteractionDriver http; + private readonly PluginInteractionDriver plugin; + + internal HttpPluginInteractionDriver(InteractionHandle interaction) + { + this.http = new HttpInteractionDriver(interaction); + this.plugin = new PluginInteractionDriver(interaction); + } + + public void Given(string description) => this.http.Given(description); + public void GivenWithParam(string description, string name, string value) => this.http.GivenWithParam(description, name, value); + public void WithRequest(string method, string path) => this.http.WithRequest(method, path); + public void WithQueryParameter(string name, string value, uint index) => this.http.WithQueryParameter(name, value, index); + public void WithRequestHeader(string name, string value, uint index) => this.http.WithRequestHeader(name, value, index); + public void WithResponseHeader(string name, string value, uint index) => this.http.WithResponseHeader(name, value, index); + public void WithResponseStatus(ushort status) => this.http.WithResponseStatus(status); + public void WithRequestBody(string contentType, string body) => this.http.WithRequestBody(contentType, body); + public void WithResponseBody(string contentType, string body) => this.http.WithResponseBody(contentType, body); + public void WithPluginContent(InteractionPart part, string contentType, Dictionary content) + => this.plugin.WithContent(part, contentType, content); + } +} \ No newline at end of file diff --git a/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs b/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs index 09c9b395b..3d5912daa 100644 --- a/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs +++ b/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs @@ -13,5 +13,6 @@ internal interface IPluginPactDriver : ICompletedPactDriver, IDisposable /// Interaction description /// Interaction driver IPluginInteractionDriver NewSyncInteraction(string description); + IHttpPluginInteractionDriver NewHttpPluginInteraction(string description); } } diff --git a/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs b/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs index e2cf360b0..215b8c375 100644 --- a/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs +++ b/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs @@ -43,8 +43,11 @@ public void GivenWithParam(string description, string name, string value) /// Content type /// A dictionary containing the plugin content. public void WithContent(string contentType, Dictionary content) + => this.WithContent(InteractionPart.Request, contentType, content); + + internal void WithContent(InteractionPart part, string contentType, Dictionary content) { - uint code = NativeInterop.InteractionContents(this.interaction, InteractionPart.Request, contentType, JsonSerializer.Serialize(content)); + uint code = NativeInterop.InteractionContents(this.interaction, part, contentType, JsonSerializer.Serialize(content)); if (code != 0) { diff --git a/src/PactNet/Drivers/Plugins/PluginPactDriver.cs b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs index e0e5da9aa..33c6b0e2b 100644 --- a/src/PactNet/Drivers/Plugins/PluginPactDriver.cs +++ b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs @@ -27,6 +27,11 @@ public IPluginInteractionDriver NewSyncInteraction(string description) return new PluginInteractionDriver(interaction); } + public IHttpPluginInteractionDriver NewHttpPluginInteraction(string description) + { + InteractionHandle interaction = NativeInterop.NewInteraction(this.pact, description); + return new HttpPluginInteractionDriver(interaction); + } /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. diff --git a/src/PactNet/HttpPluginPactBuilder.cs b/src/PactNet/HttpPluginPactBuilder.cs new file mode 100644 index 000000000..045761243 --- /dev/null +++ b/src/PactNet/HttpPluginPactBuilder.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using PactNet.Drivers.Plugins; +using PactNet.Interop; +using PactNet.Models; + +namespace PactNet +{ + internal class HttpPluginPactBuilder : AbstractPactBuilder, IHttpPluginPactBuilderV4 + { + private readonly IPluginPactDriver pact; + + internal HttpPluginPactBuilder(IPluginPactDriver pact, PactConfig config, int? port = null, + IPAddress host = IPAddress.Loopback) : base(pact, config, port, host, "http") + { + this.pact = pact; + } + + public IHttpPluginRequestBuilderV4 UponReceiving(string description) + => new HttpPluginRequestBuilder(this.pact.NewHttpPluginInteraction(description)); + + public void Dispose() => this.pact.Dispose(); + } + + internal class HttpPluginRequestBuilder : IHttpPluginRequestBuilderV4 + { + private readonly IHttpPluginInteractionDriver driver; + private readonly Dictionary headers = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary queries = new(); + private bool requestConfigured; + private bool contentsConfigured; + private bool responseStarted; + + internal HttpPluginRequestBuilder(IHttpPluginInteractionDriver driver) => this.driver = driver; + + private void EnsureMutable() + { + if (this.responseStarted) throw new InvalidOperationException("The request has already been completed."); + } + + public IHttpPluginRequestBuilderV4 Given(string description) + { + this.EnsureMutable(); + this.driver.Given(description); + return this; + } + + public IHttpPluginRequestBuilderV4 Given(string description, string name, string value) + { + this.EnsureMutable(); + this.driver.GivenWithParam(description, name, value); + return this; + } + + public IHttpPluginRequestBuilderV4 WithRequest(HttpMethod method, string path) + { + this.EnsureMutable(); + if (this.requestConfigured) throw new InvalidOperationException("Request has already been configured."); + if (method == null) throw new ArgumentNullException(nameof(method)); + if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("A request path is required.", nameof(path)); + this.driver.WithRequest(method.Method, path); + this.requestConfigured = true; + return this; + } + + public IHttpPluginRequestBuilderV4 WithQuery(string name, string value) + { + this.EnsureMutable(); + this.queries.TryGetValue(name, out uint index); + this.driver.WithQueryParameter(name, value, index); + this.queries[name] = index + 1; + return this; + } + + public IHttpPluginRequestBuilderV4 WithHeader(string name, string value) + { + this.EnsureMutable(); + this.headers.TryGetValue(name, out uint index); + this.driver.WithRequestHeader(name, value, index); + this.headers[name] = index + 1; + return this; + } + + public IHttpPluginRequestBuilderV4 WithContent(string contentType, Dictionary content) + { + this.EnsureMutable(); + if (this.contentsConfigured) throw new InvalidOperationException("Request contents have already been configured."); + this.driver.WithPluginContent(InteractionPart.Request, contentType, content); + this.contentsConfigured = true; + return this; + } + + public IHttpPluginResponseBuilderV4 WillRespondWithStatus(int status) + { + this.EnsureMutable(); + if (!this.requestConfigured) throw new InvalidOperationException("Configure the HTTP request first."); + if (status < 100 || status > 599) throw new ArgumentOutOfRangeException(nameof(status)); + this.driver.WithResponseStatus((ushort)status); + this.responseStarted = true; + return new HttpPluginResponseBuilder(this.driver); + } + } + + internal class HttpPluginResponseBuilder : IHttpPluginResponseBuilderV4 + { + private readonly IHttpPluginInteractionDriver driver; + private readonly Dictionary headers = new(StringComparer.OrdinalIgnoreCase); + private bool completed; + + internal HttpPluginResponseBuilder(IHttpPluginInteractionDriver driver) => this.driver = driver; + + private void EnsureMutable() + { + if (this.completed) throw new InvalidOperationException("Response contents have already been configured."); + } + + public IHttpPluginResponseBuilderV4 WithHeader(string name, string value) + { + this.EnsureMutable(); + this.headers.TryGetValue(name, out uint index); + this.driver.WithResponseHeader(name, value, index); + this.headers[name] = index + 1; + return this; + } + + public void WithContent(string contentType, Dictionary content) + { + this.EnsureMutable(); + this.driver.WithPluginContent(InteractionPart.Response, contentType, content); + this.completed = true; + } + } +} \ No newline at end of file diff --git a/src/PactNet/PactExtensions.cs b/src/PactNet/PactExtensions.cs index 24f7575d4..53211fabe 100644 --- a/src/PactNet/PactExtensions.cs +++ b/src/PactNet/PactExtensions.cs @@ -137,5 +137,23 @@ public static ISynchronousPluginPactBuilderV4 WithSynchronousPluginInteractions( return new SynchronousPluginPactBuilder(pluginDriver, pact.Config, port, host, transport); } + + /// Create HTTP interactions with plugin-defined request or response contents. + /// Pact details. + /// Content plugin name. + /// Optional plugin version. + /// Optional mock server port. + /// Mock server host. + /// HTTP plugin builder. + public static IHttpPluginPactBuilderV4 WithHttpPluginInteractions(this IPactV4 pact, + string pluginName, string pluginVersion = null, int? port = null, + IPAddress host = IPAddress.Loopback) + { + pact.Config.LogLevel.LogToBuffer(); + IPactDriver driver = new PactDriver(); + IPluginPactDriver pluginDriver = driver.NewPluginPact(pact.Consumer, pact.Provider, + pluginName, pluginVersion, PactSpecification.V4); + return new HttpPluginPactBuilder(pluginDriver, pact.Config, port, host); + } } } diff --git a/tests/PactNet.Tests/HttpPluginPactBuilderTests.cs b/tests/PactNet.Tests/HttpPluginPactBuilderTests.cs new file mode 100644 index 000000000..a93f1f539 --- /dev/null +++ b/tests/PactNet.Tests/HttpPluginPactBuilderTests.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using Moq; +using PactNet.Drivers.Plugins; +using PactNet.Interop; +using Xunit; + +namespace PactNet.Tests; + +public class HttpPluginPactBuilderTests +{ + private readonly Mock driver = new(); + + [Fact] + public void Contents_AreSentToTheCorrectHttpPart() + { + var request = new HttpPluginRequestBuilder(this.driver.Object); + var contents = new Dictionary(); + request.WithRequest(HttpMethod.Post, "/avro") + .WithContent("avro/binary", contents) + .WillRespondWithStatus(201).WithContent("avro/binary", contents); + this.driver.Verify(value => value.WithRequest("POST", "/avro"), Times.Once); + this.driver.Verify(value => value.WithResponseStatus(201), Times.Once); + this.driver.Verify(value => value.WithPluginContent(InteractionPart.Request, "avro/binary", contents), Times.Once); + this.driver.Verify(value => value.WithPluginContent(InteractionPart.Response, "avro/binary", contents), Times.Once); + } + + [Fact] + public void Response_RejectsRepeatedContentsAndHeadersAfterCompletion() + { + var response = new HttpPluginResponseBuilder(this.driver.Object); + var contents = new Dictionary(); + response.WithContent("avro/binary", contents); + Assert.Throws(() => response.WithContent("avro/binary", contents)); + Assert.Throws(() => response.WithHeader("Content-Type", "avro/binary")); + } + + [Fact] + public void Request_RejectsReuseAndInvalidOrdering() + { + var request = new HttpPluginRequestBuilder(this.driver.Object); + Assert.Throws(() => request.WillRespondWithStatus(200)); + request.WithRequest(HttpMethod.Get, "/avro"); + Assert.Throws(() => request.WithRequest(HttpMethod.Post, "/avro")); + Assert.Throws(() => request.WillRespondWithStatus(600)); + request.WithContent("avro/binary", new Dictionary()); + Assert.Throws(() => request.WithContent("avro/binary", new Dictionary())); + request.WillRespondWithStatus(200); + Assert.Throws(() => request.WillRespondWithStatus(200)); + Assert.Throws(() => request.Given("late state")); + } + + [Fact] + public void RepeatedHeadersAndQueries_UseIndependentIndexes() + { + var request = new HttpPluginRequestBuilder(this.driver.Object); + request.WithHeader("Accept", "one").WithHeader("accept", "two") + .WithQuery("id", "one").WithQuery("id", "two"); + var response = new HttpPluginResponseBuilder(this.driver.Object); + response.WithHeader("X-Test", "one").WithHeader("x-test", "two"); + this.driver.Verify(value => value.WithRequestHeader("accept", "two", 1), Times.Once); + this.driver.Verify(value => value.WithQueryParameter("id", "two", 1), Times.Once); + this.driver.Verify(value => value.WithResponseHeader("x-test", "two", 1), Times.Once); + } + + [Fact] + public void Pact_UsesHttpInteractionFactoryAndDelegatesDisposal() + { + var pact = new Mock(); + pact.Setup(value => value.NewHttpPluginInteraction("an avro request")).Returns(this.driver.Object); + using (var builder = new HttpPluginPactBuilder(pact.Object, new PactConfig())) + { + builder.UponReceiving("an avro request"); + } + pact.Verify(value => value.NewHttpPluginInteraction("an avro request"), Times.Once); + pact.Verify(value => value.Dispose(), Times.Once); + } +} \ No newline at end of file From 71aa4584d2a06b3e1e624a6f406cf26f2dd04a0c Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Fri, 9 Oct 2026 15:33:00 +0100 Subject: [PATCH 14/35] feat: prototype asynchronous binary plugin messages Add transport-free asynchronous plugin pact/message builders and configured consumer verification. Expose generated binary payloads, media type and cloned JSON metadata, write the pact only after successful consumption, and keep native reification and plugin cleanup internal. Decode the native V4 base64 envelope and free its allocated string. Apply user metadata after plugin content configuration, which can replace native message metadata. Preserve the existing JSON message APIs and add ordering, terminal-content, callback success/failure and disposal tests. Add an opt-in native Avro 0.1.3 synchronous capability check. With FFI 0.4.27, its unlabelled single-record configuration creates an empty sync request and no responses. Document the need for plugin request/response parts and a separate transport-free sync consumer matching API rather than presenting the transport-based gRPC builder as Avro sync support. Validation: 109 affected plugin/message/HTTP builder tests passed with the capability check enabled. External Avro async consumer/provider and mismatch checks passed with binary records and metadata. HTTP and gRPC regressions remained green. --- docs/async-plugin-interactions.md | 35 +++++ .../IAsynchronousPluginPactBuilder.cs | 54 +++++++ src/PactNet/AsynchronousPluginPactBuilder.cs | 135 ++++++++++++++++++ .../Message/MessageInteractionDriver.cs | 10 +- .../AsynchronousPluginInteractionDriver.cs | 24 ++++ .../Drivers/Plugins/IPluginPactDriver.cs | 1 + .../Drivers/Plugins/PluginPactDriver.cs | 6 + src/PactNet/PactExtensions.cs | 15 ++ .../AsynchronousPluginPactBuilderTests.cs | 81 +++++++++++ .../AvroSynchronousCapabilityTests.cs | 46 ++++++ 10 files changed, 405 insertions(+), 2 deletions(-) create mode 100644 docs/async-plugin-interactions.md create mode 100644 src/PactNet.Abstractions/IAsynchronousPluginPactBuilder.cs create mode 100644 src/PactNet/AsynchronousPluginPactBuilder.cs create mode 100644 src/PactNet/Drivers/Plugins/AsynchronousPluginInteractionDriver.cs create mode 100644 tests/PactNet.Tests/AsynchronousPluginPactBuilderTests.cs create mode 100644 tests/PactNet.Tests/AvroSynchronousCapabilityTests.cs diff --git a/docs/async-plugin-interactions.md b/docs/async-plugin-interactions.md new file mode 100644 index 000000000..460a6d755 --- /dev/null +++ b/docs/async-plugin-interactions.md @@ -0,0 +1,35 @@ +# Asynchronous Plugin Messages + +Use `WithAsynchronousPluginInteractions` for content plugins without a transport +server. Configure a single message, then exercise the real consumer with generated +binary contents and metadata: + +```csharp +using var pact = Pact.V4("consumer", "provider", config) + .WithAsynchronousPluginInteractions("avro", "0.1.3"); + +await pact.ExpectsToReceive("an Avro user") + .WithMetadata("topic", "users") + .WithContent("avro/binary", contents) + .VerifyAsync(message => ConsumeUserAsync(message.Contents, message.Metadata)); +``` + +The contents dictionary follows the plugin's schema; for Avro it includes +`pact:avro`, `pact:record-name` and record field matching expressions. Message +contents are terminal. User metadata is applied after plugin configuration so +it is not replaced by the plugin's generated metadata. + +`PluginMessage` contains copied binary contents, the media type and cloned JSON +metadata values. PactNet decodes the V4 base64 envelope, owns the reified native +string, writes the pact only after a successful callback, and cleans up plugins +when the pact builder is disposed. The existing JSON message API is unchanged. + +This does not start Kafka/RabbitMQ or claim broker-delivery coverage. Producer +verification uses the normal verifier with a message provider or HTTP message +adapter. Review multi-message/generator/error paths and platform coverage before +publishing this prototype API. + +Avro 0.1.3's single unlabelled interaction does not populate a synchronous message's +request/response fields with FFI 0.4.27. An opt-in native capability test records +that limitation. Distinct sync parts require an Avro plugin change; transport-free +binary request/response consumer verification also needs a separate PactNet API. \ No newline at end of file diff --git a/src/PactNet.Abstractions/IAsynchronousPluginPactBuilder.cs b/src/PactNet.Abstractions/IAsynchronousPluginPactBuilder.cs new file mode 100644 index 000000000..cdb94a556 --- /dev/null +++ b/src/PactNet.Abstractions/IAsynchronousPluginPactBuilder.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace PactNet +{ + /// Asynchronous plugin messages with transport abstracted away. + public interface IAsynchronousPluginPactBuilderV4 : IDisposable + { + /// Start an asynchronous message. + IAsynchronousPluginMessageBuilderV4 ExpectsToReceive(string description); + } + + /// Configure a message before consumer verification. + public interface IAsynchronousPluginMessageBuilderV4 + { + /// Add a provider state. + IAsynchronousPluginMessageBuilderV4 Given(string description); + /// Add a parameterized provider state. + IAsynchronousPluginMessageBuilderV4 Given(string description, string name, string value); + /// Add message metadata. + IAsynchronousPluginMessageBuilderV4 WithMetadata(string name, string value); + /// Set plugin-defined contents once and move to verification. + IConfiguredPluginMessageVerifier WithContent(string contentType, Dictionary content); + } + + /// Run the real consumer with a generated plugin message. + public interface IConfiguredPluginMessageVerifier + { + /// Verify consumption, then write the pact on success. + void Verify(Action consumer); + /// Verify asynchronous consumption, then write the pact on success. + Task VerifyAsync(Func consumer); + } + + /// Generated binary contents and metadata for a plugin message. + public sealed class PluginMessage + { + /// Binary payload, not a JSON serialization of the record. + public byte[] Contents { get; } + /// Payload content type. + public string ContentType { get; } + /// Message metadata. + public IReadOnlyDictionary Metadata { get; } + + /// Create a generated message context. + public PluginMessage(byte[] contents, string contentType, IReadOnlyDictionary metadata) + { + this.Contents = contents ?? throw new ArgumentNullException(nameof(contents)); + this.ContentType = contentType; + this.Metadata = metadata ?? throw new ArgumentNullException(nameof(metadata)); + } + } +} \ No newline at end of file diff --git a/src/PactNet/AsynchronousPluginPactBuilder.cs b/src/PactNet/AsynchronousPluginPactBuilder.cs new file mode 100644 index 000000000..98326acde --- /dev/null +++ b/src/PactNet/AsynchronousPluginPactBuilder.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using PactNet.Drivers.Plugins; +using PactNet.Exceptions; + +namespace PactNet +{ + internal class AsynchronousPluginPactBuilder : IAsynchronousPluginPactBuilderV4 + { + private readonly IPluginPactDriver driver; + private readonly PactConfig config; + + internal AsynchronousPluginPactBuilder(IPluginPactDriver driver, PactConfig config) + { + this.driver = driver; + this.config = config; + } + + public IAsynchronousPluginMessageBuilderV4 ExpectsToReceive(string description) + => new AsynchronousPluginMessageBuilder(this.driver.NewAsynchronousPluginInteraction(description), this.config); + + public void Dispose() => this.driver.Dispose(); + } + + internal class AsynchronousPluginMessageBuilder : IAsynchronousPluginMessageBuilderV4 + { + private readonly IAsynchronousPluginInteractionDriver driver; + private readonly PactConfig config; + private readonly Dictionary metadata = new(); + private bool completed; + + internal AsynchronousPluginMessageBuilder(IAsynchronousPluginInteractionDriver driver, PactConfig config) + { + this.driver = driver; + this.config = config; + } + + private void EnsureMutable() + { + if (this.completed) throw new InvalidOperationException("Message contents have already been configured."); + } + + public IAsynchronousPluginMessageBuilderV4 Given(string description) + { + this.EnsureMutable(); + this.driver.Given(description); + return this; + } + + public IAsynchronousPluginMessageBuilderV4 Given(string description, string name, string value) + { + this.EnsureMutable(); + this.driver.GivenWithParam(description, name, value); + return this; + } + + public IAsynchronousPluginMessageBuilderV4 WithMetadata(string name, string value) + { + this.EnsureMutable(); + this.metadata[name] = value; + return this; + } + + public IConfiguredPluginMessageVerifier WithContent(string contentType, Dictionary content) + { + this.EnsureMutable(); + this.driver.WithPluginContent(contentType, content); + foreach (var property in this.metadata) + this.driver.WithMetadata(property.Key, property.Value); + this.completed = true; + return new ConfiguredPluginMessageVerifier(this.driver, this.config); + } + } + + internal class ConfiguredPluginMessageVerifier : IConfiguredPluginMessageVerifier + { + private readonly IAsynchronousPluginInteractionDriver driver; + private readonly PactConfig config; + + internal ConfiguredPluginMessageVerifier(IAsynchronousPluginInteractionDriver driver, PactConfig config) + { + this.driver = driver; + this.config = config; + } + + internal static PluginMessage Decode(string reified) + { + using var document = JsonDocument.Parse(reified); + var contents = document.RootElement.GetProperty("contents"); + string content = contents.GetProperty("content").GetString(); + bool encoded = contents.TryGetProperty("encoded", out var encoding) + && (encoding.ValueKind == JsonValueKind.True + || (encoding.ValueKind == JsonValueKind.String && encoding.GetString() == "base64")); + byte[] bytes = encoded ? Convert.FromBase64String(content) : Encoding.UTF8.GetBytes(content); + var metadata = new Dictionary(); + if (document.RootElement.TryGetProperty("metadata", out var properties)) + { + foreach (var property in properties.EnumerateObject()) + metadata[property.Name] = property.Value.Clone(); + } + return new PluginMessage(bytes, contents.GetProperty("contentType").GetString(), metadata); + } + + public void Verify(Action consumer) + { + if (consumer == null) throw new ArgumentNullException(nameof(consumer)); + try + { + consumer(Decode(this.driver.Reify())); + this.driver.WritePactFile(this.config.PactDir); + } + catch (Exception exception) + { + throw new PactMessageConsumerVerificationException("The plugin message could not be verified by the consumer handler.", exception); + } + } + + public async Task VerifyAsync(Func consumer) + { + if (consumer == null) throw new ArgumentNullException(nameof(consumer)); + try + { + await consumer(Decode(this.driver.Reify())); + this.driver.WritePactFile(this.config.PactDir); + } + catch (Exception exception) + { + throw new PactMessageConsumerVerificationException("The plugin message could not be verified by the consumer handler.", exception); + } + } + } +} \ No newline at end of file diff --git a/src/PactNet/Drivers/Message/MessageInteractionDriver.cs b/src/PactNet/Drivers/Message/MessageInteractionDriver.cs index 58ee7128f..56a04d31e 100644 --- a/src/PactNet/Drivers/Message/MessageInteractionDriver.cs +++ b/src/PactNet/Drivers/Message/MessageInteractionDriver.cs @@ -68,8 +68,14 @@ public void WithContents(string contentType, string body, uint size) public string Reify() { IntPtr pointer = NativeInterop.MessageReify(this.interaction); - string body = Marshal.PtrToStringAnsi(pointer); - return body; + try + { + return Marshal.PtrToStringAnsi(pointer); + } + finally + { + NativeInterop.FreeString(pointer); + } } } } diff --git a/src/PactNet/Drivers/Plugins/AsynchronousPluginInteractionDriver.cs b/src/PactNet/Drivers/Plugins/AsynchronousPluginInteractionDriver.cs new file mode 100644 index 000000000..407a5c838 --- /dev/null +++ b/src/PactNet/Drivers/Plugins/AsynchronousPluginInteractionDriver.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; +using PactNet.Drivers.Message; +using PactNet.Interop; + +namespace PactNet.Drivers.Plugins +{ + internal interface IAsynchronousPluginInteractionDriver : IMessageInteractionDriver + { + void WithPluginContent(string contentType, Dictionary content); + } + + internal class AsynchronousPluginInteractionDriver : MessageInteractionDriver, IAsynchronousPluginInteractionDriver + { + private readonly PluginInteractionDriver plugin; + + internal AsynchronousPluginInteractionDriver(PactHandle pact, InteractionHandle interaction) : base(pact, interaction) + { + this.plugin = new PluginInteractionDriver(interaction); + } + + public void WithPluginContent(string contentType, Dictionary content) + => this.plugin.WithContent(InteractionPart.Request, contentType, content); + } +} \ No newline at end of file diff --git a/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs b/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs index 3d5912daa..909d6e459 100644 --- a/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs +++ b/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs @@ -14,5 +14,6 @@ internal interface IPluginPactDriver : ICompletedPactDriver, IDisposable /// Interaction driver IPluginInteractionDriver NewSyncInteraction(string description); IHttpPluginInteractionDriver NewHttpPluginInteraction(string description); + IAsynchronousPluginInteractionDriver NewAsynchronousPluginInteraction(string description); } } diff --git a/src/PactNet/Drivers/Plugins/PluginPactDriver.cs b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs index 33c6b0e2b..b5a054a32 100644 --- a/src/PactNet/Drivers/Plugins/PluginPactDriver.cs +++ b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs @@ -33,6 +33,12 @@ public IHttpPluginInteractionDriver NewHttpPluginInteraction(string description) return new HttpPluginInteractionDriver(interaction); } + public IAsynchronousPluginInteractionDriver NewAsynchronousPluginInteraction(string description) + { + InteractionHandle interaction = NativeInterop.NewMessageInteraction(this.pact, description); + return new AsynchronousPluginInteractionDriver(this.pact, interaction); + } + /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// diff --git a/src/PactNet/PactExtensions.cs b/src/PactNet/PactExtensions.cs index 53211fabe..605091639 100644 --- a/src/PactNet/PactExtensions.cs +++ b/src/PactNet/PactExtensions.cs @@ -155,5 +155,20 @@ public static IHttpPluginPactBuilderV4 WithHttpPluginInteractions(this IPactV4 p pluginName, pluginVersion, PactSpecification.V4); return new HttpPluginPactBuilder(pluginDriver, pact.Config, port, host); } + + /// Create asynchronous plugin messages without a mock-server transport. + /// Pact details. + /// Content plugin name. + /// Optional plugin version. + /// Asynchronous plugin message builder. + public static IAsynchronousPluginPactBuilderV4 WithAsynchronousPluginInteractions(this IPactV4 pact, + string pluginName, string pluginVersion = null) + { + pact.Config.LogLevel.LogToBuffer(); + IPactDriver driver = new PactDriver(); + IPluginPactDriver pluginDriver = driver.NewPluginPact(pact.Consumer, pact.Provider, + pluginName, pluginVersion, PactSpecification.V4); + return new AsynchronousPluginPactBuilder(pluginDriver, pact.Config); + } } } diff --git a/tests/PactNet.Tests/AsynchronousPluginPactBuilderTests.cs b/tests/PactNet.Tests/AsynchronousPluginPactBuilderTests.cs new file mode 100644 index 000000000..2c44a8c5e --- /dev/null +++ b/tests/PactNet.Tests/AsynchronousPluginPactBuilderTests.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Threading.Tasks; +using Moq; +using PactNet.Drivers.Plugins; +using PactNet.Exceptions; +using Xunit; + +namespace PactNet.Tests; + +public class AsynchronousPluginPactBuilderTests +{ + private readonly Mock driver = new(); + private readonly PactConfig config = new() { PactDir = "test-pacts" }; + private const string Reified = "{\"contents\":{\"content\":\"AP8B\",\"contentType\":\"avro/binary;record=User\",\"encoded\":\"base64\"},\"metadata\":{\"topic\":\"users\"}}"; + + [Fact] + public void Decode_PreservesBinaryBytesAndMetadata() + { + var message = ConfiguredPluginMessageVerifier.Decode(Reified); + Assert.Equal(new byte[] { 0, 255, 1 }, message.Contents); + Assert.Equal("avro/binary;record=User", message.ContentType); + Assert.Equal("users", ((JsonElement)message.Metadata["topic"]).GetString()); + } + + [Fact] + public void Contents_AreSingleShotAndFreezeMetadata() + { + var builder = new AsynchronousPluginMessageBuilder(this.driver.Object, this.config); + var contents = new Dictionary(); + builder.Given("available", "id", "1").WithMetadata("topic", "users").WithContent("avro/binary", contents); + Assert.Throws(() => builder.WithContent("avro/binary", contents)); + Assert.Throws(() => builder.WithMetadata("topic", "other")); + this.driver.Verify(value => value.WithPluginContent("avro/binary", contents), Times.Once); + this.driver.Verify(value => value.GivenWithParam("available", "id", "1"), Times.Once); + } + + [Fact] + public async Task SuccessfulCallback_WritesThePact() + { + this.driver.Setup(value => value.Reify()).Returns(Reified); + await new ConfiguredPluginMessageVerifier(this.driver.Object, this.config) + .VerifyAsync(message => { Assert.Equal(3, message.Contents.Length); return Task.CompletedTask; }); + this.driver.Verify(value => value.WritePactFile(this.config.PactDir), Times.Once); + } + + [Fact] + public void Metadata_IsAppliedAfterPluginConfiguration() + { + var ordered = new Mock(MockBehavior.Strict); + var sequence = new MockSequence(); + ordered.InSequence(sequence).Setup(value => value.WithPluginContent("avro/binary", It.IsAny>())); + ordered.InSequence(sequence).Setup(value => value.WithMetadata("topic", "users")); + new AsynchronousPluginMessageBuilder(ordered.Object, this.config).WithMetadata("topic", "users") + .WithContent("avro/binary", new Dictionary()); + ordered.Verify(value => value.WithMetadata("topic", "users"), Times.Once); + } + + [Fact] + public void Pact_CreatesMessagesAndDisposesItsDriver() + { + var pact = new Mock(); + pact.Setup(value => value.NewAsynchronousPluginInteraction("a message")).Returns(this.driver.Object); + using (var builder = new AsynchronousPluginPactBuilder(pact.Object, this.config)) + { + builder.ExpectsToReceive("a message"); + } + pact.Verify(value => value.Dispose(), Times.Once); + } + + [Fact] + public void FailedCallback_DoesNotWriteThePact() + { + this.driver.Setup(value => value.Reify()).Returns(Reified); + Assert.Throws(() => + new ConfiguredPluginMessageVerifier(this.driver.Object, this.config) + .Verify(_ => throw new InvalidOperationException("consumer rejected the record"))); + this.driver.Verify(value => value.WritePactFile(It.IsAny()), Times.Never); + } +} \ No newline at end of file diff --git a/tests/PactNet.Tests/AvroSynchronousCapabilityTests.cs b/tests/PactNet.Tests/AvroSynchronousCapabilityTests.cs new file mode 100644 index 000000000..187695721 --- /dev/null +++ b/tests/PactNet.Tests/AvroSynchronousCapabilityTests.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using PactNet.Drivers; +using PactNet.Interop; +using Xunit; +using Xunit.Abstractions; + +namespace PactNet.Tests; + +public class AvroSynchronousCapabilityTests(ITestOutputHelper output) +{ + private sealed class AvroCapabilityFactAttribute : FactAttribute + { + public AvroCapabilityFactAttribute() + { + if (Environment.GetEnvironmentVariable("AVRO_SCHEMA_PATH") == null) + this.Skip = "Set AVRO_SCHEMA_PATH and install Avro 0.1.3 to run the native capability probe."; + } + } + + [AvroCapabilityFact] + public void Avro013_UnlabelledRecordDoesNotPopulateSynchronousParts() + { + string schema = Environment.GetEnvironmentVariable("AVRO_SCHEMA_PATH"); + string directory = Path.Combine(Path.GetTempPath(), "pact-avro-sync-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + using var pact = new PactDriver().NewPluginPact("AvroSyncProbe", "AvroSyncProvider", "avro", "0.1.3", PactSpecification.V4); + pact.NewSyncInteraction("an Avro request response").WithContent("avro/binary", new Dictionary + { + ["pact:avro"] = schema, + ["pact:record-name"] = "User", + ["id"] = "matching(integer, 1)", + ["username"] = "matching(equalTo, 'alice')" + }); + pact.WritePactFile(directory); + string json = File.ReadAllText(Path.Combine(directory, "AvroSyncProbe-AvroSyncProvider.json")); + output.WriteLine(json); + using var document = JsonDocument.Parse(json); + var interaction = document.RootElement.GetProperty("interactions")[0]; + Assert.Equal("Synchronous/Messages", interaction.GetProperty("type").GetString()); + Assert.False(interaction.GetProperty("request").TryGetProperty("contents", out _)); + Assert.Equal(0, interaction.GetProperty("response").GetArrayLength()); + } +} \ No newline at end of file From 3de6c44fcc04b45535895971fe53fb09db2c12c4 Mon Sep 17 00:00:00 2001 From: Max Lancaster Date: Mon, 12 Oct 2026 15:08:49 +0200 Subject: [PATCH 15/35] ci: add protoc to linux arm64 wf --- .github/workflows/ci.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc509a4b3..dda963e0c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,6 +56,10 @@ jobs: run: bash -c "build/download-native-libs.sh" if: ${{ steps.cache.outputs.cache-hit != 'true' }} + - name: Install protoc (for grpc plugin test) + run: sudo apt-get install --yes protobuf-compiler + if: ${{ matrix.os == 'ubuntu-24.04-arm' }} + - name: Restore run: dotnet restore From 7887b3e04acfd077ab88c7b6e40bc7788e0e608b Mon Sep 17 00:00:00 2001 From: Max Lancaster Date: Mon, 12 Oct 2026 15:13:39 +0200 Subject: [PATCH 16/35] chore(deps): update sample to latest grpc/proto packages --- samples/Grpc/GrpcGreeter/GrpcGreeter.csproj | 4 ++-- samples/Grpc/GrpcGreeterClient/GrpcGreeterClient.csproj | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/Grpc/GrpcGreeter/GrpcGreeter.csproj b/samples/Grpc/GrpcGreeter/GrpcGreeter.csproj index ef753ccdf..379777aca 100644 --- a/samples/Grpc/GrpcGreeter/GrpcGreeter.csproj +++ b/samples/Grpc/GrpcGreeter/GrpcGreeter.csproj @@ -11,8 +11,8 @@ - - + + diff --git a/samples/Grpc/GrpcGreeterClient/GrpcGreeterClient.csproj b/samples/Grpc/GrpcGreeterClient/GrpcGreeterClient.csproj index 94331d73f..438da30c5 100644 --- a/samples/Grpc/GrpcGreeterClient/GrpcGreeterClient.csproj +++ b/samples/Grpc/GrpcGreeterClient/GrpcGreeterClient.csproj @@ -11,9 +11,9 @@ - - - + + + runtime; build; native; contentfiles; analyzers; buildtransitive all From 44d88b537b2ff09ad7b4b7d03e5d4c4bdbff2da4 Mon Sep 17 00:00:00 2001 From: Max Lancaster Date: Mon, 12 Oct 2026 15:54:19 +0200 Subject: [PATCH 17/35] chore(ffi): upgrade to pact-ffi 0.5.10 and regenerate fixtures with protobuf plugin 0.8.0 Brings in YOU54F/pact-net@92748436 as requested in the PR #551 review. - pact-ffi 0.4.27 -> 0.5.10; a request header configured with multiple values is now matched as one joined value, so the tests and the upgrading-to-5 doc reflect that - pact fixtures regenerated (pactRust metadata, merged X-Request header) - grpc sample pact regenerated with pact-protobuf-plugin 0.8.0 - grpc sample and plugin docs now request plugin 0.8.0 Co-Authored-By: Claude Fable 5.1 --- build/download-native-libs.sh | 2 +- docs/plugin-interactions.md | 4 +-- docs/upgrading-to-5.md | 15 +++++++++ .../GrpcGreeterClientTest.cs | 2 +- .../grpc-greeter-client-grpc-greeter.json | 32 +++++++++++++------ .../pacts/Fulfilment API-Orders API.json | 6 ++-- .../Drivers/FfiIntegrationTests.cs | 3 +- tests/PactNet.Tests/PactExtensionsTests.cs | 12 +++---- .../data/v2-consumer-integration.json | 6 ++-- .../data/v3-consumer-integration.json | 6 ++-- .../data/v3-message-consumer-integration.json | 4 +-- .../data/v3-message-integration.json | 4 +-- .../data/v3-server-integration.json | 4 +-- .../data/v4-combined-integration.json | 7 ++-- .../data/v4-consumer-integration.json | 9 +++--- .../data/v4-message-consumer-integration.json | 4 +-- 16 files changed, 70 insertions(+), 50 deletions(-) diff --git a/build/download-native-libs.sh b/build/download-native-libs.sh index c3ace8918..eb3f6b1bf 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.10" FFI_BASE_URL="https://github.com/pact-foundation/pact-reference/releases/download/libpact_ffi-v$FFI_VERSION" GREEN="\e[32m" diff --git a/docs/plugin-interactions.md b/docs/plugin-interactions.md index 269b41105..589d1cc9d 100644 --- a/docs/plugin-interactions.md +++ b/docs/plugin-interactions.md @@ -16,7 +16,7 @@ Plugins live under `~/.pact/plugins/-` and are installed with the [plugin CLI](https://docs.pact.io/implementation_guides/pact_plugins/cli), for example: ```shell -pact-plugin-cli install https://github.com/pact-foundation/pact-protobuf-plugin/releases/tag/v-0.4.0 +pact-plugin-cli install https://github.com/pact-foundation/pact-protobuf-plugin/releases/tag/v-0.8.0 ``` Sample @@ -45,7 +45,7 @@ public class GreeterClientTests : IDisposable Outputters = new[] { new XunitOutput(output) } }); - this.pact = v4.WithSynchronousPluginInteractions("protobuf", "0.4.0", transport: "grpc"); + this.pact = v4.WithSynchronousPluginInteractions("protobuf", "0.8.0", transport: "grpc"); } [Fact] diff --git a/docs/upgrading-to-5.md b/docs/upgrading-to-5.md index 8e9d4dd06..bcbcfbe90 100644 --- a/docs/upgrading-to-5.md +++ b/docs/upgrading-to-5.md @@ -132,3 +132,18 @@ MacOS ARM64 Full Support ------------------------ MacOS now has full x86-64 and ARM support. + +HTTP Request Headers with Multiple Values +----------------------------------------- + +With `libpact_ffi` 0.5.10, a request header configured as separate values can mismatch +the single comma-separated value sent by an HTTP client. Configure the expected header +as the joined value instead: + +```csharp +.WithHeader("X-Request", "request1, request2") +``` + +This replaces separate calls such as `.WithHeader("X-Request", "request1")` and +`.WithHeader("X-Request", "request2")` when those values are sent together in one +request header. diff --git a/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClientTest.cs b/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClientTest.cs index 7ac50bb7d..66e202e99 100644 --- a/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClientTest.cs +++ b/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClientTest.cs @@ -33,7 +33,7 @@ public GrpcGreeterClientTests(ITestOutputHelper output) }; this.pact = Pact.V4("grpc-greeter-client", "grpc-greeter", config) - .WithSynchronousPluginInteractions("protobuf", "0.4.0", transport: "grpc"); + .WithSynchronousPluginInteractions("protobuf", "0.8.0", transport: "grpc"); } [Fact] diff --git a/samples/Grpc/pacts/grpc-greeter-client-grpc-greeter.json b/samples/Grpc/pacts/grpc-greeter-client-grpc-greeter.json index c2318c69d..008d99628 100644 --- a/samples/Grpc/pacts/grpc-greeter-client-grpc-greeter.json +++ b/samples/Grpc/pacts/grpc-greeter-client-grpc-greeter.json @@ -12,14 +12,22 @@ "pending": false, "pluginConfiguration": { "protobuf": { - "descriptorKey": "e8e1fe144f808b9b0faecd7b2605efea", - "service": "Greeter/SayHello" + "descriptorKey": "d779ad0dfd0c93ac53c5b1f6fa648d76", + "expectations": { + "request": { + "name": "matching(equalTo, 'foo')" + }, + "response": { + "message": "matching(equalTo, 'Hello foo')" + } + }, + "service": ".greet.Greeter/SayHello" } }, "request": { "contents": { "content": "CgNmb28=", - "contentType": "application/protobuf;message=HelloRequest", + "contentType": "application/protobuf;message=.greet.HelloRequest", "contentTypeHint": "BINARY", "encoded": "base64" }, @@ -36,14 +44,14 @@ } }, "metadata": { - "contentType": "application/protobuf;message=HelloRequest" + "contentType": "application/protobuf;message=.greet.HelloRequest" } }, "response": [ { "contents": { "content": "CglIZWxsbyBmb28=", - "contentType": "application/protobuf;message=HelloReply", + "contentType": "application/protobuf;message=.greet.HelloReply", "contentTypeHint": "BINARY", "encoded": "base64" }, @@ -60,7 +68,7 @@ } }, "metadata": { - "contentType": "application/protobuf;message=HelloReply" + "contentType": "application/protobuf;message=.greet.HelloReply" } } ], @@ -70,9 +78,9 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "mockserver": "1.2.11", - "models": "1.2.8" + "ffi": "0.5.10", + "mockserver": "0.5.10", + "models": "1.3.16" }, "pactSpecification": { "version": "4.0" @@ -80,13 +88,17 @@ "plugins": [ { "configuration": { + "d779ad0dfd0c93ac53c5b1f6fa648d76": { + "protoDescriptors": "CvsECgtncmVldC5wcm90bxIFZ3JlZXQiIgoMSGVsbG9SZXF1ZXN0EhIKBG5hbWUYASABKAlSBG5hbWUiJgoKSGVsbG9SZXBseRIYCgdtZXNzYWdlGAEgASgJUgdtZXNzYWdlMj0KB0dyZWV0ZXISMgoIU2F5SGVsbG8SEy5ncmVldC5IZWxsb1JlcXVlc3QaES5ncmVldC5IZWxsb1JlcGx5QhSqAhFHcnBjR3JlZXRlckNsaWVudEq7AwoGEgQAABQBCggKAQISAwQADgo9CgIEABIEDQAPARoxIFRoZSByZXF1ZXN0IG1lc3NhZ2UgY29udGFpbmluZyB0aGUgdXNlcidzIG5hbWUuCgoKCgMEAAESAw0IFAoLCgQEAAIAEgMOAhIKDAoFBAACAAESAw4JDQoMCgUEAAIAAxIDDhARCgwKBQQAAgAFEgMOAggKPAoCBAESBBIAFAEaMCBUaGUgcmVzcG9uc2UgbWVzc2FnZSBjb250YWluaW5nIHRoZSBncmVldGluZ3MuCgoKCgMEAQESAxIIEgoLCgQEAQIAEgMTAhUKDAoFBAECAAESAxMJEAoMCgUEAQIAAxIDExMUCgwKBQQBAgAFEgMTAggKLgoCBgASBAcACgEaIiBUaGUgZ3JlZXRpbmcgc2VydmljZSBkZWZpbml0aW9uLgoKCgoDBgABEgMHCA8KHwoEBgACABIDCQIzGhIgU2VuZHMgYSBncmVldGluZwoKDAoFBgACAAESAwkGDgoMCgUGAAIAAhIDCRAcCgwKBQYAAgADEgMJJzEKCAoBCBIDAgAuCgkKAgglEgMCAC4KCAoBDBIDAAASYgZwcm90bzM=", + "protoFile": "syntax = \"proto3\";\r\n\r\noption csharp_namespace = \"GrpcGreeterClient\";\r\n\r\npackage greet;\r\n\r\n// The greeting service definition.\r\nservice Greeter {\r\n // Sends a greeting\r\n rpc SayHello (HelloRequest) returns (HelloReply);\r\n}\r\n\r\n// The request message containing the user's name.\r\nmessage HelloRequest {\r\n string name = 1;\r\n}\r\n\r\n// The response message containing the greetings.\r\nmessage HelloReply {\r\n string message = 1;\r\n}\r\n" + }, "e8e1fe144f808b9b0faecd7b2605efea": { "protoDescriptors": "Cr0BCgtncmVldC5wcm90bxIFZ3JlZXQiIgoMSGVsbG9SZXF1ZXN0EhIKBG5hbWUYASABKAlSBG5hbWUiJgoKSGVsbG9SZXBseRIYCgdtZXNzYWdlGAEgASgJUgdtZXNzYWdlMj0KB0dyZWV0ZXISMgoIU2F5SGVsbG8SEy5ncmVldC5IZWxsb1JlcXVlc3QaES5ncmVldC5IZWxsb1JlcGx5QhSqAhFHcnBjR3JlZXRlckNsaWVudGIGcHJvdG8z", "protoFile": "syntax = \"proto3\";\r\n\r\noption csharp_namespace = \"GrpcGreeterClient\";\r\n\r\npackage greet;\r\n\r\n// The greeting service definition.\r\nservice Greeter {\r\n // Sends a greeting\r\n rpc SayHello (HelloRequest) returns (HelloReply);\r\n}\r\n\r\n// The request message containing the user's name.\r\nmessage HelloRequest {\r\n string name = 1;\r\n}\r\n\r\n// The response message containing the greetings.\r\nmessage HelloReply {\r\n string message = 1;\r\n}\r\n" } }, "name": "protobuf", - "version": "0.4.0" + "version": "0.8.0" } ] }, 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 2a79a1b1e..26a73b190 100644 --- a/samples/OrdersApi/Consumer.Tests/pacts/Fulfilment API-Orders API.json +++ b/samples/OrdersApi/Consumer.Tests/pacts/Fulfilment API-Orders API.json @@ -161,9 +161,9 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "mockserver": "1.2.11", - "models": "1.2.8" + "ffi": "0.5.10", + "mockserver": "2.2.6", + "models": "1.3.16" }, "pactSpecification": { "version": "4.0" diff --git a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs index e8a6098f8..caf548fa6 100644 --- a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs +++ b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs @@ -42,8 +42,7 @@ public async Task HttpInteraction_v3_CreatesPactFile() interaction.Given("provider state"); interaction.GivenWithParam("state with param", "foo", "bar"); interaction.WithRequest("POST", "/path"); - interaction.WithRequestHeader("X-Request-Header", "request1", 0); - interaction.WithRequestHeader("X-Request-Header", "request2", 1); + interaction.WithRequestHeader("X-Request-Header", "request1, request2", 0); interaction.WithQueryParameter("param", "value", 0); interaction.WithRequestBody("application/json", @"{""foo"":42}"); diff --git a/tests/PactNet.Tests/PactExtensionsTests.cs b/tests/PactNet.Tests/PactExtensionsTests.cs index 160205b9b..f47c0a12e 100644 --- a/tests/PactNet.Tests/PactExtensionsTests.cs +++ b/tests/PactNet.Tests/PactExtensionsTests.cs @@ -82,8 +82,7 @@ public async Task WithHttpInteractions_V2_CreatesExpectedPactFile() builder.UponReceiving("a sample request") .Given("a provider state") .WithRequest(HttpMethod.Post, "/things") - .WithHeader("X-Request", "request1") - .WithHeader("X-Request", "request2") + .WithHeader("X-Request", "request1, request2") .WithQuery("param", "value1") .WithQuery("param", "value2") .WithJsonBody(this.matcher) @@ -119,8 +118,7 @@ public async Task WithHttpInteractions_V3_CreatesExpectedPactFile() ["baz"] = "bash" }) .WithRequest(HttpMethod.Post, "/things") - .WithHeader("X-Request", "request1") - .WithHeader("X-Request", "request2") + .WithHeader("X-Request", "request1, request2") .WithQuery("param", "value1") .WithQuery("param", "value2") .WithJsonBody(this.matcher) @@ -156,8 +154,7 @@ public async Task WithHttpInteractions_V4_CreatesExpectedPactFile() ["baz"] = "bash" }) .WithRequest(HttpMethod.Post, "/things") - .WithHeader("X-Request", "request1") - .WithHeader("X-Request", "request2") + .WithHeader("X-Request", "request1, request2") .WithQuery("param", "value1") .WithQuery("param", "value2") .WithJsonBody(this.matcher) @@ -247,8 +244,7 @@ public async Task CombinedHttpAndMessageInteractions_v4_CreatesExpectedPactFile( ["baz"] = "bash" }) .WithRequest(HttpMethod.Post, "/things") - .WithHeader("X-Request", "request1") - .WithHeader("X-Request", "request2") + .WithHeader("X-Request", "request1, request2") .WithQuery("param", "value1") .WithQuery("param", "value2") .WithJsonBody(this.matcher) diff --git a/tests/PactNet.Tests/data/v2-consumer-integration.json b/tests/PactNet.Tests/data/v2-consumer-integration.json index 7c3a57028..9400da802 100644 --- a/tests/PactNet.Tests/data/v2-consumer-integration.json +++ b/tests/PactNet.Tests/data/v2-consumer-integration.json @@ -74,9 +74,9 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "mockserver": "1.2.11", - "models": "1.2.8" + "ffi": "0.5.10", + "mockserver": "2.2.6", + "models": "1.3.16" }, "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 269da5e69..631b38832 100644 --- a/tests/PactNet.Tests/data/v3-consumer-integration.json +++ b/tests/PactNet.Tests/data/v3-consumer-integration.json @@ -130,9 +130,9 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "mockserver": "1.2.11", - "models": "1.2.8" + "ffi": "0.5.10", + "mockserver": "2.2.6", + "models": "1.3.16" }, "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 494ea2258..06ec6f253 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.10", + "models": "1.3.16" }, "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 4a3ace22b..29dc9f92b 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.10", + "models": "1.3.16" }, "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 c5050bd5b..b55fb45e4 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.10", + "models": "1.3.16" }, "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 1a3483b2a..0ded3716b 100644 --- a/tests/PactNet.Tests/data/v4-combined-integration.json +++ b/tests/PactNet.Tests/data/v4-combined-integration.json @@ -43,8 +43,7 @@ "application/json" ], "X-Request": [ - "request1", - "request2" + "request1, request2" ] }, "matchingRules": { @@ -186,8 +185,8 @@ "language": "C#" }, "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.10", + "models": "1.3.16" }, "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 5c1ee1619..46dc218e2 100644 --- a/tests/PactNet.Tests/data/v4-consumer-integration.json +++ b/tests/PactNet.Tests/data/v4-consumer-integration.json @@ -43,8 +43,7 @@ "application/json" ], "X-Request": [ - "request1", - "request2" + "request1, request2" ] }, "matchingRules": { @@ -151,9 +150,9 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "mockserver": "1.2.11", - "models": "1.2.8" + "ffi": "0.5.10", + "mockserver": "2.2.6", + "models": "1.3.16" }, "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 8861180b5..5d42d89eb 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.10", + "models": "1.3.16" }, "pactSpecification": { "version": "4.0" From 0e8d48f2f3176a794740f79a93a1c5d52926da1b Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Mon, 12 Oct 2026 17:48:17 +0100 Subject: [PATCH 18/35] chore(ffi): use pact-ffi 0.5.10 for Avro async verification Upgrade the Avro async branch native package bootstrap from pact-ffi 0.4.27 to released 0.5.10. The extension's Avro provider verification returned HTTP 200 but plugin content comparison failed with a transport error on Windows under 0.4.27. Repacking the same PactNet source against 0.5.10 makes all five Avro sample tests pass locally, including provider matching and the expected provider mismatch. All five supported runtime libraries download with published SHA-256 verification. Other legacy PactNet fixture tests may need fixture metadata updates before the general branch suite runs against 0.5.10; this branch change is the Avro async bootstrap prerequisite. --- build/download-native-libs.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/download-native-libs.sh b/build/download-native-libs.sh index c3ace8918..eb3f6b1bf 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.10" FFI_BASE_URL="https://github.com/pact-foundation/pact-reference/releases/download/libpact_ffi-v$FFI_VERSION" GREEN="\e[32m" From c7f45bb6ab71765db96a1ab8814747d2d8e37878 Mon Sep 17 00:00:00 2001 From: Max Lancaster Date: Mon, 12 Oct 2026 20:06:05 +0200 Subject: [PATCH 19/35] ci: Install Pact plugins in separate step --- .github/workflows/ci.yml | 5 ++ build/install-plugins.sh | 131 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 136 insertions(+) create mode 100644 build/install-plugins.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dda963e0c..05b44792d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -60,6 +60,11 @@ jobs: run: sudo apt-get install --yes protobuf-compiler if: ${{ matrix.os == 'ubuntu-24.04-arm' }} + # Pre-install the plugins the tests need so that parallel test projects + # don't race each other auto-downloading them on first use + - name: Install Pact plugins + run: bash -c "build/install-plugins.sh" + - name: Restore run: dotnet restore diff --git a/build/install-plugins.sh b/build/install-plugins.sh new file mode 100644 index 000000000..a84c0633e --- /dev/null +++ b/build/install-plugins.sh @@ -0,0 +1,131 @@ +#!/usr/bin/env bash +# +# Installs the Pact plugins required by the test suite into the Pact plugin +# directory (~/.pact/plugins by default, or $PACT_PLUGIN_DIR if set). +# +# The plugin driver will auto-download missing plugins on first use, but when +# several test projects run in parallel they race each other: one process +# writes the plugin manifest while another sees the manifest, assumes the +# plugin is installed, and fails to start the not-yet-downloaded binary. +# Installing up front avoids that race. +set -euo pipefail + +PROTOBUF_PLUGIN_VERSION="0.8.0" + +GREEN="\e[32m" +YELLOW="\e[33m" +BLUE="\e[34m" +CLEAR="\e[0m" + +plugins_dir="${PACT_PLUGIN_DIR:-$HOME/.pact/plugins}" + +detect_os() { + case "$OSTYPE" in + linux*) echo "linux" ;; + darwin*) echo "macos" ;; + msys*|cygwin*|win32) echo "windows" ;; + *) + echo "Unsupported OS: $OSTYPE" >&2 + exit 1 + ;; + esac +} + +detect_arch() { + case "$(uname -m)" in + x86_64|amd64) echo "x86_64" ;; + aarch64|arm64) echo "aarch64" ;; + *) + echo "Unsupported architecture: $(uname -m)" >&2 + exit 1 + ;; + esac +} + +sha256_of() { + if [[ "$OSTYPE" == "darwin"* ]]; then + shasum -a 256 "$1" | cut -d ' ' -f 1 + else + sha256sum "$1" | cut -d ' ' -f 1 + fi +} + +# install_plugin +# +# Downloads the plugin manifest and the platform-specific binary for the +# given plugin release into "$plugins_dir/-". +install_plugin() { + name="$1" + version="$2" + base_url="$3" + binary="$4" + + os=$(detect_os) + arch=$(detect_arch) + + extension="" + if [[ "$os" == "windows" ]]; then + extension=".exe" + fi + + # e.g. + # pact-protobuf-plugin-linux-aarch64.gz + # pact-protobuf-plugin-macos-x86_64.gz + # pact-protobuf-plugin-windows-x86_64.exe.gz + src_file="$binary-$os-$arch$extension" + src_archive="$src_file.gz" + dest_file="$binary$extension" + plugin_dir="$plugins_dir/$name-$version" + + echo -e "Installing Pact plugin ${YELLOW}$name $version${CLEAR} for ${YELLOW}$os/$arch${CLEAR}" + echo -e " Destination: ${BLUE}$plugin_dir${CLEAR}" + + if [[ -x "$plugin_dir/$dest_file" ]]; then + echo -e " Already installed, ${GREEN}skipping${CLEAR}" + echo "" + return + fi + + mkdir -p "$plugin_dir" + pushd "$plugin_dir" > /dev/null + + echo -e " URL: ${BLUE}$base_url/$src_archive${CLEAR}" + + echo -n " Downloading... " + curl --silent --fail -L "$base_url/$src_archive" -o "$src_archive" + curl --silent --fail -L "$base_url/$src_archive.sha256" -o "$src_archive.sha256" + echo -e "${GREEN}OK${CLEAR}" + + # The published .sha256 files contain an absolute path from the release + # machine, so compare the hash directly instead of using --check + echo -n " Verifying... " + expected=$(cut -d ' ' -f 1 "$src_archive.sha256") + actual=$(sha256_of "$src_archive") + if [[ "$expected" != "$actual" ]]; then + echo "FAILED (expected $expected, got $actual)" >&2 + exit 1 + fi + echo -e "${GREEN}OK${CLEAR}" + + echo -n " Extracting... " + gunzip -f "$src_archive" + mv "$src_file" "$dest_file" + chmod +x "$dest_file" + rm "$src_archive.sha256" + echo -e "${GREEN}OK${CLEAR}" + + # The manifest is written last so a partially-installed plugin is never + # mistaken for a complete one by the plugin driver + echo -n " Writing manifest... " + curl --silent --fail -L "$base_url/pact-plugin.json" -o "pact-plugin.json" + echo -e "${GREEN}OK${CLEAR}" + echo "" + + popd > /dev/null +} + +install_plugin "protobuf" "$PROTOBUF_PLUGIN_VERSION" \ + "https://github.com/pactflow/pact-protobuf-plugin/releases/download/v-$PROTOBUF_PLUGIN_VERSION" \ + "pact-protobuf-plugin" + +echo "Successfully installed Pact plugins" From 6e28aef31b06912ada285e40a9e82b001d787e4a Mon Sep 17 00:00:00 2001 From: Max Lancaster Date: Mon, 12 Oct 2026 20:43:35 +0200 Subject: [PATCH 20/35] ci: install protobuf plugin with pact-cli instead of shell script Replace build/install-plugins.sh with the pact-foundation/pact-cli action and `pact plugin install`, as suggested in review. The plugin is still pre-installed before the tests run so parallel test projects do not race each other auto-downloading it. Co-Authored-By: Claude Fable 5.1 --- .github/workflows/ci.yml | 5 +- build/install-plugins.sh | 131 --------------------------------------- 2 files changed, 4 insertions(+), 132 deletions(-) delete mode 100644 build/install-plugins.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 05b44792d..2ad890639 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,8 +62,11 @@ jobs: # Pre-install the plugins the tests need so that parallel test projects # don't race each other auto-downloading them on first use + - name: Install Pact CLI + uses: pact-foundation/pact-cli@v0.10.8 + - name: Install Pact plugins - run: bash -c "build/install-plugins.sh" + run: pact plugin install --yes protobuf --version 0.8.0 - name: Restore run: dotnet restore diff --git a/build/install-plugins.sh b/build/install-plugins.sh deleted file mode 100644 index a84c0633e..000000000 --- a/build/install-plugins.sh +++ /dev/null @@ -1,131 +0,0 @@ -#!/usr/bin/env bash -# -# Installs the Pact plugins required by the test suite into the Pact plugin -# directory (~/.pact/plugins by default, or $PACT_PLUGIN_DIR if set). -# -# The plugin driver will auto-download missing plugins on first use, but when -# several test projects run in parallel they race each other: one process -# writes the plugin manifest while another sees the manifest, assumes the -# plugin is installed, and fails to start the not-yet-downloaded binary. -# Installing up front avoids that race. -set -euo pipefail - -PROTOBUF_PLUGIN_VERSION="0.8.0" - -GREEN="\e[32m" -YELLOW="\e[33m" -BLUE="\e[34m" -CLEAR="\e[0m" - -plugins_dir="${PACT_PLUGIN_DIR:-$HOME/.pact/plugins}" - -detect_os() { - case "$OSTYPE" in - linux*) echo "linux" ;; - darwin*) echo "macos" ;; - msys*|cygwin*|win32) echo "windows" ;; - *) - echo "Unsupported OS: $OSTYPE" >&2 - exit 1 - ;; - esac -} - -detect_arch() { - case "$(uname -m)" in - x86_64|amd64) echo "x86_64" ;; - aarch64|arm64) echo "aarch64" ;; - *) - echo "Unsupported architecture: $(uname -m)" >&2 - exit 1 - ;; - esac -} - -sha256_of() { - if [[ "$OSTYPE" == "darwin"* ]]; then - shasum -a 256 "$1" | cut -d ' ' -f 1 - else - sha256sum "$1" | cut -d ' ' -f 1 - fi -} - -# install_plugin -# -# Downloads the plugin manifest and the platform-specific binary for the -# given plugin release into "$plugins_dir/-". -install_plugin() { - name="$1" - version="$2" - base_url="$3" - binary="$4" - - os=$(detect_os) - arch=$(detect_arch) - - extension="" - if [[ "$os" == "windows" ]]; then - extension=".exe" - fi - - # e.g. - # pact-protobuf-plugin-linux-aarch64.gz - # pact-protobuf-plugin-macos-x86_64.gz - # pact-protobuf-plugin-windows-x86_64.exe.gz - src_file="$binary-$os-$arch$extension" - src_archive="$src_file.gz" - dest_file="$binary$extension" - plugin_dir="$plugins_dir/$name-$version" - - echo -e "Installing Pact plugin ${YELLOW}$name $version${CLEAR} for ${YELLOW}$os/$arch${CLEAR}" - echo -e " Destination: ${BLUE}$plugin_dir${CLEAR}" - - if [[ -x "$plugin_dir/$dest_file" ]]; then - echo -e " Already installed, ${GREEN}skipping${CLEAR}" - echo "" - return - fi - - mkdir -p "$plugin_dir" - pushd "$plugin_dir" > /dev/null - - echo -e " URL: ${BLUE}$base_url/$src_archive${CLEAR}" - - echo -n " Downloading... " - curl --silent --fail -L "$base_url/$src_archive" -o "$src_archive" - curl --silent --fail -L "$base_url/$src_archive.sha256" -o "$src_archive.sha256" - echo -e "${GREEN}OK${CLEAR}" - - # The published .sha256 files contain an absolute path from the release - # machine, so compare the hash directly instead of using --check - echo -n " Verifying... " - expected=$(cut -d ' ' -f 1 "$src_archive.sha256") - actual=$(sha256_of "$src_archive") - if [[ "$expected" != "$actual" ]]; then - echo "FAILED (expected $expected, got $actual)" >&2 - exit 1 - fi - echo -e "${GREEN}OK${CLEAR}" - - echo -n " Extracting... " - gunzip -f "$src_archive" - mv "$src_file" "$dest_file" - chmod +x "$dest_file" - rm "$src_archive.sha256" - echo -e "${GREEN}OK${CLEAR}" - - # The manifest is written last so a partially-installed plugin is never - # mistaken for a complete one by the plugin driver - echo -n " Writing manifest... " - curl --silent --fail -L "$base_url/pact-plugin.json" -o "pact-plugin.json" - echo -e "${GREEN}OK${CLEAR}" - echo "" - - popd > /dev/null -} - -install_plugin "protobuf" "$PROTOBUF_PLUGIN_VERSION" \ - "https://github.com/pactflow/pact-protobuf-plugin/releases/download/v-$PROTOBUF_PLUGIN_VERSION" \ - "pact-protobuf-plugin" - -echo "Successfully installed Pact plugins" From 08161882a24edd8ec1165a210d41d9ae9314c3e6 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Fri, 16 Oct 2026 16:46:08 +0100 Subject: [PATCH 21/35] 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 c3ace8918..0e3f275a6 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 b6f1a702c..d65ccb80d 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 9484eef44..b14775145 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 b220eb497..920fa4864 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 494ea2258..c998c7188 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 4a3ace22b..088f09f64 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 c5050bd5b..5c7453961 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 618085116..0eebe9561 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 87ef562b3..32a8d9d9b 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 8861180b5..3ed2b1aff 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 22/35] 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 000000000..40000bc62 --- /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 000000000..9b748cb2f --- /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 000000000..140e9ac08 --- /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 000000000..58fcaa609 --- /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 4999226a6..51f16adb2 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 000000000..f1747fae8 --- /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 11b99c39e..6e62a839c 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 000000000..92ea5fbb3 --- /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 92bdc9116..5f0c02f9c 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 000000000..e8cd6ea69 --- /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 32aa358fb..fc7a84d93 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 000000000..94470da80 --- /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 000000000..e9c7a692a --- /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 000000000..010d76b52 --- /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 81ab072e2..dcdc198ed 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 000000000..5c6698948 --- /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 000000000..56e979bda --- /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 23/35] 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 40000bc62..f45b72fc8 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 24/35] 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 58fcaa609..ba83fccc2 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 f1747fae8..673a40e07 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 92ea5fbb3..3f9880375 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 5f0c02f9c..f99092252 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 010d76b52..8d72744fc 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 dcdc198ed..e3a5a7929 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 25/35] 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 6fe29be58..cad2b967d 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 26/35] 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 cad2b967d..e06bf469e 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 27/35] 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 035f8f4cc..e93bbc73c 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 3f9880375..5f09d5b74 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 28/35] 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 e06bf469e..0c9df4942 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 f45b72fc8..8e5178a56 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 ba83fccc2..ff9b9d1e8 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 8d72744fc..71705aa00 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 29/35] 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 30/35] 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 9b748cb2f..334de8d37 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 673a40e07..1338b62fa 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 94470da80..7f262e1d3 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 5c6698948..dc2b85e3b 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 31/35] 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 e3a5a7929..ae965ed7b 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 160205b9b..6750ea89d 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 000000000..958710308 --- /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 000000000..3fb98df07 --- /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 32/35] 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 0c9df4942..244910def 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 334de8d37..55ed0322b 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 1338b62fa..c44bccfce 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 5f09d5b74..dd5ede063 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 f99092252..1fae3774c 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 7f262e1d3..55af2e015 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 6750ea89d..475b91c2e 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 dc2b85e3b..5efad3a97 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 958710308..2e4408a24 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 33/35] 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 ff9b9d1e8..0c4d95224 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 c44bccfce..3154c44fe 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 dd5ede063..c34620a62 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 1fae3774c..33705822a 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 71705aa00..b831411d6 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 475b91c2e..3b1c3e8f2 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 34/35] 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 244910def..a012702a3 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 35/35] 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 2e4408a24..499262951 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 3fb98df07..cfa5d3697 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"