From f79aca98e85abe5f60bf329d6af4cb754ce3b681 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Thu, 29 Oct 2026 18:19:47 +0000 Subject: [PATCH 1/2] test(compat): run the V4 plugin compatibility scenarios Link features/V4/plugins from PACT_COMPAT_SUITE (skipped when unset or absent) and implement the plugin_http, plugin_message, plugin_sync_message, plugin_transport and plugin_lifecycle steps. PactNet has no public plugin API on this branch, so every scenario goes through direct pact_ffi calls (using_plugin, interaction_contents, create_mock_server_for_transport, verifier). Each scenario's route (DSL / FFI / fail) is written to plugin-routes.txt. Co-Authored-By: Claude Opus 5.5 --- .../Hooks/PluginHooks.cs | 81 +++ .../PactNet.Compatibility.Tests.csproj | 15 + .../Steps/HttpConsumerSteps.cs | 71 ++- .../Steps/PluginSteps.cs | 600 ++++++++++++++++++ .../Support/PluginFfi.cs | 70 ++ .../Support/PluginProviders.cs | 280 ++++++++ .../Support/PluginWorld.cs | 202 ++++++ 7 files changed, 1313 insertions(+), 6 deletions(-) create mode 100644 tests/PactNet.Compatibility.Tests/Hooks/PluginHooks.cs create mode 100644 tests/PactNet.Compatibility.Tests/Steps/PluginSteps.cs create mode 100644 tests/PactNet.Compatibility.Tests/Support/PluginFfi.cs create mode 100644 tests/PactNet.Compatibility.Tests/Support/PluginProviders.cs create mode 100644 tests/PactNet.Compatibility.Tests/Support/PluginWorld.cs diff --git a/tests/PactNet.Compatibility.Tests/Hooks/PluginHooks.cs b/tests/PactNet.Compatibility.Tests/Hooks/PluginHooks.cs new file mode 100644 index 00000000..34c18909 --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/Hooks/PluginHooks.cs @@ -0,0 +1,81 @@ +using System; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using PactNet.Compatibility.Tests.Support; +using Reqnroll; + +namespace PactNet.Compatibility.Tests.Hooks +{ + /// + /// V4 plugin scenarios: serialised (plugins are shared per-process in pact_ffi), torn down before the ratchet, + /// and each one's DSL/FFI route recorded to plugin-routes.txt + /// + [Binding] + public sealed class PluginHooks + { + private static readonly SemaphoreSlim Gate = new(1, 1); + + [BeforeScenario("plugin")] + public static async Task BeforePlugin(PluginWorld plugin, CompatWorld world, ScenarioContext scenario) + { + await Gate.WaitAsync(); + plugin.Active = true; + + // @wip plugin scenarios are reported as unsupported (skipped) by the ratchet + if (scenario.ScenarioInfo.CombinedTags.Contains("wip")) + { + world.Run("@wip", () => throw new NotSupportedException("@wip")); + } + } + + [AfterScenario("plugin", Order = 10)] + public static async Task AfterPlugin(PluginWorld plugin) + { + try + { + await plugin.ShutdownAsync(); + } + finally + { + Gate.Release(); + } + } + + [AfterScenario("plugin", Order = 50)] + public static void RecordRoute(PluginWorld plugin, CompatWorld world, FeatureContext feature, ScenarioContext scenario) + { + bool failed = world.Failure != null || world.Unsupported != null || scenario.TestError != null || + scenario.ScenarioExecutionStatus != ScenarioExecutionStatus.OK; + string route = failed ? "fail" : plugin.Ops.Any(o => o.StartsWith("ffi:", StringComparison.Ordinal)) ? "FFI" : "DSL"; + string ops = string.Join(",", plugin.Ops.Distinct()); + PluginWorld.Routes[(feature.FeatureInfo.Title, scenario.ScenarioInfo.Title)] = (route, ops); + } + + [AfterTestRun] + public static void WriteRoutes() + { + if (PluginWorld.Routes.IsEmpty) + { + return; + } + + var text = new StringBuilder(); + foreach (var feature in PluginWorld.Routes.GroupBy(r => r.Key.Feature).OrderBy(g => g.Key)) + { + text.AppendLine($"{feature.Key}: DSL={feature.Count(r => r.Value.Route == "DSL")} " + + $"FFI={feature.Count(r => r.Value.Route == "FFI")} fail={feature.Count(r => r.Value.Route == "fail")}"); + } + + text.AppendLine(); + foreach (var r in PluginWorld.Routes.OrderBy(r => r.Key.Feature).ThenBy(r => r.Key.Scenario)) + { + text.AppendLine($"{r.Value.Route}\t{r.Key.Feature}: {r.Key.Scenario}\t[{r.Value.Ops}]"); + } + + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "plugin-routes.txt"), text.ToString()); + } + } +} diff --git a/tests/PactNet.Compatibility.Tests/PactNet.Compatibility.Tests.csproj b/tests/PactNet.Compatibility.Tests/PactNet.Compatibility.Tests.csproj index e2db4e3f..defa483e 100644 --- a/tests/PactNet.Compatibility.Tests/PactNet.Compatibility.Tests.csproj +++ b/tests/PactNet.Compatibility.Tests/PactNet.Compatibility.Tests.csproj @@ -36,6 +36,21 @@ + + + + features/V4/plugins/%(Filename)%(Extension) + + + <_Parameter1>PluginSuiteDir + <_Parameter2>$(PACT_COMPAT_SUITE) + + + + + + + diff --git a/tests/PactNet.Compatibility.Tests/Steps/HttpConsumerSteps.cs b/tests/PactNet.Compatibility.Tests/Steps/HttpConsumerSteps.cs index 418a1a34..6c84d326 100644 --- a/tests/PactNet.Compatibility.Tests/Steps/HttpConsumerSteps.cs +++ b/tests/PactNet.Compatibility.Tests/Steps/HttpConsumerSteps.cs @@ -21,10 +21,14 @@ public sealed class HttpConsumerSteps { "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth" }; private readonly CompatWorld world; + private readonly PluginWorld plugin; + private readonly PluginSteps pluginSteps; - public HttpConsumerSteps(CompatWorld world) + public HttpConsumerSteps(CompatWorld world, PluginWorld plugin, PluginSteps pluginSteps) { this.world = world; + this.plugin = plugin; + this.pluginSteps = pluginSteps; } [Given(@"^the following HTTP interactions have been defined:$")] @@ -57,7 +61,18 @@ public Task RequestMadeWithChanges(int no, Table changes) => this.world.RunAsync }); [Then(@"^a (\d+) (?:success|error) response is returned$")] - public void ResponseReturned(int status) => this.world.Run("response status", () => + public void ResponseReturned(int status) + { + if (this.plugin.Active) + { + this.pluginSteps.ResponseStatus(status); + return; + } + + this.ResponseReturnedV1(status); + } + + private void ResponseReturnedV1(int status) => this.world.Run("response status", () => { HttpResponse response = this.RequireResponse(); CompatWorld.Check(response.Status == status, @@ -80,10 +95,32 @@ public void ContentType(string contentType) => this.world.Run("response content }); [When(@"^the pact test is done$")] - public Task PactTestDone() => this.world.RunAsync("pact test done", () => this.world.RequireSession().FinishAsync()); + public Task PactTestDone() + { + if (this.plugin.Active) + { + this.pluginSteps.PactTestDone(); + return Task.CompletedTask; + } + + return this.PactTestDoneV1(); + } + + private Task PactTestDoneV1() => this.world.RunAsync("pact test done", () => this.world.RequireSession().FinishAsync()); [Then(@"^the mock server status will be OK$")] - public void StatusOk() => this.world.Run("status OK", () => + public void StatusOk() + { + if (this.plugin.Active) + { + this.pluginSteps.StatusOk(); + return; + } + + this.StatusOkV1(); + } + + private void StatusOkV1() => this.world.Run("status OK", () => { MockServerSession session = this.RequireDone(); CompatWorld.Check(session.Ok, $"Expected the mock server status to be OK, but verification failed: {session.VerifyError?.Message}\n{session.FinalMismatches?.ToJsonString()}"); @@ -96,7 +133,18 @@ public void StatusNotOk() => this.world.Run("status NOT OK", () => }); [Then(@"^the mock server will write out a Pact file for the interactions? when done$")] - public void PactWritten() => this.world.Run("pact file written", () => + public void PactWritten() + { + if (this.plugin.Active) + { + this.pluginSteps.PactWritten(); + return; + } + + this.PactWrittenV1(); + } + + private void PactWrittenV1() => this.world.Run("pact file written", () => { MockServerSession session = this.RequireDone(); CompatWorld.Check(File.Exists(session.PactFile), $"Expected a pact file at {session.PactFile}"); @@ -214,7 +262,18 @@ public void UnexpectedRequestForPath(string method, string path) => this.world.R }); [Then(@"^the mock server status will be mismatches$")] - public void StatusMismatches() => this.world.Run("request mismatches", () => + public void StatusMismatches() + { + if (this.plugin.Active) + { + this.pluginSteps.StatusMismatches(); + return; + } + + this.StatusMismatchesV1(); + } + + private void StatusMismatchesV1() => this.world.Run("request mismatches", () => { MockServerSession session = this.RequireDone(); CompatWorld.Check(!session.Ok && session.FinalMismatches.Any(m => (string)m?["type"] == "request-mismatch"), diff --git a/tests/PactNet.Compatibility.Tests/Steps/PluginSteps.cs b/tests/PactNet.Compatibility.Tests/Steps/PluginSteps.cs new file mode 100644 index 00000000..4e36b8ae --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/Steps/PluginSteps.cs @@ -0,0 +1,600 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; +using PactNet.Compatibility.Tests.Support; +using PactNet.Interop; +using Reqnroll; +using TableRow = Reqnroll.DataTableRow; + +namespace PactNet.Compatibility.Tests.Steps +{ + /// + /// Steps for features/V4/plugins (plugin_http, plugin_message, plugin_sync_message, plugin_transport, plugin_lifecycle) + /// + [Binding] + public sealed class PluginSteps + { + private readonly CompatWorld world; + private readonly PluginWorld plugin; + + public PluginSteps(CompatWorld world, PluginWorld plugin) + { + this.world = world; + this.plugin = plugin; + } + + private void Run(string step, Action body) => this.world.Run(step, () => + { + this.RequireActive(); + body(); + }); + + private Task RunAsync(string step, Func body) => this.world.RunAsync(step, () => + { + this.RequireActive(); + return body(); + }); + + private void RequireActive() + { + if (!this.plugin.Active) + { + throw new NotSupportedException("Plugin steps only run in @plugin scenarios"); + } + } + + // ---------------------------------------------------------------- plugins + + [StepDefinition(@"^the ""([^""]*)"" plugin version ""([^""]*)"" is installed$")] + public void PluginInstalled(string name, string version) => this.Run("plugin installed", () => + { + string dir = Path.Combine(PluginWorld.PluginDir, $"{name}-{version}"); + if (!Directory.Exists(dir)) + { + throw new NotSupportedException($"Plugin {name} {version} is not installed in {PluginWorld.PluginDir}"); + } + + this.plugin.InstalledVersions[name] = version; + }); + + [StepDefinition(@"^the ""([^""]*)"" plugin is not installed$")] + public void PluginNotInstalled(string name) => this.Run("plugin not installed", () => + { + bool installed = Directory.Exists(PluginWorld.PluginDir) && + Directory.EnumerateDirectories(PluginWorld.PluginDir, name + "-*").Any(); + CompatWorld.Check(!installed, $"Plugin {name} is installed in {PluginWorld.PluginDir}"); + }); + + [StepDefinition(@"^the ""([^""]*)"" plugin is loaded for the test$")] + public void PluginLoadedAnyVersion(string name) => this.PluginLoaded(name, null); + + [StepDefinition(@"^the ""([^""]*)"" plugin version ""([^""]*)"" is loaded for the test$")] + public void PluginLoaded(string name, string version) => this.Run("plugin loaded", () => + this.plugin.LoadPlugin(name, string.IsNullOrEmpty(version) ? null : version)); + + [StepDefinition(@"^loading the plugin will fail with an error that mentions ""([^""]*)""$")] + public void LoadFails(string text) => this.Run("plugin load failed", () => + { + CompatWorld.Check(this.plugin.LoadResult is > 0, $"Expected loading the plugin to fail, got {this.plugin.LoadResult}"); + CompatWorld.Check(this.plugin.LoadError?.Contains(text) == true, $"Expected the error to mention '{text}', got '{this.plugin.LoadError}'"); + }); + + [StepDefinition(@"^the test will not have panicked$")] + public void NotPanicked() => this.Run("no panic", () => + CompatWorld.Check(this.plugin.LoadResult != 1, "The plugin load panicked")); + + [StepDefinition(@"^the plugins are cleaned up$")] + public void PluginsCleanedUp() => this.Run("plugins cleaned up", () => + { + this.plugin.Ffi("cleanup_plugins"); + PactHandle pact = this.plugin.RequirePact(); + PluginFfi.CleanupPlugins(pact); + PluginFfi.FreePactHandle(pact); + this.plugin.Pact = null; + }); + + [StepDefinition(@"^no ""([^""]*)"" plugin process will still be running$")] + public Task NoPluginProcess(string name) => this.RunAsync("no plugin process", async () => + { + for (int i = 0; i < 50; i++) + { + if (!PluginWorld.PluginProcessRunning(name)) + { + return; + } + + await Task.Delay(200); + } + + throw new CompatAssertionException($"A {name} plugin process is still running"); + }); + + // ---------------------------------------------------------------- consumer: defining interactions + + [StepDefinition(@"^an HTTP interaction is being defined for a consumer test$")] + [StepDefinition(@"^another HTTP interaction is being defined for the same consumer test$")] + public void HttpInteraction() => this.Run("HTTP interaction", () => + { + this.plugin.Ffi("new_interaction"); + PactHandle pact = this.plugin.EnsurePact(); + this.plugin.InteractionHandles.Add(NativeInterop.NewInteraction(pact, $"plugin interaction {this.plugin.InteractionHandles.Count + 1}")); + }); + + [StepDefinition(@"^a message interaction is being defined for a consumer test$")] + public void MessageInteraction() => this.Run("message interaction", () => + { + this.plugin.Ffi("new_message_interaction"); + this.plugin.InteractionHandles.Add(NativeInterop.NewMessageInteraction(this.plugin.EnsurePact(), "plugin message 1")); + }); + + [StepDefinition(@"^a synchronous message interaction is being defined for a consumer test$")] + public void SyncMessageInteraction() => this.Run("synchronous message interaction", () => + { + this.plugin.Ffi("new_sync_message_interaction"); + this.plugin.InteractionHandles.Add(PluginFfi.NewSyncMessageInteraction(this.plugin.EnsurePact(), "plugin message 1")); + }); + + [StepDefinition(@"^the HTTP request is ""([^""]*)"" ""([^""]*)""$")] + public void HttpRequest(string method, string path) => this.Run("HTTP request", () => + { + this.plugin.Ffi("with_request"); + NativeInterop.WithRequest(this.plugin.Current, method, path); + }); + + [StepDefinition(@"^the HTTP (request|response) body is set with the ""([^""]*)"" plugin for ""([^""]*)"" with:$")] + public void HttpPluginBody(string part, string name, string contentType, string contents) => this.Run("HTTP plugin body", () => + this.SetPluginContents(name, part == "request" ? InteractionPart.Request : InteractionPart.Response, contentType, contents)); + + [StepDefinition(@"^the (?:synchronous )?message contents are set with the ""([^""]*)"" plugin for ""([^""]*)"" with:$")] + public void MessagePluginContents(string name, string contentType, string contents) => this.Run("message plugin contents", () => + this.SetPluginContents(name, InteractionPart.Request, contentType, contents)); + + [StepDefinition(@"^the HTTP response body is ""([^""]*)"" with content type ""([^""]*)""$")] + public void HttpResponseBody(string body, string contentType) => this.Run("HTTP response body", () => + { + this.plugin.Ffi("with_body"); + NativeInterop.WithBody(this.plugin.Current, InteractionPart.Response, contentType, Encoding.UTF8.GetString(PluginWorld.BodyCell(body))); + }); + + private void SetPluginContents(string name, InteractionPart part, string contentType, string contents) + { + this.plugin.EnsurePlugin(name); + this.plugin.Ffi("interaction_contents"); + uint rc = PluginFfi.InteractionContents(this.plugin.Current, part, contentType, PluginWorld.PluginContents(contents)); + CompatWorld.Check(rc == 0, $"Setting the {name} plugin contents failed ({rc}): {PluginFfi.LastError()}"); + } + + // ---------------------------------------------------------------- consumer: pact file and mock servers + + [StepDefinition(@"^the Pact file for the test is generated$")] + public void PactGenerated() => this.Run("pact file generated", () => + { + this.plugin.Ffi("pact_handle_write_file"); + int rc = NativeInterop.WritePactFile(this.plugin.RequirePact(), this.plugin.PactDir, false); + CompatWorld.Check(rc == 0, $"Writing the pact file failed ({rc})"); + this.plugin.ReadPactFile(); + }); + + [StepDefinition(@"^the mock server is started with (?:the plugin interaction|all the interactions)$")] + public void MockServerStarted() => this.Run("mock server started", () => this.StartMockServer("http")); + + [StepDefinition(@"^a mock server is started for the ""([^""]*)"" transport$")] + public void MockServerForTransport(string transport) => this.Run("transport mock server started", () => this.StartMockServer(transport)); + + private void StartMockServer(string transport) + { + this.plugin.Ffi("create_mock_server_for_transport"); + int port = NativeInterop.CreateMockServerForTransport(this.plugin.RequirePact(), "127.0.0.1", 0, transport, null); + CompatWorld.Check(port > 0, $"Starting the {transport} mock server failed ({port}): {PluginFfi.LastError()}"); + this.plugin.MockServerPort = port; + } + + private int RequireMockServer() => this.plugin.MockServerPort ?? throw new InvalidOperationException("The mock server has not been started"); + + [StepDefinition(@"^a ""([^""]*)"" request is made to ""([^""]*)""$")] + public Task RequestMadeNoBody(string method, string path) => this.RequestMade(method, path, null, null); + + [StepDefinition(@"^a ""([^""]*)"" request is made to ""([^""]*)"" with content type ""([^""]*)"" and body ""([^""]*)""$")] + public Task RequestMade(string method, string path, string contentType, string body) => this.RunAsync("request made", async () => + { + byte[] bytes = string.IsNullOrEmpty(body) ? null : PluginWorld.BodyCell(body); + this.plugin.HttpResponse = await PluginProviders.HttpRequestAsync(this.RequireMockServer(), method, path, + string.IsNullOrEmpty(contentType) ? null : contentType, bytes); + }); + + [StepDefinition(@"^the response body will be ""([^""]*)""$")] + public void ResponseBody(string expected) => this.Run("response body", () => + { + byte[] actual = (this.plugin.HttpResponse ?? throw new InvalidOperationException("No request was made")).Body; + byte[] wanted = PluginWorld.BodyCell(expected); + CompatWorld.Check(BytesOrJsonEqual(wanted, actual), + $"Expected body '{Encoding.UTF8.GetString(wanted)}' but got '{Encoding.UTF8.GetString(actual)}'"); + }); + + [StepDefinition(@"^the line ""([^""]*)"" is sent to the mock server over TCP$")] + public Task TcpLineSent(string line) => this.RunAsync("TCP line sent", async () => + this.plugin.TcpReply = await PluginProviders.TcpLineAsync(this.RequireMockServer(), line)); + + [StepDefinition(@"^the line ""([^""]*)"" will be received from the mock server$")] + public void TcpLineReceived(string line) => this.Run("TCP line received", () => + CompatWorld.Check(this.plugin.TcpReply?.Trim() == line, $"Expected '{line}' but received '{this.plugin.TcpReply}'")); + + [StepDefinition(@"^the gRPC method ""([^""]*)"" is called on the mock server with an empty message$")] + public Task GrpcCalledEmpty(string method) => this.GrpcCalled(method, null); + + [StepDefinition(@"^the gRPC method ""([^""]*)"" is called on the mock server with ""([^""]*)""$")] + public Task GrpcCalled(string method, string message) => this.RunAsync("gRPC call", async () => + { + byte[] bytes = string.IsNullOrEmpty(message) ? Array.Empty() : PluginWorld.BodyCell(message); + this.plugin.GrpcResult = await PluginProviders.GrpcCallAsync(this.RequireMockServer(), method, bytes); + }); + + [StepDefinition(@"^the gRPC call will return ""([^""]*)""$")] + public void GrpcReturns(string expected) => this.Run("gRPC result", () => + { + var (status, message) = this.plugin.GrpcResult ?? throw new InvalidOperationException("No gRPC call was made"); + CompatWorld.Check(status == 0, $"Expected gRPC status OK but got {PluginProviders.GrpcStatusName(status)}"); + byte[] wanted = PluginWorld.BodyCell(expected); + CompatWorld.Check(message != null && wanted.SequenceEqual(message), + $"Expected gRPC message {Convert.ToHexString(wanted)} but got {(message == null ? "none" : Convert.ToHexString(message))}"); + }); + + [StepDefinition(@"^the gRPC call will fail with status ""([^""]*)""$")] + public void GrpcFails(string status) => this.Run("gRPC failure", () => + { + var (actual, _) = this.plugin.GrpcResult ?? throw new InvalidOperationException("No gRPC call was made"); + CompatWorld.Check(PluginProviders.GrpcStatusName(actual) == status, $"Expected gRPC status {status} but got {PluginProviders.GrpcStatusName(actual)}"); + }); + + /// Delegated from ("the pact test is done") + internal void PactTestDone() => this.Run("pact test done", () => + { + int port = this.RequireMockServer(); + this.plugin.Ffi("mock_server_matched"); + this.plugin.Matched = PluginFfi.MockServerMatched(port); + IntPtr ptr = NativeInterop.MockServerMismatches(port); + string json = ptr == IntPtr.Zero ? "[]" : Marshal.PtrToStringUTF8(ptr); + this.plugin.Mismatches = JsonNode.Parse(json ?? "[]"); + + if (this.plugin.Matched == true) + { + this.plugin.Ffi("write_pact_file"); + int rc = PluginFfi.WritePactFileForPort(port, this.plugin.PactDir, false); + CompatWorld.Check(rc == 0, $"Writing the pact file failed ({rc})"); + this.plugin.ReadPactFile(); + } + + NativeInterop.CleanupMockServer(port); + this.plugin.MockServerPort = null; + }); + + internal void StatusOk() => this.Run("status OK", () => + CompatWorld.Check(this.plugin.Matched == true, $"Expected the mock server to match, mismatches: {this.plugin.Mismatches?.ToJsonString()}")); + + internal void StatusMismatches() => this.Run("status mismatches", () => + CompatWorld.Check(this.plugin.Matched == false, "Expected mismatches, but the mock server matched")); + + internal void ResponseStatus(int status) => this.Run("response status", () => + { + var (actual, body) = this.plugin.HttpResponse ?? throw new InvalidOperationException("No request was made"); + CompatWorld.Check(actual == status, $"Expected a {status} response but got {actual}: {Encoding.UTF8.GetString(body)}"); + }); + + internal void PactWritten() => this.Run("pact file written", () => + CompatWorld.Check(this.plugin.PactJson != null && File.Exists(this.plugin.PactFile), $"Expected a pact file at {this.plugin.PactFile}")); + + [StepDefinition(@"^the mismatches will contain a mismatch with error ""(.*)""$")] + public void MismatchError(string error) => this.Run("mismatch error", () => + CompatWorld.Check(AnyStringContains(this.plugin.Mismatches, error), + $"Expected a mismatch containing '{error}', got {this.plugin.Mismatches?.ToJsonString()}")); + + // ---------------------------------------------------------------- consumer: pact file contents + + [StepDefinition(@"^the Pact file metadata will list the ""([^""]*)"" plugin with version ""([^""]*)""$")] + public void MetadataPlugin(string name, string version) => this.Run("metadata plugin", () => + { + JsonArray plugins = this.plugin.RequirePactJson()["metadata"]?["plugins"]?.AsArray(); + CompatWorld.Check(plugins?.Any(p => (string)p?["name"] == name && (string)p?["version"] == version) == true, + $"Expected metadata.plugins to list {name} {version}, got {plugins?.ToJsonString()}"); + }); + + [StepDefinition(@"^the first interaction in the pact file (request|response|contents) content type will be ""([^""]*)""$")] + public void PartContentType(string part, string contentType) => this.Run("content type", () => + { + JsonNode contents = PartContents(this.PartOf(part)); + string actual = (string)contents?["contentType"]; + CompatWorld.Check(actual == contentType, $"Expected {part} content type '{contentType}' but got '{actual}'"); + }); + + [StepDefinition(@"^the first interaction in the pact file contents will be ""([^""]*)""$")] + public void ContentsEqual(string expected) => this.PartContentsEqual("contents", expected); + + [StepDefinition(@"^the first interaction in the pact file (request|response) contents will be ""([^""]*)""$")] + public void PartContentsEqual(string part, string expected) => this.Run("contents", () => + { + JsonNode contents = PartContents(this.PartOf(string.IsNullOrEmpty(part) ? "contents" : part)); + string actual = (string)contents?["encoded"] is string enc && enc.StartsWith("base64", StringComparison.OrdinalIgnoreCase) + ? Encoding.UTF8.GetString(Convert.FromBase64String((string)contents["content"])) + : (string)contents?["content"]; + CompatWorld.Check(actual == expected, $"Expected contents '{expected}' but got '{actual}'"); + }); + + [StepDefinition(@"^the first interaction (request|response|contents) in the pact file will have a matching rule for ""([^""]*)"" of type ""([^""]*)""$")] + public void MatchingRule(string part, string key, string type) => this.Run("matching rule", () => + { + JsonNode rules = this.PartOf(part)?["matchingRules"]?["body"]?[key]?["matchers"]; + CompatWorld.Check(rules is JsonArray arr && arr.Any(m => (string)m?["match"] == type), + $"Expected a '{type}' matching rule for {key}, got {this.PartOf(part)?["matchingRules"]?.ToJsonString()}"); + }); + + [StepDefinition(@"^the first interaction in the pact file will have plugin configuration for ""([^""]*)""$")] + public void PluginConfiguration(string name) => this.Run("plugin configuration", () => + CompatWorld.Check(this.plugin.FirstInteraction()["pluginConfiguration"]?[name] != null, + $"Expected plugin configuration for {name}, got {this.plugin.FirstInteraction()["pluginConfiguration"]?.ToJsonString()}")); + + [StepDefinition(@"^the second interaction in the pact file will not have plugin configuration$")] + public void NoPluginConfiguration() => this.Run("no plugin configuration", () => + { + JsonNode config = this.plugin.RequirePactJson()["interactions"]?[1]?["pluginConfiguration"]; + CompatWorld.Check(config == null || (config is JsonObject o && o.Count == 0), $"Expected no plugin configuration, got {config?.ToJsonString()}"); + }); + + [StepDefinition(@"^the pact file will contain (\d+) interactions$")] + public void InteractionCount(int count) => this.Run("interaction count", () => + { + int actual = this.plugin.RequirePactJson()["interactions"]?.AsArray().Count ?? 0; + CompatWorld.Check(actual == count, $"Expected {count} interactions but got {actual}"); + }); + + [StepDefinition(@"^the first interaction in the Pact file will have a type of ""([^""]*)""$")] + public void InteractionType(string type) => this.Run("interaction type", () => + CompatWorld.Check((string)this.plugin.FirstInteraction()["type"] == type, $"Expected type {type}, got {this.plugin.FirstInteraction()["type"]}")); + + [StepDefinition(@"^the first interaction in the pact file will contain (\d+) response messages?$")] + public void ResponseMessages(int count) => this.Run("response messages", () => + { + int actual = this.plugin.FirstInteraction()["response"] is JsonArray a ? a.Count : 0; + CompatWorld.Check(actual == count, $"Expected {count} response messages but got {actual}"); + }); + + [StepDefinition(@"^the first interaction in the Pact file will have ""([^""]*)"" = '(.*)'$")] + public void InteractionField(string field, string json) => this.Run("interaction field", () => + { + JsonNode actual = this.plugin.FirstInteraction()[field]; + JsonNode expected = JsonNode.Parse(json); + if (field == "transport" && actual is JsonValue v && v.TryGetValue(out string s)) + { + actual = JsonValue.Create(s.Split('/').Last()); + } + + CompatWorld.Check(JsonNode.DeepEquals(expected, actual), $"Expected {field} = {json} but got {actual?.ToJsonString()}"); + }); + + private JsonNode PartOf(string part) + { + JsonNode interaction = this.plugin.FirstInteraction(); + return part switch + { + "contents" => interaction, + "response" when interaction["response"] is JsonArray arr => arr[0], + _ => interaction[part] + }; + } + + private static JsonNode PartContents(JsonNode part) => part?["contents"] ?? part?["body"]; + + // ---------------------------------------------------------------- provider: pact files + + [StepDefinition(@"^a Pact file with an HTTP ""([^""]*)"" ""([^""]*)"" interaction with plugin contents:$")] + public void HttpPactFile(string method, string path, DataTable table) => this.Run("HTTP pact file", () => + { + TableRow row = table.Rows[0]; + this.WritePactFile(row["plugin"], pact => + { + this.plugin.Ffi("new_interaction"); + InteractionHandle i = NativeInterop.NewInteraction(pact, "plugin interaction"); + NativeInterop.WithRequest(i, method, path); + foreach ((string column, InteractionPart part) in new[] { ("request", InteractionPart.Request), ("response", InteractionPart.Response) }) + { + if (row.TryGetValue(column, out string value) && !string.IsNullOrWhiteSpace(value)) + { + this.plugin.Ffi("interaction_contents"); + uint rc = PluginFfi.InteractionContents(i, part, row["content type"], PluginWorld.PluginContents(value)); + CompatWorld.Check(rc == 0, $"Setting the {column} plugin contents failed ({rc}): {PluginFfi.LastError()}"); + } + } + }); + }); + + [StepDefinition(@"^a Pact file with a ""([^""]*)"" (message|synchronous message) interaction with plugin contents:$")] + public void MessagePactFile(string description, string kind, DataTable table) => this.Run("message pact file", () => + this.WriteMessagePactFile(description, kind == "synchronous message", table.Rows[0], null)); + + [StepDefinition(@"^a Pact file with a ""([^""]*)"" synchronous message interaction over the ""([^""]*)"" transport with plugin contents:$")] + public void TransportPactFile(string description, string transport, DataTable table) => this.Run("transport pact file", () => + this.WriteMessagePactFile(description, true, table.Rows[0], transport)); + + private void WriteMessagePactFile(string description, bool sync, TableRow row, string transport) + { + string file = this.WritePactFile(row["plugin"], pact => + { + InteractionHandle i; + if (sync) + { + this.plugin.Ffi("new_sync_message_interaction"); + i = PluginFfi.NewSyncMessageInteraction(pact, description); + } + else + { + this.plugin.Ffi("new_message_interaction"); + i = NativeInterop.NewMessageInteraction(pact, description); + } + + this.plugin.Ffi("interaction_contents"); + uint rc = PluginFfi.InteractionContents(i, InteractionPart.Request, row["content type"], PluginWorld.PluginContents(row["contents"])); + CompatWorld.Check(rc == 0, $"Setting the plugin contents failed ({rc}): {PluginFfi.LastError()}"); + }); + + if (transport != null) + { + JsonNode json = JsonNode.Parse(File.ReadAllText(file)); + json["interactions"][0]["transport"] = transport; + File.WriteAllText(file, json.ToJsonString()); + } + } + + /// Build a pact with one plugin interaction on its own handle and write it out; returns the file + private string WritePactFile(string pluginName, Action define) + { + string dir = Path.Combine(this.plugin.PactDir, "provider-" + this.plugin.PactFiles.Count); + PactHandle pact = NativeInterop.NewPact(PluginWorld.Consumer, PluginWorld.Provider); + NativeInterop.WithSpecification(pact, PactSpecification.V4); + try + { + this.plugin.Ffi("using_plugin"); + this.plugin.InstalledVersions.TryGetValue(pluginName, out string version); + uint rc = PluginFfi.UsingPlugin(pact, pluginName, version); + CompatWorld.Check(rc == 0, $"Loading plugin {pluginName} failed ({rc}): {PluginFfi.LastError()}"); + define(pact); + this.plugin.Ffi("pact_handle_write_file"); + int written = NativeInterop.WritePactFile(pact, dir, false); + CompatWorld.Check(written == 0, $"Writing the pact file failed ({written})"); + } + finally + { + PluginFfi.CleanupPlugins(pact); + PluginFfi.FreePactHandle(pact); + } + + string file = Path.Combine(dir, $"{PluginWorld.Consumer}-{PluginWorld.Provider}.json"); + this.plugin.PactFiles.Add(file); + return file; + } + + // ---------------------------------------------------------------- provider: providers + + [StepDefinition(@"^a provider is started that returns ""([^""]*)"" with content type ""([^""]*)""$")] + public Task HttpProvider(string body, string contentType) => this.RunAsync("HTTP provider", async () => + this.TrackProvider(await PluginProviders.StartBodyProviderAsync(PluginWorld.BodyCell(body), contentType))); + + [StepDefinition(@"^a provider is started that can generate the ""([^""]*)"" message with ""([^""]*)"" and content type ""([^""]*)""$")] + public Task MessageProvider(string description, string body, string contentType) => this.RunAsync("message provider", async () => + this.TrackProvider(await PluginProviders.StartMessageProviderAsync(description, PluginWorld.BodyCell(body), contentType))); + + [StepDefinition(@"^a gRPC provider is started that answers ""([^""]*)"" with ""([^""]*)""$")] + public Task GrpcProvider(string method, string message) => this.RunAsync("gRPC provider", async () => + this.TrackProvider(await PluginProviders.StartGrpcProviderAsync(method, PluginWorld.BodyCell(message)))); + + [StepDefinition(@"^a TCP provider is started that replies to ""([^""]*)"" with ""([^""]*)""$")] + public void TcpProvider(string expected, string reply) => this.Run("TCP provider", () => + this.TrackProvider(PluginProviders.StartTcpLineProvider(expected, reply))); + + [StepDefinition(@"^no provider is listening$")] + public void NoProvider() => this.Run("no provider", () => this.plugin.ProviderPort = PluginProviders.FreePort()); + + private void TrackProvider((int Port, IAsyncDisposable Server) started) + { + this.plugin.ProviderPort = started.Port; + this.plugin.Servers.Add(started.Server); + } + + // ---------------------------------------------------------------- provider: verification + + [StepDefinition(@"^the verification is run$")] + public Task VerificationRunHttp() => this.VerificationRun(null); + + [StepDefinition(@"^the verification is run with the ""([^""]*)"" transport$")] + public Task VerificationRun(string transport) => this.RunAsync("verification", async () => + { + int port = this.plugin.ProviderPort ?? throw new InvalidOperationException("No provider has been started"); + this.plugin.Ffi("verifier"); + IntPtr handle = NativeInterop.VerifierNewForApplication("pact-net-compat", "0.0.0"); + try + { + NativeInterop.VerifierSetProviderInfo(handle, PluginWorld.Provider, "http", "127.0.0.1", (ushort)port, "/"); + if (!string.IsNullOrEmpty(transport)) + { + NativeInterop.AddProviderTransport(handle, transport, (ushort)port, "", transport == "grpc" ? "http" : "tcp"); + } + + foreach (string file in this.plugin.PactFiles) + { + NativeInterop.VerifierAddFileSource(handle, file); + } + + this.plugin.VerifyExitCode = await Task.Run(() => NativeInterop.VerifierExecute(handle)); + this.plugin.VerifyOutput = PluginFfi.TakeString(NativeInterop.VerifierOutput(handle, 1)) ?? string.Empty; + string json = PluginFfi.TakeString(PluginFfi.VerifierJson(handle)); + this.plugin.VerifyJson = string.IsNullOrEmpty(json) ? null : JsonNode.Parse(json); + } + finally + { + NativeInterop.VerifierShutdown(handle); + } + }); + + [StepDefinition(@"^the verification will be successful$")] + public void VerificationSuccessful() => this.Run("verification successful", () => + CompatWorld.Check(this.plugin.VerifyExitCode == 0 && (bool?)this.plugin.VerifyJson?["result"] != false, + $"Expected verification to pass (exit {this.plugin.VerifyExitCode}):\n{this.plugin.VerifyOutput}")); + + [StepDefinition(@"^the verification will NOT be successful$")] + public void VerificationFailed() => this.Run("verification NOT successful", () => + CompatWorld.Check(this.plugin.VerifyExitCode is not null and not 0 && (bool?)this.plugin.VerifyJson?["result"] != true, + $"Expected verification to fail (exit {this.plugin.VerifyExitCode}):\n{this.plugin.VerifyOutput}")); + + [StepDefinition(@"^the verification results will contain a ""([^""]*)"" error$")] + public void VerificationError(string error) => this.Run("verification error", () => + { + string[] types = error switch + { + "Body had differences" => new[] { "BodyMismatch", "BodyTypeMismatch" }, + "Metadata had differences" => new[] { "MetadataMismatch" }, + _ => new[] { error } + }; + IEnumerable found = (this.plugin.VerifyJson?["interactionResults"]?.AsArray() ?? new JsonArray()) + .SelectMany(r => r?["mismatch"]?["mismatches"]?.AsArray() ?? new JsonArray()) + .Select(m => (string)m?["type"]); + CompatWorld.Check(found.Any(t => types.Contains(t)) || this.plugin.VerifyOutput.Contains(error), + $"Expected a '{error}' error, results: {this.plugin.VerifyJson?.ToJsonString()}"); + }); + + [StepDefinition(@"^the verification output will contain ""(.*)""$")] + public void VerificationOutput(string text) => this.Run("verification output", () => + CompatWorld.Check(this.plugin.VerifyOutput?.Contains(text) == true, $"Expected the verification output to contain '{text}':\n{this.plugin.VerifyOutput}")); + + // ---------------------------------------------------------------- helpers + + private static bool BytesOrJsonEqual(byte[] expected, byte[] actual) + { + if (expected.SequenceEqual(actual)) + { + return true; + } + + try + { + return JsonNode.DeepEquals(JsonNode.Parse(expected), JsonNode.Parse(actual)); + } + catch (JsonException) + { + return false; + } + } + + private static bool AnyStringContains(JsonNode node, string text) => node switch + { + JsonObject o => o.Any(kv => AnyStringContains(kv.Value, text)), + JsonArray a => a.Any(n => AnyStringContains(n, text)), + JsonValue v when v.TryGetValue(out string s) => s.Contains(text), + _ => false + }; + } +} diff --git a/tests/PactNet.Compatibility.Tests/Support/PluginFfi.cs b/tests/PactNet.Compatibility.Tests/Support/PluginFfi.cs new file mode 100644 index 00000000..7ccec546 --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/Support/PluginFfi.cs @@ -0,0 +1,70 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; +using PactNet.Interop; + +namespace PactNet.Compatibility.Tests.Support +{ + /// + /// Plugin FFI calls PactNet does not bind (or binds only internally). Used where the PactNet DSL has no equivalent; + /// every call site records an "ffi" route in . + /// + internal static class PluginFfi + { + private const string Dll = "pact_ffi"; + + [DllImport(Dll, EntryPoint = "pactffi_using_plugin")] + public static extern uint UsingPlugin(PactHandle pact, string name, string version); + + [DllImport(Dll, EntryPoint = "pactffi_cleanup_plugins")] + public static extern void CleanupPlugins(PactHandle pact); + + [DllImport(Dll, EntryPoint = "pactffi_interaction_contents")] + public static extern uint InteractionContents(InteractionHandle interaction, InteractionPart part, string contentType, string contents); + + [DllImport(Dll, EntryPoint = "pactffi_new_sync_message_interaction")] + public static extern InteractionHandle NewSyncMessageInteraction(PactHandle pact, string description); + + [DllImport(Dll, EntryPoint = "pactffi_mock_server_matched")] + [return: MarshalAs(UnmanagedType.U1)] + public static extern bool MockServerMatched(int port); + + [DllImport(Dll, EntryPoint = "pactffi_write_pact_file")] + public static extern int WritePactFileForPort(int port, string directory, [MarshalAs(UnmanagedType.U1)] bool overwrite); + + [DllImport(Dll, EntryPoint = "pactffi_free_pact_handle")] + public static extern uint FreePactHandle(PactHandle pact); + + [DllImport(Dll, EntryPoint = "pactffi_get_error_message")] + private static extern int GetErrorMessage(byte[] buffer, int length); + + [DllImport(Dll, EntryPoint = "pactffi_verifier_json")] + public static extern IntPtr VerifierJson(IntPtr handle); + + public static string LastError() + { + byte[] buffer = new byte[4096]; + int len = GetErrorMessage(buffer, buffer.Length); + if (len <= 0) + { + return string.Empty; + } + + int end = Array.IndexOf(buffer, (byte)0); + return Encoding.UTF8.GetString(buffer, 0, end < 0 ? len : end); + } + + /// Read and free an FFI-owned string + public static string TakeString(IntPtr ptr) + { + if (ptr == IntPtr.Zero) + { + return null; + } + + string s = Marshal.PtrToStringUTF8(ptr); + NativeInterop.FreeString(ptr); + return s; + } + } +} diff --git a/tests/PactNet.Compatibility.Tests/Support/PluginProviders.cs b/tests/PactNet.Compatibility.Tests/Support/PluginProviders.cs new file mode 100644 index 00000000..0e0e5a46 --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/Support/PluginProviders.cs @@ -0,0 +1,280 @@ +using System; +using System.Buffers.Binary; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Sockets; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.Logging; + +namespace PactNet.Compatibility.Tests.Support +{ + /// + /// Throwaway providers (HTTP, message, gRPC, TCP line) and clients (HTTP, gRPC, TCP line) for the plugin scenarios + /// + internal static class PluginProviders + { + public static async Task<(int Port, IAsyncDisposable Server)> StartHttpAsync(RequestDelegate handler, bool http2 = false) + { + WebApplicationBuilder builder = WebApplication.CreateSlimBuilder(); + builder.Logging.ClearProviders(); + builder.WebHost.ConfigureKestrel(k => k.Listen(IPAddress.Loopback, 0, + l => l.Protocols = http2 ? HttpProtocols.Http2 : HttpProtocols.Http1)); + WebApplication app = builder.Build(); + app.Run(handler); + await app.StartAsync(); + int port = new Uri(app.Urls.First()).Port; + return (port, app); + } + + /// A plain HTTP provider that always returns the body + public static Task<(int Port, IAsyncDisposable Server)> StartBodyProviderAsync(byte[] body, string contentType) => + StartHttpAsync(async ctx => + { + ctx.Response.StatusCode = 200; + ctx.Response.ContentType = contentType; + await ctx.Response.Body.WriteAsync(body); + }); + + /// A message provider: the verifier POSTs the interaction description, the provider answers with the message + public static Task<(int Port, IAsyncDisposable Server)> StartMessageProviderAsync(string description, byte[] body, string contentType) => + StartHttpAsync(async ctx => + { + string requested = null; + try + { + using JsonDocument doc = await JsonDocument.ParseAsync(ctx.Request.Body); + requested = doc.RootElement.TryGetProperty("description", out JsonElement d) ? d.GetString() : null; + } + catch (JsonException) + { + } + + if (!string.Equals(ctx.Request.Method, "POST", StringComparison.OrdinalIgnoreCase) || requested != description) + { + ctx.Response.StatusCode = 404; + return; + } + + string metadata = Convert.ToBase64String(Encoding.UTF8.GetBytes(new JsonObject { ["contentType"] = contentType }.ToJsonString())); + ctx.Response.StatusCode = 200; + ctx.Response.ContentType = contentType; + ctx.Response.Headers["pact-message-metadata"] = metadata; + await ctx.Response.Body.WriteAsync(body); + }); + + /// An h2c gRPC provider answering one method with a fixed message + public static Task<(int Port, IAsyncDisposable Server)> StartGrpcProviderAsync(string method, byte[] message) => + StartHttpAsync(async ctx => + { + using (var drain = new MemoryStream()) + { + await ctx.Request.Body.CopyToAsync(drain); + } + + ctx.Response.StatusCode = 200; + ctx.Response.ContentType = "application/grpc"; + if (ctx.Request.Path.Value == method) + { + await ctx.Response.Body.WriteAsync(GrpcFrame(message)); + ctx.Response.AppendTrailer("grpc-status", "0"); + } + else + { + ctx.Response.AppendTrailer("grpc-status", "12"); + } + }, http2: true); + + /// A TCP provider replying to one line + public static (int Port, IAsyncDisposable Server) StartTcpLineProvider(string expected, string reply) + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var cts = new CancellationTokenSource(); + _ = Task.Run(async () => + { + while (!cts.IsCancellationRequested) + { + TcpClient client; + try + { + client = await listener.AcceptTcpClientAsync(cts.Token); + } + catch + { + return; + } + + _ = Task.Run(async () => + { + using (client) + { + try + { + NetworkStream stream = client.GetStream(); + using var reader = new StreamReader(stream, Encoding.UTF8, false, 1024, leaveOpen: true); + string line; + while ((line = await reader.ReadLineAsync(cts.Token)) != null) + { + string answer = line.Trim() == expected ? reply : "MATTerrorMATT"; + byte[] bytes = Encoding.UTF8.GetBytes(answer + "\n"); + await stream.WriteAsync(bytes, cts.Token); + await stream.FlushAsync(cts.Token); + } + } + catch + { + // connection dropped + } + } + }); + } + }); + + int port = ((IPEndPoint)listener.LocalEndpoint).Port; + return (port, new ActionDisposable(() => + { + cts.Cancel(); + listener.Stop(); + })); + } + + /// A port nothing listens on + public static int FreePort() + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + int port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + return port; + } + + public static async Task<(int Status, byte[] Body)> HttpRequestAsync(int port, string method, string path, string contentType, byte[] body) + { + using var client = new HttpClient(); + using var request = new HttpRequestMessage(new HttpMethod(method), $"http://127.0.0.1:{port}{path}"); + if (body != null) + { + request.Content = new ByteArrayContent(body); + if (contentType != null) + { + request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); + } + } + + using HttpResponseMessage response = await client.SendAsync(request); + return ((int)response.StatusCode, await response.Content.ReadAsByteArrayAsync()); + } + + /// Unary gRPC call over h2c. Returns the gRPC status and the response message (null when none) + public static async Task<(int Status, byte[] Message)> GrpcCallAsync(int port, string method, byte[] message) + { + Exception last = null; + foreach (string host in new[] { "127.0.0.1", "[::1]" }) + { + try + { + using var client = new HttpClient(); + using var request = new HttpRequestMessage(HttpMethod.Post, $"http://{host}:{port}{method}") + { + Version = HttpVersion.Version20, + VersionPolicy = HttpVersionPolicy.RequestVersionExact, + Content = new ByteArrayContent(GrpcFrame(message)) + }; + request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/grpc"); + request.Headers.TryAddWithoutValidation("te", "trailers"); + + using HttpResponseMessage response = await client.SendAsync(request); + byte[] body = await response.Content.ReadAsByteArrayAsync(); + string status = response.TrailingHeaders.TryGetValues("grpc-status", out var t) ? t.First() + : response.Headers.TryGetValues("grpc-status", out var h) ? h.First() : "0"; + byte[] reply = body.Length >= 5 ? body.Skip(5).ToArray() : null; + return (int.Parse(status), reply); + } + catch (HttpRequestException e) + { + last = e; + } + } + + throw last!; + } + + /// Send one line over TCP and read one line back (null when nothing comes back) + public static async Task TcpLineAsync(int port, string line) + { + Exception last = null; + foreach (IPAddress address in new[] { IPAddress.Loopback, IPAddress.IPv6Loopback }) + { + using var client = new TcpClient(address.AddressFamily); + try + { + await client.ConnectAsync(address, port); + } + catch (SocketException e) + { + last = e; + continue; + } + + NetworkStream stream = client.GetStream(); + await stream.WriteAsync(Encoding.UTF8.GetBytes(line + "\n")); + await stream.FlushAsync(); + using var reader = new StreamReader(stream, Encoding.UTF8); + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + try + { + return await reader.ReadLineAsync(cts.Token); + } + catch (Exception) + { + return null; + } + } + + throw last!; + } + + public static string GrpcStatusName(int status) => status switch + { + 0 => "OK", + 3 => "INVALID_ARGUMENT", + 5 => "NOT_FOUND", + 9 => "FAILED_PRECONDITION", + 12 => "UNIMPLEMENTED", + 13 => "INTERNAL", + _ => status.ToString() + }; + + private static byte[] GrpcFrame(byte[] message) + { + var frame = new byte[5 + message.Length]; + BinaryPrimitives.WriteUInt32BigEndian(frame.AsSpan(1), (uint)message.Length); + message.CopyTo(frame, 5); + return frame; + } + + private sealed class ActionDisposable : IAsyncDisposable + { + private readonly Action action; + + public ActionDisposable(Action action) => this.action = action; + + public ValueTask DisposeAsync() + { + this.action(); + return ValueTask.CompletedTask; + } + } + } +} diff --git a/tests/PactNet.Compatibility.Tests/Support/PluginWorld.cs b/tests/PactNet.Compatibility.Tests/Support/PluginWorld.cs new file mode 100644 index 00000000..c0ff26ef --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/Support/PluginWorld.cs @@ -0,0 +1,202 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Text.Json.Nodes; +using System.Threading.Tasks; +using PactNet.Interop; + +namespace PactNet.Compatibility.Tests.Support +{ + /// + /// Per-scenario state for the V4 plugin features, plus a record of which scenarios went through the PactNet DSL + /// and which needed direct FFI calls + /// + public sealed class PluginWorld + { + public const string Consumer = "c"; + public const string Provider = "p"; + + /// (feature, scenario) -> (route, ops) + internal static readonly ConcurrentDictionary<(string Feature, string Scenario), (string Route, string Ops)> Routes = new(); + + private readonly List ops = new(); + + /// Set for scenarios tagged @plugin, so steps shared with the V1 features delegate here + public bool Active { get; set; } + + internal string PactDir { get; } = Path.Combine(AppContext.BaseDirectory, "pacts", "plugins", Guid.NewGuid().ToString("N")); + + internal string PactFile => Path.Combine(this.PactDir, $"{Consumer}-{Provider}.json"); + + internal Dictionary InstalledVersions { get; } = new(); + + // consumer side (FFI) + internal PactHandle? Pact { get; set; } + + internal List InteractionHandles { get; } = new(); + + internal HashSet LoadedPlugins { get; } = new(); + + internal uint? LoadResult { get; set; } + + internal string LoadError { get; set; } + + internal int? MockServerPort { get; set; } + + internal bool? Matched { get; set; } + + internal JsonNode Mismatches { get; set; } + + internal JsonNode PactJson { get; set; } + + // client results + internal (int Status, byte[] Body)? HttpResponse { get; set; } + + internal (int Status, byte[] Message)? GrpcResult { get; set; } + + internal string TcpReply { get; set; } + + // provider side + internal List PactFiles { get; } = new(); + + internal int? ProviderPort { get; set; } + + internal List Servers { get; } = new(); + + internal int? VerifyExitCode { get; set; } + + internal string VerifyOutput { get; set; } + + internal JsonNode VerifyJson { get; set; } + + /// A step went through a direct FFI call PactNet has no public API for + internal void Ffi(string op) => this.ops.Add("ffi:" + op); + + /// A step went through the PactNet DSL + internal void Dsl(string op) => this.ops.Add("dsl:" + op); + + internal IReadOnlyList Ops => this.ops; + + internal static string SuiteDir { get; } = + Environment.GetEnvironmentVariable("PACT_COMPAT_SUITE") is { Length: > 0 } env + ? env + : typeof(PluginWorld).Assembly.GetCustomAttributes() + .FirstOrDefault(a => a.Key == "PluginSuiteDir")?.Value; + + internal static string Fixture(string name) => Path.Combine(SuiteDir, "fixtures", name); + + /// A body cell: "file: X" reads the suite fixture, anything else is the literal text + internal static byte[] BodyCell(string value) => + value.StartsWith("file: ", StringComparison.Ordinal) + ? File.ReadAllBytes(Fixture(value.Substring("file: ".Length).Trim())) + : Encoding.UTF8.GetBytes(value); + + /// Plugin contents may reference suite fixtures as "fixture:path" + internal static string PluginContents(string contents) => + contents.Replace("\"fixture:", "\"" + Path.Combine(SuiteDir, "fixtures") + "/"); + + internal static string PluginDir => + Environment.GetEnvironmentVariable("PACT_PLUGIN_DIR") is { Length: > 0 } dir + ? dir + : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".pact", "plugins"); + + internal static bool PluginProcessRunning(string name) + { + using var p = Process.Start(new ProcessStartInfo("pgrep", new[] { "-f", $"{PluginDir}/{name}-" }) + { + RedirectStandardOutput = true, + RedirectStandardError = true + })!; + p.WaitForExit(); + return p.ExitCode == 0; + } + + internal PactHandle RequirePact() => this.Pact ?? throw new InvalidOperationException("No interaction is being defined"); + + internal InteractionHandle Current => + this.InteractionHandles.Count > 0 ? this.InteractionHandles[^1] : throw new InvalidOperationException("No interaction is being defined"); + + internal JsonNode RequirePactJson() => this.PactJson ?? throw new InvalidOperationException("No pact file has been written"); + + internal JsonNode FirstInteraction() => this.RequirePactJson()["interactions"]?[0] ?? throw new InvalidOperationException("The pact file has no interactions"); + + /// Lazily create the consumer pact handle (V4) + internal PactHandle EnsurePact() + { + if (this.Pact == null) + { + PactHandle pact = NativeInterop.NewPact(Consumer, Provider); + NativeInterop.WithSpecification(pact, PactSpecification.V4); + this.Pact = pact; + } + + return this.Pact.Value; + } + + internal void LoadPlugin(string name, string version) + { + this.Ffi("using_plugin"); + uint rc = PluginFfi.UsingPlugin(this.EnsurePact(), name, version); + this.LoadResult = rc; + if (rc == 0) + { + this.LoadedPlugins.Add(name); + } + else + { + this.LoadError = PluginFfi.LastError(); + } + } + + internal void EnsurePlugin(string name) + { + if (!this.LoadedPlugins.Contains(name)) + { + this.InstalledVersions.TryGetValue(name, out string version); + this.LoadPlugin(name, version); + CompatWorld.Check(this.LoadResult == 0, $"Loading plugin {name} {version} failed ({this.LoadResult}): {this.LoadError}"); + } + } + + internal void ReadPactFile() + { + CompatWorld.Check(File.Exists(this.PactFile), $"Expected a pact file at {this.PactFile}"); + this.PactJson = JsonNode.Parse(File.ReadAllText(this.PactFile)); + } + + internal async Task ShutdownAsync() + { + foreach (IAsyncDisposable server in this.Servers) + { + try + { + await server.DisposeAsync(); + } + catch + { + // best effort + } + } + + this.Servers.Clear(); + + if (this.MockServerPort is int port) + { + NativeInterop.CleanupMockServer(port); + this.MockServerPort = null; + } + + if (this.Pact is PactHandle pact) + { + PluginFfi.CleanupPlugins(pact); + PluginFfi.FreePactHandle(pact); + this.Pact = null; + } + } + } +} From 69dac556aef29965e73f3686cd09563e219435fc Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Thu, 29 Oct 2026 19:36:56 +0000 Subject: [PATCH 2/2] ci: run the V4 plugin compatibility features Adds compat-plugins.yml, which checks out the suite branch with features/V4/plugins, installs the four plugins and runs the V4.Plugins tests. It runs on PRs to any base, so stacked PRs are covered. Also reads verification mismatches from "errors" in the verifier JSON, which is where FFI 0.4.27 reports them; 10 scenarios failed without it. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/compat-plugins.yml | 86 +++++++++++++++++++ .../Steps/PluginSteps.cs | 4 +- 2 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/compat-plugins.yml diff --git a/.github/workflows/compat-plugins.yml b/.github/workflows/compat-plugins.yml new file mode 100644 index 00000000..3735308c --- /dev/null +++ b/.github/workflows/compat-plugins.yml @@ -0,0 +1,86 @@ +name: Compatibility suite (V4 plugins) + +# The V4 plugin features are not in the pinned suite submodule yet, so this +# checks out the suite branch that adds them and runs the V4.Plugins tests in +# PactNet.Compatibility.Tests against it. It runs on PRs to any base, unlike ci.yml. +on: + push: + branches: + - master + pull_request: + workflow_dispatch: + inputs: + suite-repository: + description: pact-compatibility-suite repository with features/V4/plugins + default: YOU54F/pact-compatibility-suite + suite-ref: + description: Ref of that repository to run + default: feat/plugin-features + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true + DOTNET_CLI_TELEMETRY_OPTOUT: true + PACT_DO_NOT_TRACK: 'true' + SUITE_REPOSITORY: ${{ inputs.suite-repository || 'YOU54F/pact-compatibility-suite' }} + SUITE_REF: ${{ inputs.suite-ref || 'feat/plugin-features' }} + +jobs: + plugins: + name: V4 plugins (Linux) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + submodules: true + + - name: Checkout plugin suite + uses: actions/checkout@v7 + with: + repository: ${{ env.SUITE_REPOSITORY }} + ref: ${{ env.SUITE_REF }} + path: pact-compatibility-suite-plugins + + # PactNet.Compatibility.Tests targets net10.0. + - name: Setup .NET Core SDK + uses: actions/setup-dotnet@v6 + with: + dotnet-version: "10.0.x" + + - name: Cache FFI dependencies + id: cache + uses: actions/cache@v6 + with: + key: cache-ffi-${{ hashFiles('build/download-native-libs.sh') }} + enableCrossOsArchive: true + path: | + build/linux + build/macos + build/windows + + - name: Pull interop dependencies + run: bash -c "build/download-native-libs.sh" + if: ${{ steps.cache.outputs.cache-hit != 'true' }} + + - name: Install the Pact CLI + uses: pact-foundation/pact-cli@ce8e65692ad3ea9d11244749ae24c8c49225d95f # main + + - name: Install plugins + run: | + # matt is not in the plugin repository index, so it is installed from its release. + pact plugin install https://github.com/mefellows/pact-matt-plugin/releases/tag/v0.1.1 -y + pact plugin install csv --version 0.0.6 -y + pact plugin install avro --version 0.1.3 -y + pact plugin install protobuf --version 0.8.0 -y + + # PACT_COMPAT_SUITE is read at build time too, to include the plugin feature files. + - name: Run plugin features + run: dotnet test tests/PactNet.Compatibility.Tests --filter "FullyQualifiedName~.V4.Plugins." --verbosity normal + env: + PACT_COMPAT_SUITE: ${{ github.workspace }}/pact-compatibility-suite-plugins diff --git a/tests/PactNet.Compatibility.Tests/Steps/PluginSteps.cs b/tests/PactNet.Compatibility.Tests/Steps/PluginSteps.cs index 4e36b8ae..b0e83fde 100644 --- a/tests/PactNet.Compatibility.Tests/Steps/PluginSteps.cs +++ b/tests/PactNet.Compatibility.Tests/Steps/PluginSteps.cs @@ -559,7 +559,9 @@ public void VerificationError(string error) => this.Run("verification error", () "Metadata had differences" => new[] { "MetadataMismatch" }, _ => new[] { error } }; - IEnumerable found = (this.plugin.VerifyJson?["interactionResults"]?.AsArray() ?? new JsonArray()) + // The verifier JSON lists failures under "errors"; older versions used "interactionResults". + IEnumerable found = new[] { "errors", "interactionResults" } + .SelectMany(key => this.plugin.VerifyJson?[key]?.AsArray() ?? new JsonArray()) .SelectMany(r => r?["mismatch"]?["mismatches"]?.AsArray() ?? new JsonArray()) .Select(m => (string)m?["type"]); CompatWorld.Check(found.Any(t => types.Contains(t)) || this.plugin.VerifyOutput.Contains(error),