Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
0816188
chore(ffi): upgrade to libpact_ffi 0.5.12
YOU54F Oct 16, 2026
aa18dc5
feat: add consumer-side support for synchronous (request/response) me…
fabio-andre-rodrigues Sep 24, 2026
94a4d8f
Refine summary comment in IConfiguredSyncMessageVerifier
fabio-andre-rodrigues Sep 24, 2026
5f055c3
refactor: rename sync message Reify() members to GenerateContents()
fabio-andre-rodrigues Sep 24, 2026
4b3b0e0
docs: document synchronous (request/response) message support
fabio-andre-rodrigues Sep 24, 2026
2a7194d
Simplify messaging pacts documentation
fabio-andre-rodrigues Sep 24, 2026
e506c0a
fix: free the native string returned by Reify/GenerateContents
fabio-andre-rodrigues Sep 25, 2026
961d1c2
feat: assert the handler's response against the configured response
fabio-andre-rodrigues Sep 28, 2026
9f64d81
chore: move sync message driver into Drivers/Message
fabio-andre-rodrigues Sep 28, 2026
e02541e
fix: typed sync message metadata, applied after the response exists
fabio-andre-rodrigues Oct 8, 2026
c22a50c
test: verify sync messages end to end on pact_ffi 0.5.10
fabio-andre-rodrigues Oct 8, 2026
29b2119
feat: add WithReference to synchronous message interactions
fabio-andre-rodrigues Oct 8, 2026
bc34c5c
feat: match the sync handler's response against the response matchers
fabio-andre-rodrigues Oct 8, 2026
b946d4f
docs: describe how sync message responses are matched
fabio-andre-rodrigues Oct 8, 2026
c1acf8d
test: bump sync message fixtures to pact-ffi 0.5.12
fabio-andre-rodrigues Oct 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build/download-native-libs.sh
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
61 changes: 61 additions & 0 deletions docs/messaging-pacts.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,64 @@ 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, PactNet feeds the
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:

```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")
.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<OrderRequest, OrderStatus>(request =>
{
OrderStatus response = this.orderLookupClient.Lookup(request);
return response;
});
}
}
```

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
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
31 changes: 31 additions & 0 deletions src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Threading.Tasks;

namespace PactNet
{
/// <summary>
/// A configured synchronous (request/response) message type state
/// </summary>
public interface IConfiguredSyncMessageVerifier
{
/// <summary>
/// Verify a request message is read and handled correctly, and that the response returned
/// by the handler matches the configured response content
/// </summary>
/// <param name="handler">The method handling the request message and producing a response</param>
/// <exception cref="Exceptions.PactMessageConsumerVerificationException">
/// The handler threw, or its response did not match the configured response content
/// </exception>
void Verify<TRequest, TResponse>(Func<TRequest, TResponse> handler);

/// <summary>
/// Verify a request message is read and handled correctly, and that the response returned
/// by the handler matches the configured response content
/// </summary>
/// <param name="handler">The method handling the request message and producing a response</param>
/// <exception cref="Exceptions.PactMessageConsumerVerificationException">
/// The handler threw, or its response did not match the configured response content
/// </exception>
Task VerifyAsync<TRequest, TResponse>(Func<TRequest, Task<TResponse>> handler);
}
}
82 changes: 82 additions & 0 deletions src/PactNet.Abstractions/ISyncMessageBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
using System.Collections.Generic;
using System.Text.Json;

namespace PactNet
{
/// <summary>
/// Build up a mock synchronous (request/response) message for a v4 message pact
/// </summary>
public interface ISyncMessageBuilderV4
{
/// <summary>
/// Add a provider state
/// </summary>
/// <param name="providerState">Provider state description</param>
/// <returns>Fluent builder</returns>
ISyncMessageBuilderV4 Given(string providerState);

/// <summary>
/// Add a provider state with one or more parameters
/// </summary>
/// <param name="providerState">Provider state description</param>
/// <param name="parameters">Provider state parameters</param>
/// <returns>Fluent builder</returns>
ISyncMessageBuilderV4 Given(string providerState, IDictionary<string, string> parameters);

/// <summary>
/// Add a reference to an external resource, e.g. an AsyncAPI operation, which is written to the
/// interaction's comments under <c>references.{group}.{name}</c>
/// </summary>
/// <param name="group">Reference group, e.g. AsyncAPI</param>
/// <param name="name">Reference name, e.g. operationId</param>
/// <param name="value">Reference value</param>
/// <returns>Fluent builder</returns>
ISyncMessageBuilderV4 WithReference(string group, string name, string value);

/// <summary>
/// Set a request metadata value, which is serialised as JSON
/// </summary>
/// <param name="key">the metadata key</param>
/// <param name="value">the metadata value, e.g. a string, number, boolean or matcher</param>
/// <returns>Fluent builder</returns>
ISyncMessageBuilderV4 WithRequestMetadata(string key, dynamic value);

/// <summary>
/// Set a response metadata value, which is serialised as JSON
/// </summary>
/// <param name="key">the metadata key</param>
/// <param name="value">the metadata value, e.g. a string, number, boolean or matcher</param>
/// <returns>Fluent builder</returns>
ISyncMessageBuilderV4 WithResponseMetadata(string key, dynamic value);

/// <summary>
/// Set the request content which is serialised as JSON
/// </summary>
/// <param name="body">Request body</param>
/// <returns>Fluent builder</returns>
ISyncMessageBuilderV4 WithRequestJsonContent(dynamic body);

/// <summary>
/// Set the request content which is serialised as JSON
/// </summary>
/// <param name="body">Request body</param>
/// <param name="settings">Custom JSON serializer settings</param>
/// <returns>Fluent builder</returns>
ISyncMessageBuilderV4 WithRequestJsonContent(dynamic body, JsonSerializerOptions settings);

/// <summary>
/// Set the response content which is serialised as JSON
/// </summary>
/// <param name="body">Response body</param>
/// <returns>Configured message</returns>
IConfiguredSyncMessageVerifier WithResponseJsonContent(dynamic body);

/// <summary>
/// Set the response content which is serialised as JSON
/// </summary>
/// <param name="body">Response body</param>
/// <param name="settings">Custom JSON serializer settings</param>
/// <returns>Configured message</returns>
IConfiguredSyncMessageVerifier WithResponseJsonContent(dynamic body, JsonSerializerOptions settings);
}
}
24 changes: 24 additions & 0 deletions src/PactNet.Abstractions/ISyncMessagePactBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
namespace PactNet
{
/// <summary>
/// Synchronous (request/response) message pact v4 Builder
/// </summary>
public interface ISyncMessagePactBuilderV4
{
/// <summary>
/// Add a new synchronous message to the pact
/// </summary>
/// <param name="description">Message description</param>
/// <returns>Fluent builder</returns>
ISyncMessageBuilderV4 ExpectsToReceive(string description);

/// <summary>
/// Add metadata information to message pact
/// </summary>
/// <param name="namespace">the parent configuration section</param>
/// <param name="name">the metadata field value</param>
/// <param name="value">the metadata field value</param>
/// <returns>Fluent builder</returns>
ISyncMessagePactBuilderV4 WithPactMetadata(string @namespace, string name, string value);
}
}
157 changes: 157 additions & 0 deletions src/PactNet/ConfiguredSyncMessageVerifier.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using PactNet.Drivers;
using PactNet.Exceptions;
using PactNet.Interop;
using PactNet.Models;

namespace PactNet
{
/// <summary>
/// Verifies a configured synchronous (request/response) message interaction
/// </summary>
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;

/// <summary>
/// Initialises a new instance of the <see cref="ConfiguredSyncMessageVerifier"/>
/// </summary>
/// <param name="driver">Pact driver</param>
/// <param name="config">Pact configuration</param>
/// <param name="version">Pact specification version</param>
internal ConfiguredSyncMessageVerifier(ISyncMessageInteractionDriver driver, PactConfig config, PactSpecification version)
{
this.driver = driver;
this.config = config;
this.version = version;
}

/// <summary>
/// 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
/// </summary>
/// <param name="handler">The method handling the request message and producing a response</param>
public void Verify<TRequest, TResponse>(Func<TRequest, TResponse> handler)
{
try
{
NativeSyncMessage generated = this.GeneratedMessage();
TRequest request = DeserializeContent<TRequest>((JsonElement)generated.Request.Contents);

TResponse actualResponse = handler(request);

this.VerifyResponse(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);
}
}

/// <summary>
/// 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
/// </summary>
/// <param name="handler">The method handling the request message and producing a response</param>
public async Task VerifyAsync<TRequest, TResponse>(Func<TRequest, Task<TResponse>> handler)
{
try
{
NativeSyncMessage generated = this.GeneratedMessage();
TRequest request = DeserializeContent<TRequest>((JsonElement)generated.Request.Contents);

TResponse actualResponse = await handler(request);

this.VerifyResponse(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);
}
}

/// <summary>
/// Get the generated message, with any matchers removed and any configured generators applied
/// </summary>
/// <returns>the native message</returns>
private NativeSyncMessage GeneratedMessage()
{
string generated = this.driver.GenerateContents();
return JsonSerializer.Deserialize<NativeSyncMessage>(generated, NativeMessageSettings);
}

/// <summary>
/// Check the handler's response against the configured response, applying its matching rules
/// </summary>
/// <param name="actualResponse">the response returned by the handler under test</param>
private void VerifyResponse<TResponse>(TResponse actualResponse)
{
string actualJson = JsonSerializer.Serialize(actualResponse, this.config.DefaultJsonSettings);
string mismatchesJson = this.driver.MatchResponseContents(0, "application/json", actualJson);

using JsonDocument mismatches = JsonDocument.Parse(mismatchesJson);

if (mismatches.RootElement.GetArrayLength() > 0)
{
IEnumerable<string> descriptions = mismatches.RootElement
.EnumerateArray()
.Select(DescribeMismatch);

throw new PactMessageConsumerVerificationException(
"The response returned by the consumer handler did not match the configured response:" +
Environment.NewLine + string.Join(Environment.NewLine, descriptions));
}
}

/// <summary>
/// Describe a mismatch returned by the FFI, e.g. "$.status: Expected 1 (Integer) to be the same type as 'shipped' (String)"
/// </summary>
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}";
}

/// <summary>
/// Deserialize the content of the request or response, with any matchers removed and any
/// configured generators applied
/// </summary>
/// <typeparam name="T">the type to deserialize the content into</typeparam>
/// <param name="contents">the generated message contents</param>
/// <returns>the deserialized content</returns>
private T DeserializeContent<T>(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 = contents.GetProperty("content").GetRawText();

return JsonSerializer.Deserialize<T>(contentString, this.config.DefaultJsonSettings);
}
}
}
7 changes: 7 additions & 0 deletions src/PactNet/Drivers/IMessagePactDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ internal interface IMessagePactDriver
/// <returns>Message interaction driver</returns>
IMessageInteractionDriver NewMessageInteraction(string description);

/// <summary>
/// Create a new synchronous (request/response) message interaction on the current pact
/// </summary>
/// <param name="description">Interaction description</param>
/// <returns>Synchronous message interaction driver</returns>
ISyncMessageInteractionDriver NewSyncMessageInteraction(string description);

/// <summary>
/// Add metadata to the message pact
/// </summary>
Expand Down
Loading