diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..ea94360a --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "tests/PactNet.Compatibility.Tests/pact-compatibility-suite"] + path = tests/PactNet.Compatibility.Tests/pact-compatibility-suite + url = https://github.com/pact-foundation/pact-compatibility-suite.git diff --git a/PactNet.sln b/PactNet.sln index 243019fa..bf51cdb0 100644 --- a/PactNet.sln +++ b/PactNet.sln @@ -37,6 +37,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PactNet.Output.Xunit", "src\PactNet.Output.Xunit\PactNet.Output.Xunit.csproj", "{02E265A1-A7A2-4106-8F6A-5027FDC3FC50}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PactNet.Compatibility.Tests", "tests\PactNet.Compatibility.Tests\PactNet.Compatibility.Tests.csproj", "{063989E4-6B3A-4BA1-BDDD-72B105B9919C}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -155,6 +157,18 @@ Global {02E265A1-A7A2-4106-8F6A-5027FDC3FC50}.Release|x64.Build.0 = Release|Any CPU {02E265A1-A7A2-4106-8F6A-5027FDC3FC50}.Release|x86.ActiveCfg = Release|Any CPU {02E265A1-A7A2-4106-8F6A-5027FDC3FC50}.Release|x86.Build.0 = Release|Any CPU + {063989E4-6B3A-4BA1-BDDD-72B105B9919C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {063989E4-6B3A-4BA1-BDDD-72B105B9919C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {063989E4-6B3A-4BA1-BDDD-72B105B9919C}.Debug|x64.ActiveCfg = Debug|Any CPU + {063989E4-6B3A-4BA1-BDDD-72B105B9919C}.Debug|x64.Build.0 = Debug|Any CPU + {063989E4-6B3A-4BA1-BDDD-72B105B9919C}.Debug|x86.ActiveCfg = Debug|Any CPU + {063989E4-6B3A-4BA1-BDDD-72B105B9919C}.Debug|x86.Build.0 = Debug|Any CPU + {063989E4-6B3A-4BA1-BDDD-72B105B9919C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {063989E4-6B3A-4BA1-BDDD-72B105B9919C}.Release|Any CPU.Build.0 = Release|Any CPU + {063989E4-6B3A-4BA1-BDDD-72B105B9919C}.Release|x64.ActiveCfg = Release|Any CPU + {063989E4-6B3A-4BA1-BDDD-72B105B9919C}.Release|x64.Build.0 = Release|Any CPU + {063989E4-6B3A-4BA1-BDDD-72B105B9919C}.Release|x86.ActiveCfg = Release|Any CPU + {063989E4-6B3A-4BA1-BDDD-72B105B9919C}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -170,6 +184,7 @@ Global {5E915D66-917B-4730-B31A-C9727C196346} = {6663C12E-9912-40D0-9310-D119D1F6B023} {D8B75E48-6E45-468B-8049-B73823C14CB8} = {6663C12E-9912-40D0-9310-D119D1F6B023} {02E265A1-A7A2-4106-8F6A-5027FDC3FC50} = {CF67D7A1-AE96-420B-9971-65E535B903E8} + {063989E4-6B3A-4BA1-BDDD-72B105B9919C} = {A117BBC6-60BB-4282-BF10-E616DE0AFAD0} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {C2CBC30C-92D4-4E3A-A5B8-1E5D4E938DFC} diff --git a/README.md b/README.md index c70c541b..27cc2dd2 100644 --- a/README.md +++ b/README.md @@ -251,6 +251,24 @@ Due to using a shared native library instead of C# for the main Pact logic only | 4.x | Deprecated | 2, 3 | See [installation] | | 3.x | Deprecated | 2 | | +### Pact Compatibility Suite + +`tests/PactNet.Compatibility.Tests` runs the shared [pact-compatibility-suite](https://github.com/pact-foundation/pact-compatibility-suite) +feature files (a git submodule) against PactNet using [Reqnroll](https://reqnroll.net). Only the V1 HTTP consumer +steps are implemented so far; scenarios with undefined steps are reported as skipped (unsupported), not failed. + +```bash +git submodule update --init +./build/download-native-libs.sh # or copy a libpact_ffi into build/// +dotnet test tests/PactNet.Compatibility.Tests --logger "junit;LogFilePath=TestResults/compat-junit.xml" +``` + +- `PACT_FFI_LIB=/path/to/libpact_ffi.{so,dylib,dll}` runs the suite against a different FFI build than the bundled one. +- `tests/PactNet.Compatibility.Tests/baseline.yaml` is a ratchet of scenarios that are known to fail, each with a reason. + A run fails when a scenario that is not in the baseline fails, or when a baselined scenario starts passing. + Rerun with `COMPAT_UPDATE_BASELINE=1` to rewrite it (existing reasons are kept); `COMPAT_BASELINE_FILE` points at a different file. +- The JUnit report lands in `tests/PactNet.Compatibility.Tests/TestResults/`; a plain-text summary is written to `compat-summary.txt` in the test output directory. + ## Roadmap The [roadmap](https://docs.pact.io/roadmap/) for Pact and Pact Net is outlined on our main website. diff --git a/src/PactNet/AssemblyInfo.cs b/src/PactNet/AssemblyInfo.cs index c29bd8a9..e1f9a47d 100644 --- a/src/PactNet/AssemblyInfo.cs +++ b/src/PactNet/AssemblyInfo.cs @@ -1,2 +1,3 @@ [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("PactNet.Tests")] +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("PactNet.Compatibility.Tests")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/PactNet.Compatibility.Tests/Hooks/CompatHooks.cs b/tests/PactNet.Compatibility.Tests/Hooks/CompatHooks.cs new file mode 100644 index 00000000..efc74102 --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/Hooks/CompatHooks.cs @@ -0,0 +1,173 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using PactNet.Compatibility.Tests.Support; +using Reqnroll; +using Reqnroll.UnitTestProvider; + +namespace PactNet.Compatibility.Tests.Hooks +{ + /// + /// Native library override, per-scenario cleanup and the baseline ratchet + /// + [Binding] + public sealed class CompatHooks + { + private static readonly ConcurrentDictionary<(string Feature, string Scenario), (string Outcome, string Detail)> Results = new(); + + private static Baseline baseline; + + private static bool UpdateMode => Environment.GetEnvironmentVariable("COMPAT_UPDATE_BASELINE") == "1"; + + [BeforeTestRun] + public static void BeforeTestRun() + { + NativeLibraryOverride.Install(); + baseline = Baseline.Load(CompatPaths.BaselineFile); + } + + [AfterScenario(Order = 0)] + public static async Task CleanUp(CompatWorld world) + { + if (world.Session != null) + { + await world.Session.DisposeAsync(); + world.Session = null; + } + } + + [AfterScenario(Order = 100)] + public static void Ratchet(CompatWorld world, FeatureContext feature, ScenarioContext scenario, IUnitTestRuntimeProvider runtime) + { + string featureKey = FeatureKey(feature.FeatureInfo); + string scenarioKey = scenario.ScenarioInfo.Title; + + ScenarioExecutionStatus status = scenario.ScenarioExecutionStatus; + string outcome; + string detail; + + // Reqnroll itself skips scenarios with undefined/pending steps; calling TestIgnore again would turn that into a failure + bool reqnrollSkips = status is ScenarioExecutionStatus.UndefinedStep or ScenarioExecutionStatus.StepDefinitionPending; + + if (reqnrollSkips || world.Unsupported != null) + { + outcome = "unsupported"; + detail = world.Unsupported?.Message ?? $"undefined step(s) ({status})"; + } + else if (world.Failure != null || scenario.TestError != null) + { + outcome = "failing"; + Exception error = world.Failure ?? scenario.TestError; + detail = $"step '{world.FailedStep}': {error.GetType().Name}: {error.Message}"; + } + else + { + outcome = "passed"; + detail = null; + } + + Results[(featureKey, scenarioKey)] = (outcome, detail); + + if (UpdateMode) + { + if (!reqnrollSkips && outcome != "passed") + { + runtime.TestIgnore($"[{outcome}] {detail}"); + } + + return; + } + + BaselineEntry entry = baseline.Find(featureKey, scenarioKey); + + switch (outcome) + { + case "unsupported" when !reqnrollSkips: + // tolerated: reported as skipped, never fails the run + runtime.TestIgnore($"Unsupported: {detail}"); + break; + + case "unsupported": + // undefined/pending steps: Reqnroll already marks the test as skipped (missingOrPendingStepsOutcome = Ignore) + break; + + case "failing" when entry == null: + throw new CompatAssertionException( + $"Scenario failed and is not in the baseline ({featureKey}: {scenarioKey})\n{detail}"); + + case "failing": + runtime.TestIgnore($"Baselined ({entry.Status}): {entry.Reason}\nActual: {detail}"); + break; + + case "passed" when entry != null: + throw new CompatAssertionException( + $"Scenario now passes but is listed in the baseline ({featureKey}: {scenarioKey}); remove it from baseline.yaml or rerun with COMPAT_UPDATE_BASELINE=1"); + } + } + + [AfterTestRun] + public static void AfterTestRun() + { + var counts = Results.Values.GroupBy(r => r.Outcome).ToDictionary(g => g.Key, g => g.Count()); + var summary = new StringBuilder(); + summary.AppendLine($"pact_ffi: {NativeLibraryOverride.LibraryPath ?? "(bundled)"}"); + summary.AppendLine($"scenarios: {Results.Count}"); + + foreach (string key in new[] { "passed", "failing", "unsupported" }) + { + summary.AppendLine($"{key}: {counts.GetValueOrDefault(key)}"); + } + + foreach (var result in Results.Where(r => r.Value.Outcome == "failing").OrderBy(r => r.Key.Feature).ThenBy(r => r.Key.Scenario)) + { + summary.AppendLine($"FAILING {result.Key.Feature}: {result.Key.Scenario} -- {result.Value.Detail}"); + } + + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "compat-summary.txt"), summary.ToString()); + + if (UpdateMode) + { + WriteBaseline(); + } + } + + private static void WriteBaseline() + { + var entries = new List(); + + // scenarios not executed in this run (e.g. filtered out) keep their entries + entries.AddRange(baseline.Entries.Where(e => !Results.ContainsKey((e.Feature, e.Scenario)))); + + foreach (var result in Results.Where(r => r.Value.Outcome == "failing")) + { + BaselineEntry existing = baseline.Find(result.Key.Feature, result.Key.Scenario); + entries.Add(new BaselineEntry + { + Feature = result.Key.Feature, + Scenario = result.Key.Scenario, + Status = "failing", + Reason = existing?.Reason ?? $"not yet triaged: {result.Value.Detail}" + }); + } + + Baseline.Write(CompatPaths.BaselineFile, entries); + } + + private static string FeatureKey(FeatureInfo info) + { + string folder = (info.FolderPath ?? string.Empty).Replace('\\', '/').Trim('/'); + // e.g. "pact-compatibility-suite/features/V1" -> "V1" + int features = folder.LastIndexOf("features", StringComparison.OrdinalIgnoreCase); + if (features >= 0) + { + folder = folder.Substring(features + "features".Length).Trim('/'); + } + + return string.IsNullOrEmpty(folder) ? info.Title : $"{folder}/{info.Title}"; + } + } +} diff --git a/tests/PactNet.Compatibility.Tests/PactNet.Compatibility.Tests.csproj b/tests/PactNet.Compatibility.Tests/PactNet.Compatibility.Tests.csproj new file mode 100644 index 00000000..e2db4e3f --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/PactNet.Compatibility.Tests.csproj @@ -0,0 +1,55 @@ + + + + net10.0 + false + true + latest + disable + + false + + true + + $(MSBuildProjectDirectory)/compat.runsettings + $(MSBuildProjectDirectory)/pact-compatibility-suite + + + + + + features/%(RecursiveDir)%(Filename)%(Extension) + + + + + + + + + <_Parameter1>CompatSuiteDir + <_Parameter2>$(CompatSuiteDir) + + + <_Parameter1>CompatProjectDir + <_Parameter2>$(MSBuildProjectDirectory) + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + diff --git a/tests/PactNet.Compatibility.Tests/Steps/HttpConsumerSteps.cs b/tests/PactNet.Compatibility.Tests/Steps/HttpConsumerSteps.cs new file mode 100644 index 00000000..418a1a34 --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/Steps/HttpConsumerSteps.cs @@ -0,0 +1,328 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading.Tasks; +using PactNet.Compatibility.Tests.Support; +using Reqnroll; + +namespace PactNet.Compatibility.Tests.Steps +{ + /// + /// Steps for the HTTP consumer features (written against features/V1/http_consumer.feature) + /// + [Binding] + public sealed class HttpConsumerSteps + { + private static readonly string[] Ordinals = + { "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth" }; + + private readonly CompatWorld world; + + public HttpConsumerSteps(CompatWorld world) + { + this.world = world; + } + + [Given(@"^the following HTTP interactions have been defined:$")] + public void InteractionsDefined(Table table) => this.world.Run("interactions defined", () => + { + this.world.Interactions = InteractionDefinition.FromTable(table); + }); + + [When(@"^the mock server is started with interactions? ""?([\d, ]+)""?$")] + public Task MockServerStarted(string numbers) => this.world.RunAsync("start mock server", async () => + { + List selected = numbers.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(n => this.world.Interaction(int.Parse(n))) + .ToList(); + + this.world.Session = await MockServerSession.StartAsync(selected); + }); + + [When(@"^request (\d+) is made to the mock server$")] + public Task RequestMade(int no) => this.world.RunAsync($"request {no}", async () => + { + this.world.Response = await this.world.RequireSession().SendAsync(this.world.Interaction(no)); + }); + + [When(@"^request (\d+) is made to the mock server with the following changes:$")] + public Task RequestMadeWithChanges(int no, Table changes) => this.world.RunAsync($"request {no} with changes", async () => + { + InteractionDefinition request = this.world.Interaction(no).WithChanges(changes); + this.world.Response = await this.world.RequireSession().SendAsync(request); + }); + + [Then(@"^a (\d+) (?:success|error) response is returned$")] + public void ResponseReturned(int status) => this.world.Run("response status", () => + { + HttpResponse response = this.RequireResponse(); + CompatWorld.Check(response.Status == status, + $"Expected a {status} response but got {response.Status}: {Encoding.UTF8.GetString(response.Body)}"); + }); + + [Then(@"^the payload will contain the ""([^""]*)"" JSON document$")] + public void PayloadJson(string name) => this.world.Run("payload JSON document", () => + { + JsonNode expected = JsonNode.Parse(File.ReadAllText(CompatPaths.Fixture(name + ".json"))); + JsonNode actual = JsonNode.Parse(this.RequireResponse().Body); + CompatWorld.Check(JsonNode.DeepEquals(expected, actual), $"Expected payload {expected?.ToJsonString()} but got {actual?.ToJsonString()}"); + }); + + [Then(@"^the content type will be set as ""([^""]*)""$")] + public void ContentType(string contentType) => this.world.Run("response content type", () => + { + string actual = this.RequireResponse().ContentType; + CompatWorld.Check(MediaTypeEquals(actual, contentType), $"Expected content type '{contentType}' but got '{actual}'"); + }); + + [When(@"^the pact test is done$")] + public Task PactTestDone() => 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", () => + { + 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()}"); + }); + + [Then(@"^the mock server status will NOT be OK$")] + public void StatusNotOk() => this.world.Run("status NOT OK", () => + { + CompatWorld.Check(!this.RequireDone().Ok, "Expected the mock server status to NOT be OK, but verification passed"); + }); + + [Then(@"^the mock server will write out a Pact file for the interactions? when done$")] + public void PactWritten() => this.world.Run("pact file written", () => + { + MockServerSession session = this.RequireDone(); + CompatWorld.Check(File.Exists(session.PactFile), $"Expected a pact file at {session.PactFile}"); + }); + + [Then(@"^the mock server will NOT write out a Pact file for the interactions? when done$")] + public void PactNotWritten() => this.world.Run("pact file not written", () => + { + MockServerSession session = this.RequireDone(); + CompatWorld.Check(!File.Exists(session.PactFile), $"Expected no pact file, but found {session.PactFile}"); + }); + + [Then(@"^the pact file will contain \{(\d+)\} interactions?$")] + public void PactInteractionCount(int count) => this.world.Run("pact interaction count", () => + { + JsonArray interactions = this.PactInteractions(); + CompatWorld.Check(interactions.Count == count, $"Expected {count} interaction(s) in the pact file but found {interactions.Count}"); + }); + + [Then(@"^the \{(\w+)\} interaction request will be for a ""([^""]*)""$")] + public void InteractionMethod(string ordinal, string method) => this.world.Run("pact request method", () => + { + string actual = (string)this.PactInteraction(ordinal)["request"]?["method"]; + CompatWorld.Check(string.Equals(actual, method, StringComparison.OrdinalIgnoreCase), $"Expected request method '{method}' but the pact has '{actual}'"); + }); + + [Then(@"^the \{(\w+)\} interaction request query parameters will be ""([^""]*)""$")] + public void InteractionQuery(string ordinal, string query) => this.world.Run("pact request query", () => + { + JsonNode actual = this.PactInteraction(ordinal)["request"]?["query"]; + var expected = InteractionDefinition.ParseQuery(query); + var actualPairs = actual switch + { + null => new List>(), + JsonValue v => InteractionDefinition.ParseQuery((string)v), + JsonObject o => o.SelectMany(p => p.Value is JsonArray a + ? a.Select(x => new KeyValuePair(p.Key, (string)x)) + : new[] { new KeyValuePair(p.Key, (string)p.Value) }).ToList(), + _ => throw new CompatAssertionException($"Unexpected query representation {actual.ToJsonString()}") + }; + + CompatWorld.Check(expected.OrderBy(p => p.Key).SequenceEqual(actualPairs.OrderBy(p => p.Key)), + $"Expected query '{query}' but the pact has {actual?.ToJsonString()}"); + }); + + [Then(@"^the \{(\w+)\} interaction request will contain the header ""([^""]*)"" with value ""([^""]*)""$")] + public void InteractionHeader(string ordinal, string name, string value) => this.world.Run("pact request header", () => + { + JsonNode headers = this.PactInteraction(ordinal)["request"]?["headers"]; + string actual = HeaderValue(headers, name); + CompatWorld.Check(actual == value, $"Expected header '{name}: {value}' but the pact has {headers?.ToJsonString()}"); + }); + + [Then(@"^the \{(\w+)\} interaction request content type will be ""([^""]*)""$")] + public void InteractionContentType(string ordinal, string contentType) => this.world.Run("pact request content type", () => + { + JsonNode request = this.PactInteraction(ordinal)["request"]; + string actual = HeaderValue(request?["headers"], "Content-Type") ?? (string)request?["body"]?["contentType"]; + CompatWorld.Check(MediaTypeEquals(actual, contentType), $"Expected request content type '{contentType}' but the pact has '{actual}'"); + }); + + [Then(@"^the \{(\w+)\} interaction (request|response) will contain the ""([^""]*)"" document$")] + public void InteractionDocument(string ordinal, string part, string name) => this.world.Run($"pact {part} document", () => + { + BodyDefinition expected = BodyDefinition.FromFixture(name); + JsonNode actual = this.PactInteraction(ordinal)[part]?["body"]; + + // V4 pacts wrap the body as {content, contentType, encoded} + if (actual is JsonObject wrapper && wrapper.ContainsKey("content") && wrapper.ContainsKey("contentType")) + { + actual = wrapper["content"]; + } + + if (expected.ContentType.Contains("json", StringComparison.OrdinalIgnoreCase)) + { + JsonNode expectedJson = JsonNode.Parse(expected.Bytes); + JsonNode actualJson = actual is JsonValue v && v.TryGetValue(out string text) ? JsonNode.Parse(text) : actual; + CompatWorld.Check(JsonNode.DeepEquals(expectedJson, actualJson), + $"Expected {part} body {expectedJson?.ToJsonString()} but the pact has {actual?.ToJsonString()}"); + } + else + { + string actualText = actual is JsonValue v && v.TryGetValue(out string s) ? s : actual?.ToJsonString(); + CompatWorld.Check(actualText == expected.Text, $"Expected {part} body '{expected.Text}' but the pact has '{actualText}'"); + } + }); + + [Then(@"^the mock server status will be an expected but not received error for interaction \{(\d+)\}$")] + public void ExpectedNotReceived(int no) => this.world.Run("missing request mismatch", () => + { + InteractionDefinition interaction = this.world.Interaction(no); + JsonArray mismatches = this.RequireDone().FinalMismatches; + + CompatWorld.Check(mismatches.Any(m => (string)m?["type"] == "missing-request" && RequestMatches(m, interaction.Method, interaction.Path)), + $"Expected a missing-request mismatch for {interaction.Method} {interaction.Path}, got {mismatches.ToJsonString()}"); + }); + + [Then(@"^the mock server status will be an unexpected ""([^""]*)"" request received error for interaction \{(\d+)\}$")] + public void UnexpectedRequestForInteraction(string method, int no) => this.world.Run("unexpected request mismatch", () => + { + InteractionDefinition interaction = this.world.Interaction(no); + JsonArray mismatches = this.RequireDone().FinalMismatches; + + CompatWorld.Check(mismatches.Any(m => (string)m?["type"] == "request-not-found" && RequestMatches(m, method, interaction.Path)), + $"Expected a request-not-found mismatch for {method} {interaction.Path}, got {mismatches.ToJsonString()}"); + }); + + [Then(@"^the mock server status will be an unexpected ""([^""]*)"" request received error for path ""([^""]*)""$")] + public void UnexpectedRequestForPath(string method, string path) => this.world.Run("unexpected request mismatch", () => + { + JsonArray mismatches = this.RequireDone().FinalMismatches; + + CompatWorld.Check(mismatches.Any(m => (string)m?["type"] == "request-not-found" && RequestMatches(m, method, path)), + $"Expected a request-not-found mismatch for {method} {path}, got {mismatches.ToJsonString()}"); + }); + + [Then(@"^the mock server status will be mismatches$")] + public void StatusMismatches() => this.world.Run("request mismatches", () => + { + MockServerSession session = this.RequireDone(); + CompatWorld.Check(!session.Ok && session.FinalMismatches.Any(m => (string)m?["type"] == "request-mismatch"), + $"Expected request mismatches, got {session.FinalMismatches?.ToJsonString()}"); + }); + + [Then(@"^the mismatches will contain a ""([^""]*)"" mismatch with error ""(.*)""$")] + public void MismatchWithError(string kind, string error) => this.world.Run($"{kind} mismatch", () => + { + this.AssertMismatch(kind, null, error); + }); + + [Then(@"^the mismatches will contain a ""([^""]*)"" mismatch with path ""([^""]*)"" with error ""(.*)""$")] + public void MismatchWithPathAndError(string kind, string path, string error) => this.world.Run($"{kind} mismatch", () => + { + this.AssertMismatch(kind, path, error); + }); + + private void AssertMismatch(string kind, string path, string error) + { + JsonArray mismatches = this.world.RequireSession().LiveMismatches(); + + IEnumerable details = mismatches.SelectMany(m => m?["mismatches"] as JsonArray ?? new JsonArray()); + + bool found = details.Any(d => + { + string type = ((string)d?["type"] ?? string.Empty).ToLowerInvariant(); + bool typeMatches = kind == "body-content-type" + ? type == "bodytypemismatch" + : type.StartsWith(kind.Replace("-", string.Empty).ToLowerInvariant(), StringComparison.Ordinal); + + if (!typeMatches || !((string)d["mismatch"] ?? string.Empty).Contains(error, StringComparison.Ordinal)) + { + return false; + } + + if (path == null) + { + return true; + } + + string location = (string)d["path"] ?? (string)d["key"] ?? (string)d["parameter"]; + return location == path; + }); + + CompatWorld.Check(found, $"Expected a '{kind}' mismatch{(path == null ? string.Empty : $" at '{path}'")} with error \"{error}\", got {mismatches.ToJsonString()}"); + } + + private static bool RequestMatches(JsonNode mismatch, string method, string path) + { + string actualMethod = (string)mismatch["method"] ?? (string)mismatch["request"]?["method"]; + string actualPath = (string)mismatch["path"] ?? (string)mismatch["request"]?["path"]; + return string.Equals(actualMethod, method, StringComparison.OrdinalIgnoreCase) && actualPath == path; + } + + private static string HeaderValue(JsonNode headers, string name) + { + if (headers is not JsonObject obj) + { + return null; + } + + foreach (KeyValuePair header in obj) + { + if (header.Key.Equals(name, StringComparison.OrdinalIgnoreCase)) + { + return header.Value is JsonArray values ? string.Join(", ", values.Select(v => (string)v)) : (string)header.Value; + } + } + + return null; + } + + private static bool MediaTypeEquals(string actual, string expected) + { + static string Strip(string ct) => ct?.Split(';')[0].Trim(); + return string.Equals(Strip(actual), Strip(expected), StringComparison.OrdinalIgnoreCase); + } + + private HttpResponse RequireResponse() => + this.world.Response ?? throw new InvalidOperationException("No request has been made to the mock server"); + + private MockServerSession RequireDone() + { + MockServerSession session = this.world.RequireSession(); + return session.IsDone ? session : throw new InvalidOperationException("The pact test has not been marked as done"); + } + + private JsonArray PactInteractions() + { + MockServerSession session = this.RequireDone(); + CompatWorld.Check(File.Exists(session.PactFile), $"No pact file was written to {session.PactFile}"); + + JsonNode pact = JsonNode.Parse(File.ReadAllText(session.PactFile)); + return pact?["interactions"] as JsonArray ?? new JsonArray(); + } + + private JsonNode PactInteraction(string ordinal) + { + int index = Array.IndexOf(Ordinals, ordinal.ToLowerInvariant()); + if (index < 0) + { + throw new NotSupportedException($"Unknown ordinal '{ordinal}'"); + } + + JsonArray interactions = this.PactInteractions(); + CompatWorld.Check(index < interactions.Count, $"The pact file has {interactions.Count} interaction(s), no {ordinal} interaction"); + return interactions[index]; + } + } +} diff --git a/tests/PactNet.Compatibility.Tests/Support/Baseline.cs b/tests/PactNet.Compatibility.Tests/Support/Baseline.cs new file mode 100644 index 00000000..25a2945f --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/Support/Baseline.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using YamlDotNet.Serialization; +using YamlDotNet.Serialization.NamingConventions; + +namespace PactNet.Compatibility.Tests.Support +{ + /// + /// One scenario that is known not to pass + /// + public sealed class BaselineEntry + { + public string Feature { get; set; } + + public string Scenario { get; set; } + + /// + /// failing | unsupported + /// + public string Status { get; set; } + + public string Reason { get; set; } + } + + /// + /// The ratchet baseline: scenarios expected not to pass, keyed by feature file and scenario name + /// + public sealed class Baseline + { + private const string Header = + "# Compatibility suite baseline (ratchet) for pact-net.\n" + + "# Lists scenarios that are NOT expected to pass, with a reason.\n" + + "# A run fails if an unlisted scenario fails, or a listed scenario now passes.\n" + + "# Regenerate with COMPAT_UPDATE_BASELINE=1 (existing reasons are kept).\n"; + + private readonly Dictionary<(string, string), BaselineEntry> entries; + + private Baseline(IEnumerable entries) + { + this.entries = entries.ToDictionary(e => (e.Feature, e.Scenario)); + } + + public IReadOnlyCollection Entries => this.entries.Values; + + public static Baseline Load(string path) + { + if (!File.Exists(path)) + { + return new Baseline(Enumerable.Empty()); + } + + IDeserializer deserializer = new DeserializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).Build(); + List list = deserializer.Deserialize>(File.ReadAllText(path)) ?? new List(); + return new Baseline(list); + } + + public BaselineEntry Find(string feature, string scenario) => + this.entries.TryGetValue((feature, scenario), out BaselineEntry entry) ? entry : null; + + public static void Write(string path, IEnumerable entries) + { + List ordered = entries.OrderBy(e => e.Feature, StringComparer.Ordinal) + .ThenBy(e => e.Scenario, StringComparer.Ordinal) + .ToList(); + + var sb = new StringBuilder(Header); + + if (ordered.Count == 0) + { + sb.AppendLine("[]"); + } + else + { + ISerializer serializer = new SerializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).Build(); + sb.Append(serializer.Serialize(ordered)); + } + + File.WriteAllText(path, sb.ToString()); + } + } +} diff --git a/tests/PactNet.Compatibility.Tests/Support/CapturingHttpPactDriver.cs b/tests/PactNet.Compatibility.Tests/Support/CapturingHttpPactDriver.cs new file mode 100644 index 00000000..98e89cf8 --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/Support/CapturingHttpPactDriver.cs @@ -0,0 +1,35 @@ +using PactNet.Drivers; +using PactNet.Interop; + +namespace PactNet.Compatibility.Tests.Support +{ + /// + /// HTTP pact driver that remembers the handle of the most recently created interaction, so that + /// parts the DSL can't express (binary bodies) can be added through the FFI directly + /// + internal sealed class CapturingHttpPactDriver : IHttpPactDriver + { + private readonly PactHandle pact; + private readonly HttpPactDriver inner; + + public CapturingHttpPactDriver(PactHandle pact) + { + this.pact = pact; + this.inner = new HttpPactDriver(pact); + } + + public InteractionHandle LastInteraction { get; private set; } + + public IHttpInteractionDriver NewHttpInteraction(string description) + { + this.LastInteraction = NativeInterop.NewInteraction(this.pact, description); + return new HttpInteractionDriver(this.pact, this.LastInteraction); + } + + public IMockServerDriver CreateMockServer(string host, int? port, bool tls) + => this.inner.CreateMockServer(host, port, tls); + + public void WritePactFile(string directory) + => this.inner.WritePactFile(directory); + } +} diff --git a/tests/PactNet.Compatibility.Tests/Support/CompatFfi.cs b/tests/PactNet.Compatibility.Tests/Support/CompatFfi.cs new file mode 100644 index 00000000..3d31be99 --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/Support/CompatFfi.cs @@ -0,0 +1,16 @@ +using System; +using System.Runtime.InteropServices; +using PactNet.Interop; + +namespace PactNet.Compatibility.Tests.Support +{ + /// + /// FFI calls PactNet does not bind. Resolved through like PactNet's own. + /// + internal static class CompatFfi + { + // PactNet has no binary body API: WithBody(string, contentType) marshals a NUL-terminated C string + [DllImport("pact_ffi", EntryPoint = "pactffi_with_binary_body")] + public static extern bool WithBinaryBody(InteractionHandle interaction, InteractionPart part, string contentType, byte[] body, UIntPtr size); + } +} diff --git a/tests/PactNet.Compatibility.Tests/Support/CompatPaths.cs b/tests/PactNet.Compatibility.Tests/Support/CompatPaths.cs new file mode 100644 index 00000000..fc1475d5 --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/Support/CompatPaths.cs @@ -0,0 +1,42 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; + +namespace PactNet.Compatibility.Tests.Support +{ + /// + /// Locations baked in at build time, so fixtures and the baseline are read in place from the source tree + /// + internal static class CompatPaths + { + public static string SuiteDir { get; } = Metadata("CompatSuiteDir"); + + public static string ProjectDir { get; } = Metadata("CompatProjectDir"); + + public static string FixturesDir => Path.Combine(SuiteDir, "fixtures"); + + public static string BaselineFile => + Environment.GetEnvironmentVariable("COMPAT_BASELINE_FILE") is { Length: > 0 } custom + ? custom + : Path.Combine(ProjectDir, "baseline.yaml"); + + public static string Fixture(string name) + { + string path = Path.Combine(FixturesDir, name); + + if (!File.Exists(path)) + { + throw new FileNotFoundException($"Fixture '{name}' not found in {FixturesDir} (is the pact-compatibility-suite submodule checked out?)", path); + } + + return path; + } + + private static string Metadata(string key) => + typeof(CompatPaths).Assembly + .GetCustomAttributes() + .Single(a => a.Key == key) + .Value; + } +} diff --git a/tests/PactNet.Compatibility.Tests/Support/CompatWorld.cs b/tests/PactNet.Compatibility.Tests/Support/CompatWorld.cs new file mode 100644 index 00000000..418d3553 --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/Support/CompatWorld.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace PactNet.Compatibility.Tests.Support +{ + /// + /// Raised by a step when the scenario's expectation does not hold + /// + public sealed class CompatAssertionException : Exception + { + public CompatAssertionException(string message) : base(message) + { + } + } + + /// + /// Per-scenario state shared between step classes (injected by Reqnroll) + /// + public sealed class CompatWorld + { + internal List Interactions { get; set; } = new(); + + internal MockServerSession Session { get; set; } + + internal HttpResponse Response { get; set; } + + /// + /// First step failure; once set, remaining steps are skipped and the ratchet decides the outcome + /// + public Exception Failure { get; private set; } + + /// + /// Set when the scenario uses something this runner can't express (counts as unsupported, not failed) + /// + public Exception Unsupported { get; private set; } + + public string FailedStep { get; private set; } + + public void Run(string step, Action body) => + this.RunAsync(step, () => + { + body(); + return Task.CompletedTask; + }).GetAwaiter().GetResult(); + + public async Task RunAsync(string step, Func body) + { + if (this.Failure != null || this.Unsupported != null) + { + return; + } + + try + { + await body(); + } + catch (NotSupportedException e) + { + this.Unsupported = e; + this.FailedStep = step; + } + catch (Exception e) + { + this.Failure = e; + this.FailedStep = step; + } + } + + internal InteractionDefinition Interaction(int no) + { + InteractionDefinition found = this.Interactions.Find(i => i.No == no); + return found ?? throw new InvalidOperationException($"Interaction {no} has not been defined"); + } + + internal MockServerSession RequireSession() => + this.Session ?? throw new InvalidOperationException("The mock server has not been started"); + + public static void Check(bool condition, string message) + { + if (!condition) + { + throw new CompatAssertionException(message); + } + } + } +} diff --git a/tests/PactNet.Compatibility.Tests/Support/InteractionDefinition.cs b/tests/PactNet.Compatibility.Tests/Support/InteractionDefinition.cs new file mode 100644 index 00000000..89676845 --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/Support/InteractionDefinition.cs @@ -0,0 +1,312 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Xml.Linq; +using Reqnroll; + +namespace PactNet.Compatibility.Tests.Support +{ + /// + /// Request/response body described by a compatibility suite table cell + /// + internal sealed class BodyDefinition + { + public BodyDefinition(string contentType, byte[] bytes) + { + this.ContentType = contentType; + this.Bytes = bytes; + } + + public string ContentType { get; } + + public byte[] Bytes { get; } + + public string Text => Encoding.UTF8.GetString(this.Bytes); + + /// + /// Whether the body can only be expressed as raw bytes (it cannot round-trip through a C string) + /// + public bool IsBinary + { + get + { + if (this.ContentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || + this.ContentType.StartsWith("application/octet-stream", StringComparison.OrdinalIgnoreCase) || + this.ContentType.StartsWith("application/pdf", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (Array.IndexOf(this.Bytes, (byte)0) >= 0) + { + return true; + } + + try + { + _ = new UTF8Encoding(false, true).GetString(this.Bytes); + return false; + } + catch (ArgumentException) + { + return true; + } + } + } + + /// + /// Parse a body cell: JSON: ..., XML: ..., file: name, EMPTY or literal text + /// + public static BodyDefinition Parse(string cell, string fallbackContentType) + { + string value = cell.Trim(); + + if (value.StartsWith("JSON:", StringComparison.Ordinal)) + { + return new BodyDefinition("application/json", Encoding.UTF8.GetBytes(value.Substring(5).Trim())); + } + + if (value.StartsWith("XML:", StringComparison.Ordinal)) + { + return new BodyDefinition("application/xml", Encoding.UTF8.GetBytes(value.Substring(4).Trim())); + } + + if (value.StartsWith("file:", StringComparison.Ordinal)) + { + return FromFixture(value.Substring(5).Trim(), fallbackContentType); + } + + if (value == "EMPTY") + { + return new BodyDefinition(fallbackContentType ?? "text/plain", Array.Empty()); + } + + return new BodyDefinition(fallbackContentType ?? "text/plain", Encoding.UTF8.GetBytes(value)); + } + + public static BodyDefinition FromFixture(string name, string fallbackContentType = null) + { + string path = CompatPaths.Fixture(name); + + // *-body.xml fixtures are an envelope: + if (name.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)) + { + XDocument doc = XDocument.Load(path); + XElement root = doc.Root; + + if (root?.Name.LocalName == "body" && root.Element("contents") is { } contents) + { + string contentType = root.Element("contentType")?.Value.Trim() is { Length: > 0 } ct ? ct : "text/plain"; + string text = contents.Value.Trim().Replace("\r\n", "\n"); + + if (string.Equals((string)contents.Attribute("eol"), "CRLF", StringComparison.OrdinalIgnoreCase)) + { + text = text.Replace("\n", "\r\n"); + } + + return new BodyDefinition(contentType, Encoding.UTF8.GetBytes(text)); + } + } + + string inferred = Path.GetExtension(name).ToLowerInvariant() switch + { + ".json" => "application/json", + ".xml" => "application/xml", + ".jpg" or ".jpeg" => "image/jpeg", + ".png" => "image/png", + ".pdf" => "application/pdf", + _ => fallbackContentType ?? "text/plain" + }; + + return new BodyDefinition(inferred, File.ReadAllBytes(path)); + } + } + + /// + /// One row of a "the following HTTP interactions have been defined" table + /// + internal sealed class InteractionDefinition + { + private static readonly HashSet SupportedColumns = new(StringComparer.Ordinal) + { + "No", "method", "path", "query", "headers", "body", "response", "response headers", "response content", "response body" + }; + + public int No { get; set; } + + public string Method { get; set; } = "GET"; + + public string Path { get; set; } = "/"; + + public string Query { get; set; } + + public List> Headers { get; set; } = new(); + + public BodyDefinition Body { get; set; } + + public ushort Status { get; set; } = 200; + + public List> ResponseHeaders { get; set; } = new(); + + public string ResponseContentType { get; set; } + + public BodyDefinition ResponseBody { get; set; } + + public InteractionDefinition Clone() => new() + { + No = this.No, + Method = this.Method, + Path = this.Path, + Query = this.Query, + Headers = this.Headers.ToList(), + Body = this.Body, + Status = this.Status, + ResponseHeaders = this.ResponseHeaders.ToList(), + ResponseContentType = this.ResponseContentType, + ResponseBody = this.ResponseBody + }; + + public static List FromTable(Table table) + { + EnsureSupported(table.Header); + + return table.Rows.Select(row => + { + var interaction = new InteractionDefinition(); + interaction.Apply(row); + return interaction; + }).ToList(); + } + + /// + /// Apply a changes table (header row + one value row) to a copy of this interaction + /// + public InteractionDefinition WithChanges(Table changes) + { + EnsureSupported(changes.Header); + + if (changes.RowCount != 1) + { + throw new NotSupportedException($"Expected exactly one row of changes, got {changes.RowCount}"); + } + + InteractionDefinition copy = this.Clone(); + copy.Apply(changes.Rows[0]); + return copy; + } + + private static void EnsureSupported(IEnumerable columns) + { + string[] unknown = columns.Where(c => !SupportedColumns.Contains(c)).ToArray(); + + if (unknown.Length > 0) + { + throw new NotSupportedException($"Interaction table column(s) not supported by this runner: {string.Join(", ", unknown)}"); + } + } + + private void Apply(DataTableRow row) + { + foreach (KeyValuePair cell in row) + { + string value = cell.Value?.Trim() ?? string.Empty; + + switch (cell.Key) + { + case "No": + this.No = int.Parse(value); + break; + case "method": + this.Method = value; + break; + case "path": + this.Path = value; + break; + case "query": + this.Query = value.Length == 0 ? null : value; + break; + case "headers": + this.Headers = ParseHeaders(value); + break; + case "body": + if (value.Length > 0) + { + this.Body = BodyDefinition.Parse(value, this.Body?.ContentType); + } + break; + case "response": + if (value.Length > 0) + { + this.Status = ushort.Parse(value); + } + break; + case "response headers": + this.ResponseHeaders = ParseHeaders(value); + break; + case "response content": + this.ResponseContentType = value.Length == 0 ? null : value; + break; + case "response body": + if (value.Length > 0) + { + this.ResponseBody = BodyDefinition.Parse(value, this.ResponseContentType ?? this.ResponseBody?.ContentType); + } + break; + } + } + } + + /// + /// Parse 'X-A: 1', 'X-B: 2' + /// + public static List> ParseHeaders(string cell) + { + var headers = new List>(); + + if (string.IsNullOrWhiteSpace(cell)) + { + return headers; + } + + foreach (string part in cell.Split(',')) + { + string header = part.Trim().Trim('\'', '"').Trim(); + int colon = header.IndexOf(':'); + + if (colon <= 0) + { + throw new FormatException($"Invalid header '{header}'"); + } + + headers.Add(new KeyValuePair(header.Substring(0, colon).Trim(), header.Substring(colon + 1).Trim())); + } + + return headers; + } + + /// + /// Parse a raw query string into ordered, decoded pairs + /// + public static List> ParseQuery(string query) + { + var pairs = new List>(); + + if (string.IsNullOrEmpty(query)) + { + return pairs; + } + + foreach (string part in query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + int eq = part.IndexOf('='); + string key = eq < 0 ? part : part.Substring(0, eq); + string value = eq < 0 ? string.Empty : part.Substring(eq + 1); + pairs.Add(new KeyValuePair(Uri.UnescapeDataString(key.Replace('+', ' ')), Uri.UnescapeDataString(value.Replace('+', ' ')))); + } + + return pairs; + } + } +} diff --git a/tests/PactNet.Compatibility.Tests/Support/MockServerSession.cs b/tests/PactNet.Compatibility.Tests/Support/MockServerSession.cs new file mode 100644 index 00000000..f5e98914 --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/Support/MockServerSession.cs @@ -0,0 +1,284 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json.Nodes; +using System.Threading.Tasks; +using PactNet.Exceptions; +using PactNet.Infrastructure.Outputters; +using PactNet.Interop; + +namespace PactNet.Compatibility.Tests.Support +{ + /// + /// A PactNet consumer test held open across Gherkin steps: the mock server starts inside + /// and the interact callback only completes once "the pact test is done" + /// + internal sealed class MockServerSession : IAsyncDisposable + { + public const string Consumer = "compatibility-suite-c"; + public const string Provider = "p"; + + private readonly TaskCompletionSource started = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource finished = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly CapturingOutput output = new(); + private Task verifyTask; + + private MockServerSession(string pactDir) + { + this.PactDir = pactDir; + } + + public string PactDir { get; } + + public string PactFile => Path.Combine(this.PactDir, $"{Consumer}-{Provider}.json"); + + public Uri BaseUri { get; private set; } + + public bool IsDone { get; private set; } + + /// + /// Result of verification once done: true when the mock server reported no mismatches + /// + public bool Ok { get; private set; } + + public Exception VerifyError { get; private set; } + + /// + /// Mismatches captured at the moment the test was marked done (the mock server is gone afterwards) + /// + public JsonArray FinalMismatches { get; private set; } + + public string Output => this.output.ToString(); + + public static async Task StartAsync(IReadOnlyList interactions) + { + string pactDir = Path.Combine(Path.GetTempPath(), "pactnet-compat", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(pactDir); + + var session = new MockServerSession(pactDir); + var config = new PactConfig + { + PactDir = pactDir, + Outputters = new IOutput[] { session.output }, + LogLevel = PactLogLevel.Information + }; + + IPactBuilderV2 builder; + CapturingHttpPactDriver capturing = null; + + if (interactions.Any(i => i.Body?.IsBinary == true || i.ResponseBody?.IsBinary == true)) + { + // Binary bodies need the interaction handle, which the public DSL never exposes + PactHandle pact = NativeInterop.NewPact(Consumer, Provider); + NativeInterop.WithSpecification(pact, PactSpecification.V2); + capturing = new CapturingHttpPactDriver(pact); + builder = new PactBuilder(capturing, config); + } + else + { + builder = Pact.V2(Consumer, Provider, config).WithHttpInteractions(); + } + + foreach (InteractionDefinition interaction in interactions) + { + Define(builder, capturing, interaction); + } + + session.verifyTask = Task.Run(() => builder.VerifyAsync(async ctx => + { + session.started.TrySetResult(ctx.MockServerUri); + await session.finished.Task; + })); + + Task first = await Task.WhenAny(session.started.Task, session.verifyTask); + if (first != session.started.Task) + { + await session.verifyTask; // surfaces the start-up exception + throw new InvalidOperationException("Mock server exited before it started"); + } + + session.BaseUri = await session.started.Task; + return session; + } + + private static void Define(IPactBuilderV2 builder, CapturingHttpPactDriver capturing, InteractionDefinition interaction) + { + IRequestBuilderV2 request = builder.UponReceiving($"Interaction {interaction.No}") + .WithRequest(interaction.Method, interaction.Path); + + foreach (KeyValuePair query in InteractionDefinition.ParseQuery(interaction.Query)) + { + request = request.WithQuery(query.Key, query.Value); + } + + foreach (KeyValuePair header in interaction.Headers) + { + request = request.WithHeader(header.Key, header.Value); + } + + if (interaction.Body is { } body) + { + if (body.IsBinary) + { + AddBinaryBody(capturing, InteractionPart.Request, body); + } + else + { + request = request.WithBody(body.Text, body.ContentType); + } + } + + IResponseBuilderV2 response = request.WillRespond().WithStatus(interaction.Status); + + foreach (KeyValuePair header in interaction.ResponseHeaders) + { + response = response.WithHeader(header.Key, header.Value); + } + + if (interaction.ResponseBody is { } responseBody) + { + if (responseBody.IsBinary) + { + AddBinaryBody(capturing, InteractionPart.Response, responseBody); + } + else + { + response.WithBody(responseBody.Text, interaction.ResponseContentType ?? responseBody.ContentType); + } + } + else if (interaction.ResponseContentType != null) + { + response.WithHeader("Content-Type", interaction.ResponseContentType); + } + } + + private static void AddBinaryBody(CapturingHttpPactDriver capturing, InteractionPart part, BodyDefinition body) + { + if (!CompatFfi.WithBinaryBody(capturing.LastInteraction, part, body.ContentType, body.Bytes, (UIntPtr)body.Bytes.Length)) + { + throw new InvalidOperationException($"pactffi_with_binary_body failed for the {part} body"); + } + } + + /// + /// Current mismatches straight from the running mock server (the DSL only exposes them as an exception message) + /// + public JsonArray LiveMismatches() + { + if (this.IsDone) + { + return this.FinalMismatches; + } + + IntPtr ptr = NativeInterop.MockServerMismatches(this.BaseUri.Port); + string json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(ptr); + return string.IsNullOrWhiteSpace(json) ? new JsonArray() : (JsonArray)JsonNode.Parse(json); + } + + public async Task SendAsync(InteractionDefinition request) + { + using var client = new HttpClient { BaseAddress = this.BaseUri }; + string target = request.Path + (string.IsNullOrEmpty(request.Query) ? string.Empty : "?" + request.Query); + using var message = new HttpRequestMessage(new HttpMethod(request.Method), target); + + foreach (KeyValuePair header in request.Headers) + { + if (!header.Key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase)) + { + message.Headers.TryAddWithoutValidation(header.Key, header.Value); + } + } + + if (request.Body is { } body) + { + message.Content = new ByteArrayContent(body.Bytes); + string contentType = request.Headers.FirstOrDefault(h => h.Key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase)).Value ?? body.ContentType; + message.Content.Headers.TryAddWithoutValidation("Content-Type", contentType); + } + + using HttpResponseMessage response = await client.SendAsync(message); + byte[] bytes = await response.Content.ReadAsByteArrayAsync(); + + return new HttpResponse((int)response.StatusCode, response.Content.Headers.ContentType?.ToString(), bytes); + } + + /// + /// Let VerifyAsync complete: it checks mismatches and writes the pact file only if there are none + /// + public async Task FinishAsync() + { + if (this.IsDone) + { + return; + } + + this.FinalMismatches = this.LiveMismatches(); + this.IsDone = true; + this.finished.TrySetResult(); + + try + { + await this.verifyTask; + this.Ok = true; + } + catch (PactFailureException e) + { + this.Ok = false; + this.VerifyError = e; + } + } + + public async ValueTask DisposeAsync() + { + this.finished.TrySetResult(); + + try + { + if (this.verifyTask != null) + { + await this.verifyTask; + } + } + catch (Exception) + { + // the scenario's outcome has already been decided by its steps + } + + try + { + Directory.Delete(this.PactDir, true); + } + catch (IOException) + { + } + } + + private sealed class CapturingOutput : IOutput + { + private readonly StringBuilder buffer = new(); + + public void WriteLine(string line) + { + lock (this.buffer) + { + this.buffer.AppendLine(line); + } + } + + public override string ToString() + { + lock (this.buffer) + { + return this.buffer.ToString(); + } + } + } + } + + internal sealed record HttpResponse(int Status, string ContentType, byte[] Body); +} diff --git a/tests/PactNet.Compatibility.Tests/Support/NativeLibraryOverride.cs b/tests/PactNet.Compatibility.Tests/Support/NativeLibraryOverride.cs new file mode 100644 index 00000000..4a263b66 --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/Support/NativeLibraryOverride.cs @@ -0,0 +1,81 @@ +using System; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using PactNet.Interop; + +namespace PactNet.Compatibility.Tests.Support +{ + /// + /// Lets PACT_FFI_LIB point at a specific pact_ffi build (a library file, or a directory containing one) + /// instead of the copy PactNet would normally load from build/<os>/<arch>/ + /// + internal static class NativeLibraryOverride + { + public const string EnvironmentVariable = "PACT_FFI_LIB"; + private const string LibraryName = "pact_ffi"; + + private static readonly object Sync = new(); + private static bool installed; + + /// + /// Resolved library path, or null when the default resolution is being used + /// + public static string LibraryPath { get; private set; } + + public static void Install() + { + lock (Sync) + { + if (installed) + { + return; + } + + installed = true; + + string configured = Environment.GetEnvironmentVariable(EnvironmentVariable); + if (string.IsNullOrWhiteSpace(configured)) + { + return; + } + + LibraryPath = ResolvePath(configured); + + // PactNet's own P/Invokes, plus the few extra ones this test assembly declares + SetResolver(typeof(NativeInterop).Assembly); + SetResolver(typeof(NativeLibraryOverride).Assembly); + } + } + + private static void SetResolver(Assembly assembly) + { + NativeLibrary.SetDllImportResolver(assembly, (name, _, _) => + name == LibraryName ? NativeLibrary.Load(LibraryPath) : IntPtr.Zero); + } + + private static string ResolvePath(string configured) + { + string path = Path.GetFullPath(configured); + + if (File.Exists(path)) + { + return path; + } + + if (Directory.Exists(path)) + { + foreach (string candidate in new[] { "libpact_ffi.dylib", "libpact_ffi.so", "pact_ffi.dll" }) + { + string file = Path.Combine(path, candidate); + if (File.Exists(file)) + { + return file; + } + } + } + + throw new FileNotFoundException($"{EnvironmentVariable}='{configured}' is not a pact_ffi library or a directory containing one", path); + } + } +} diff --git a/tests/PactNet.Compatibility.Tests/baseline.yaml b/tests/PactNet.Compatibility.Tests/baseline.yaml new file mode 100644 index 00000000..c4593299 --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/baseline.yaml @@ -0,0 +1,2 @@ +# Compatibility suite baseline (ratchet) for pact-net. +[] diff --git a/tests/PactNet.Compatibility.Tests/compat.runsettings b/tests/PactNet.Compatibility.Tests/compat.runsettings new file mode 100644 index 00000000..a061adae --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/compat.runsettings @@ -0,0 +1,12 @@ + + + + + json + + diff --git a/tests/PactNet.Compatibility.Tests/pact-compatibility-suite b/tests/PactNet.Compatibility.Tests/pact-compatibility-suite new file mode 160000 index 00000000..dd08122c --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/pact-compatibility-suite @@ -0,0 +1 @@ +Subproject commit dd08122ce7343730fd373574a91d046e8814be43 diff --git a/tests/PactNet.Compatibility.Tests/reqnroll.json b/tests/PactNet.Compatibility.Tests/reqnroll.json new file mode 100644 index 00000000..45fa4b5e --- /dev/null +++ b/tests/PactNet.Compatibility.Tests/reqnroll.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://schemas.reqnroll.net/reqnroll-config-latest.json", + "language": { "feature": "en-US" }, + "runtime": { "missingOrPendingStepsOutcome": "Ignore" }, + "trace": { "stepDefinitionSkeletonStyle": "CucumberExpressionAttribute" } +}