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/docs/messaging-pacts.md b/docs/messaging-pacts.md index 6fe29be58..a012702a3 100644 --- a/docs/messaging-pacts.md +++ b/docs/messaging-pacts.md @@ -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(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 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/src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs b/src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs new file mode 100644 index 000000000..8e5178a56 --- /dev/null +++ b/src/PactNet.Abstractions/IConfiguredSyncMessageVerifier.cs @@ -0,0 +1,31 @@ +using System; +using System.Threading.Tasks; + +namespace PactNet +{ + /// + /// A configured synchronous (request/response) message type state + /// + public interface IConfiguredSyncMessageVerifier + { + /// + /// 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, 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.Abstractions/ISyncMessageBuilder.cs b/src/PactNet.Abstractions/ISyncMessageBuilder.cs new file mode 100644 index 000000000..55ed0322b --- /dev/null +++ b/src/PactNet.Abstractions/ISyncMessageBuilder.cs @@ -0,0 +1,82 @@ +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); + + /// + /// 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 + /// + /// the metadata key + /// the metadata value, e.g. a string, number, boolean or matcher + /// Fluent builder + ISyncMessageBuilderV4 WithRequestMetadata(string key, dynamic value); + + /// + /// Set a response metadata value, which is serialised as JSON + /// + /// the metadata key + /// the metadata value, e.g. a string, number, boolean or matcher + /// Fluent builder + ISyncMessageBuilderV4 WithResponseMetadata(string key, dynamic 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..0c4d95224 --- /dev/null +++ b/src/PactNet/ConfiguredSyncMessageVerifier.cs @@ -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 +{ + /// + /// 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 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 + { + NativeSyncMessage generated = this.GeneratedMessage(); + TRequest request = DeserializeContent((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); + } + } + + /// + /// 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 + { + NativeSyncMessage generated = this.GeneratedMessage(); + TRequest request = DeserializeContent((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); + } + } + + /// + /// Get the generated message, with any matchers removed and any configured generators applied + /// + /// the native message + private NativeSyncMessage GeneratedMessage() + { + string generated = this.driver.GenerateContents(); + return JsonSerializer.Deserialize(generated, NativeMessageSettings); + } + + /// + /// Check the handler's response against the configured response, applying its matching rules + /// + /// the response returned by the handler under test + private void VerifyResponse(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 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)); + } + } + + /// + /// 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 + /// + /// 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 = contents.GetProperty("content").GetRawText(); + + return JsonSerializer.Deserialize(contentString, this.config.DefaultJsonSettings); + } + } +} 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/Message/ISyncMessageInteractionDriver.cs b/src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs new file mode 100644 index 000000000..3154c44fe --- /dev/null +++ b/src/PactNet/Drivers/Message/ISyncMessageInteractionDriver.cs @@ -0,0 +1,60 @@ +namespace PactNet.Drivers +{ + /// + /// Driver for synchronous (request/response) message interactions + /// + 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 + /// + /// the key + /// the value as JSON, which may contain matchers + void WithRequestMetadata(string key, string value); + + /// + /// Set a metadata value of all the existing response messages + /// + /// the key + /// the value as JSON, which may contain matchers + 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); + + /// + /// Get the actual request and response contents, with any matchers removed and any + /// configured generators applied + /// + /// 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 new file mode 100644 index 000000000..c34620a62 --- /dev/null +++ b/src/PactNet/Drivers/Message/SyncMessageInteractionDriver.cs @@ -0,0 +1,120 @@ +using System; +using System.Runtime.InteropServices; +using System.Text.Json; +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(); + + /// + /// 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 + /// + /// 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(); + + /// + /// Get the actual request and response contents, with any matchers removed and any + /// configured generators applied + /// + /// The generated request and response contents + public string GenerateContents() + { + IntPtr pointer = NativeInterop.SyncMessageGenerateContents(this.interaction); + string body = Marshal.PtrToStringAnsi(pointer); + 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/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/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/Interop/NativeInterop.cs b/src/PactNet/Interop/NativeInterop.cs index 92bdc9116..33705822a 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 @@ -91,6 +94,18 @@ 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_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/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..55af2e015 --- /dev/null +++ b/src/PactNet/SyncMessageBuilder.cs @@ -0,0 +1,196 @@ +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; + + // 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. + /// + /// 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.WithReference(string group, string name, string value) + => WithReference(group, name, value); + + /// + ISyncMessageBuilderV4 ISyncMessageBuilderV4.WithRequestMetadata(string key, dynamic value) + => WithRequestMetadata(key, value); + + /// + ISyncMessageBuilderV4 ISyncMessageBuilderV4.WithResponseMetadata(string key, dynamic 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; + } + + /// + /// 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 + /// + /// key of the metadata + /// value of the metadata + /// Fluent builder + internal SyncMessageBuilder WithRequestMetadata(string key, dynamic value) + { + string serialised = JsonSerializer.Serialize(value, this.config.DefaultJsonSettings); + + this.driver.WithRequestMetadata(key, serialised); + + return this; + } + + /// + /// 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, dynamic value) + { + string serialised = JsonSerializer.Serialize(value, this.config.DefaultJsonSettings); + + this.responseMetadata.Add(new KeyValuePair(key, serialised)); + + 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); + + 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/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..b831411d6 --- /dev/null +++ b/tests/PactNet.Tests/ConfiguredSyncMessageVerifierTests.cs @@ -0,0 +1,221 @@ +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 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_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() + { + (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() + { + (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(); + } + + [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); + + // 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.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); + } + + 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..ae965ed7b 100644 --- a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs +++ b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs @@ -130,5 +130,44 @@ public void MessageInteraction_v3_CreatesPactFile() string expectedPactContent = File.ReadAllText("data/v3-message-integration.json").TrimEnd(); pactContents.Should().Be(expectedPactContent); } + + [Fact] + 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.WithRequestMetadata("count", "42"); + interaction.WithRequestContents("application/json", @"{""foo"":42}"); + + // 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(); + + interaction.WritePactFile(Environment.CurrentDirectory); + } + finally + { + this.WriteDriverLogs(driver); + } + + 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..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; @@ -230,6 +231,84 @@ 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" + }) + .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") }) + .WithResponseMetadata("replyTo", Match.Regex("queue-1", "^queue-")) + .WithResponseJsonContent(new { Int = Match.Integer(2), String = Match.Type("a reply") }) + .Verify(request => + { + received = request; + + // 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" }); + + 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); + } + + [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() + { + 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 +386,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/SyncMessageBuilderTests.cs b/tests/PactNet.Tests/SyncMessageBuilderTests.cs new file mode 100644 index 000000000..5efad3a97 --- /dev/null +++ b/tests/PactNet.Tests/SyncMessageBuilderTests.cs @@ -0,0 +1,174 @@ +using System; +using System.Collections.Generic; +using System.Text.Json; +using FluentAssertions; +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 WithReference_WhenCalled_AddsReference() + { + this.builder.WithReference("AsyncAPI", "operationId", "getOrder"); + + this.mockDriver.Verify(s => s.AddReference("AsyncAPI", "operationId", "getOrder")); + } + + [Fact] + public void WithRequestMetadata_WhenCalled_AddsRequestMetadata() + { + this.builder.WithRequestMetadata("poolId", "1234"); + + this.mockDriver.Verify(s => s.WithRequestMetadata("poolId", @"""1234""")); + } + + [Fact] + 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 }); + + calls.Should().Equal("contents", @"poolId=""1234""", @"region=""eu"""); + } + + [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); + } + } +} 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" 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..499262951 --- /dev/null +++ b/tests/PactNet.Tests/data/v4-sync-message-consumer-integration.json @@ -0,0 +1,128 @@ +{ + "consumer": { + "name": "PactExtensionsTests-SyncMessageConsumer-V4" + }, + "interactions": [ + { + "comments": { + "references": { + "AsyncAPI": { + "operationId": "getOrder", + "version": "123" + } + } + }, + "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.12", + "models": "1.3.17" + }, + "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..cfa5d3697 --- /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.12", + "models": "1.3.17" + }, + "pactSpecification": { + "version": "4.0" + } + }, + "provider": { + "name": "NativeDriverTests-Producer" + } +} \ No newline at end of file