diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ca135af57..c07ed85b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,6 +55,18 @@ jobs: run: bash -c "build/download-native-libs.sh" if: ${{ steps.cache.outputs.cache-hit != 'true' }} + - name: Install protoc (for grpc plugin test) + run: sudo apt-get install --yes protobuf-compiler + if: ${{ matrix.os == 'ubuntu-24.04-arm' }} + + # Pre-install the plugins the tests need so that parallel test projects + # don't race each other auto-downloading them on first use + - name: Install Pact CLI + uses: pact-foundation/pact-cli@v0.10.8 + + - name: Install Pact plugins + run: pact plugin install --yes protobuf --version 0.8.0 + - name: Restore run: dotnet restore diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a8aa3f7a8..689458a2e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -53,14 +53,16 @@ Building PactNet ---------------- In order to build PactNet you must first download the native Rust FFI libraries. You can pull the current supported -version by executing the script in Bash (or Git Bash on Windows): +version by executing the script in Bash (or Git Bash on Windows). The script needs `curl`, `tar` with xz support, and +`unzip` (or `7z`) on the path, and verifies each archive against its `.sha256` file: ```bash build/download-native-libs.sh ``` -Alternatively you can download a particular FFI version from the [pact-reference] releases or build your own version -locally, and then copy the artifacts into the folders: +Alternatively you can download a particular FFI version from the [pact-reference] `pact_ffi-v` releases (one +archive per Rust target, e.g. `pact_ffi-aarch64-apple-darwin.tar.xz`) or build your own version locally, and then copy +the shared libraries into the folders: ``` build/ @@ -69,7 +71,7 @@ build/ libpact_ffi.so aarch64/ libpact_ffi.so - osx/ + macos/ aarch64/ libpact_ffi.dylib x86_64/ diff --git a/PactNet.sln b/PactNet.sln index 243019fae..a63927829 100644 --- a/PactNet.sln +++ b/PactNet.sln @@ -37,6 +37,21 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PactNet.Output.Xunit", "src\PactNet.Output.Xunit\PactNet.Output.Xunit.csproj", "{02E265A1-A7A2-4106-8F6A-5027FDC3FC50}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Grpc", "Grpc", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GrpcGreeter", "samples\Grpc\GrpcGreeter\GrpcGreeter.csproj", "{529F37CB-CDA0-6553-EAC9-8DAC2195ED69}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GrpcGreeterClient", "samples\Grpc\GrpcGreeterClient\GrpcGreeterClient.csproj", "{917DAC61-55B4-D721-B1ED-B0E352E4CF1A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GrpcGreeterClient.Tests", "samples\Grpc\GrpcGreeterClient.Tests\GrpcGreeterClient.Tests.csproj", "{13756BC3-0750-E2AF-E1F0-565855A3E636}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GrpcGreeter.Tests", "samples\Grpc\GrpcGreeter.Tests\GrpcGreeter.Tests.csproj", "{DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "pacts", "pacts", "{FB3A8B7F-7DA0-40A8-AFD1-FB0992FB9B2C}" + ProjectSection(SolutionItems) = preProject + samples\Grpc\pacts\grpc-greeter-client-grpc-greeter.json = samples\Grpc\pacts\grpc-greeter-client-grpc-greeter.json + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -155,6 +170,54 @@ Global {02E265A1-A7A2-4106-8F6A-5027FDC3FC50}.Release|x64.Build.0 = Release|Any CPU {02E265A1-A7A2-4106-8F6A-5027FDC3FC50}.Release|x86.ActiveCfg = Release|Any CPU {02E265A1-A7A2-4106-8F6A-5027FDC3FC50}.Release|x86.Build.0 = Release|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Debug|Any CPU.Build.0 = Debug|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Debug|x64.ActiveCfg = Debug|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Debug|x64.Build.0 = Debug|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Debug|x86.ActiveCfg = Debug|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Debug|x86.Build.0 = Debug|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Release|Any CPU.ActiveCfg = Release|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Release|Any CPU.Build.0 = Release|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Release|x64.ActiveCfg = Release|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Release|x64.Build.0 = Release|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Release|x86.ActiveCfg = Release|Any CPU + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69}.Release|x86.Build.0 = Release|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Debug|x64.ActiveCfg = Debug|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Debug|x64.Build.0 = Debug|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Debug|x86.ActiveCfg = Debug|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Debug|x86.Build.0 = Debug|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Release|Any CPU.Build.0 = Release|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Release|x64.ActiveCfg = Release|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Release|x64.Build.0 = Release|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Release|x86.ActiveCfg = Release|Any CPU + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A}.Release|x86.Build.0 = Release|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Debug|Any CPU.Build.0 = Debug|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Debug|x64.ActiveCfg = Debug|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Debug|x64.Build.0 = Debug|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Debug|x86.ActiveCfg = Debug|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Debug|x86.Build.0 = Debug|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Release|Any CPU.ActiveCfg = Release|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Release|Any CPU.Build.0 = Release|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Release|x64.ActiveCfg = Release|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Release|x64.Build.0 = Release|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Release|x86.ActiveCfg = Release|Any CPU + {13756BC3-0750-E2AF-E1F0-565855A3E636}.Release|x86.Build.0 = Release|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Debug|x64.ActiveCfg = Debug|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Debug|x64.Build.0 = Debug|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Debug|x86.ActiveCfg = Debug|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Debug|x86.Build.0 = Debug|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Release|Any CPU.Build.0 = Release|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Release|x64.ActiveCfg = Release|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Release|x64.Build.0 = Release|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Release|x86.ActiveCfg = Release|Any CPU + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -170,6 +233,12 @@ Global {5E915D66-917B-4730-B31A-C9727C196346} = {6663C12E-9912-40D0-9310-D119D1F6B023} {D8B75E48-6E45-468B-8049-B73823C14CB8} = {6663C12E-9912-40D0-9310-D119D1F6B023} {02E265A1-A7A2-4106-8F6A-5027FDC3FC50} = {CF67D7A1-AE96-420B-9971-65E535B903E8} + {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} = {547DB478-460A-428F-9371-1D653CE85DB5} + {529F37CB-CDA0-6553-EAC9-8DAC2195ED69} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {917DAC61-55B4-D721-B1ED-B0E352E4CF1A} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {13756BC3-0750-E2AF-E1F0-565855A3E636} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {DC5371A0-7DE2-4CC5-D0E1-1DF6CB567FA6} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {FB3A8B7F-7DA0-40A8-AFD1-FB0992FB9B2C} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {C2CBC30C-92D4-4E3A-A5B8-1E5D4E938DFC} diff --git a/README.md b/README.md index c70c541bb..edf9deb12 100644 --- a/README.md +++ b/README.md @@ -226,6 +226,12 @@ For writing messaging pacts instead of requests/response pacts, see the [messagi ![----------](https://raw.githubusercontent.com/pactumjs/pactum/master/assets/rainbow.png) +### Plugin Interactions + +For protocols handled by a Pact plugin, such as gRPC, see the [plugin interactions guide](docs/plugin-interactions.md). + +![----------](https://raw.githubusercontent.com/pactumjs/pactum/master/assets/rainbow.png) + ## Compatibility ### Operating System diff --git a/build/download-native-libs.sh b/build/download-native-libs.sh index c3ace8918..46d492cd5 100755 --- a/build/download-native-libs.sh +++ b/build/download-native-libs.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash set -euo pipefail -FFI_VERSION="0.4.27" -FFI_BASE_URL="https://github.com/pact-foundation/pact-reference/releases/download/libpact_ffi-v$FFI_VERSION" +FFI_VERSION="0.5.13" +FFI_BASE_URL="https://github.com/pact-foundation/pact-reference/releases/download/pact_ffi-v$FFI_VERSION" GREEN="\e[32m" YELLOW="\e[33m" @@ -12,60 +12,75 @@ CLEAR="\e[0m" base_path=$(dirname "$0") download_native() { - file="$1" - os="$2" - platform="$3" - extension="$4" + os="$1" + platform="$2" + target="$3" + archive_ext="$4" + lib="$5" # e.g. - # pact_ffi-windows-x86_64.dll.gz - # libpact_ffi-linux-x86_64.so.gz - # libpact_ffi-macos-x86_64.dylib.gz - src_file="$file-$os-$platform.$extension" - src_archive="$src_file.gz" + # pact_ffi-x86_64-pc-windows-msvc.zip (pact_ffi.dll at the archive root) + # pact_ffi-x86_64-unknown-linux-gnu.tar.xz (pact_ffi-/libpact_ffi.so) + # pact_ffi-aarch64-apple-darwin.tar.xz (pact_ffi-/libpact_ffi.dylib) + src_archive="pact_ffi-$target.$archive_ext" src_sha="$src_archive.sha256" - dest_file="$file.$extension" url="$FFI_BASE_URL/$src_archive" sha="$url.sha256" path="$base_path/$os/$platform" mkdir -p "$path" - pushd $path > /dev/null + pushd "$path" > /dev/null echo -e "Downloading FFI library for ${YELLOW}$os/$platform${CLEAR}" - echo -e " Destination: ${BLUE}$path/$src_archive${CLEAR}" + echo -e " Destination: ${BLUE}$path/$lib${CLEAR}" echo -e " URL: ${BLUE}$url${CLEAR}" echo -n " Downloading... " - curl --silent -L "$url" -o "$src_archive" - curl --silent -L "$sha" -o "$src_archive.sha256" + curl --silent --show-error --fail -L "$url" -o "$src_archive" + curl --silent --show-error --fail -L "$sha" -o "$src_sha" echo -e "${GREEN}OK${CLEAR}" echo -n " Verifying... " if [[ "$OSTYPE" == "darwin"* ]]; then - shasum -a 256 --check --quiet "$src_sha" + sed '/^$/d' "$src_sha" | shasum -a 256 --check --quiet - else - sha256sum --check --quiet "$src_sha" + sed '/^$/d' "$src_sha" | sha256sum --check --quiet - fi echo -e "${GREEN}OK${CLEAR}" echo -n " Extracting... " - gunzip -f "$src_archive" + extract_dir=$(mktemp -d) + if [[ "$archive_ext" == "zip" ]]; then + extract_zip "$src_archive" "$extract_dir" + extracted="$extract_dir/$lib" + else + tar -xJf "$src_archive" -C "$extract_dir" + extracted="$extract_dir/pact_ffi-$target/$lib" + fi + mv -f "$extracted" "$lib" + rm -rf "$extract_dir" "$src_archive" "$src_sha" echo -e "${GREEN}OK${CLEAR}" echo "" - mv "$src_file" "$dest_file" - rm "$src_sha" - popd > /dev/null } -download_native "pact_ffi" "windows" "x86_64" "dll" -download_native "libpact_ffi" "linux" "x86_64" "so" -download_native "libpact_ffi" "linux" "aarch64" "so" -download_native "libpact_ffi" "macos" "x86_64" "dylib" -download_native "libpact_ffi" "macos" "aarch64" "dylib" +extract_zip() { + if command -v unzip > /dev/null; then + unzip -q -o "$1" -d "$2" + elif command -v 7z > /dev/null; then + 7z x -y -o"$2" "$1" > /dev/null + else + tar -xf "$1" -C "$2" + fi +} + +download_native "windows" "x86_64" "x86_64-pc-windows-msvc" "zip" "pact_ffi.dll" +download_native "linux" "x86_64" "x86_64-unknown-linux-gnu" "tar.xz" "libpact_ffi.so" +download_native "linux" "aarch64" "aarch64-unknown-linux-gnu" "tar.xz" "libpact_ffi.so" +download_native "macos" "x86_64" "x86_64-apple-darwin" "tar.xz" "libpact_ffi.dylib" +download_native "macos" "aarch64" "aarch64-apple-darwin" "tar.xz" "libpact_ffi.dylib" -echo "Successfully downloaded FFI libraries" \ No newline at end of file +echo "Successfully downloaded FFI libraries" diff --git a/docs/http-plugin-interactions.md b/docs/http-plugin-interactions.md new file mode 100644 index 000000000..ce5d14888 --- /dev/null +++ b/docs/http-plugin-interactions.md @@ -0,0 +1,31 @@ +# HTTP Plugin Interactions + +Content plugins can configure binary HTTP request and response bodies without +providing their own transport. The public `WithHttpPluginInteractions` entry point +creates HTTP interactions on a plugin-loaded pact and keeps native handles private. + +```csharp +using var pact = Pact.V4("consumer", "provider", config) + .WithHttpPluginInteractions("avro", "0.1.3"); + +pact.UponReceiving("an Avro response") + .WithRequest(HttpMethod.Get, "/avro") + .WillRespondWithStatus(200) + .WithHeader("Content-Type", "avro/binary;record=User") + .WithContent("avro/binary", new Dictionary + { + ["pact:avro"] = schemaPath, + ["pact:record-name"] = "User", + ["id"] = "matching(integer, 1)", + ["username"] = "matching(equalTo, 'alice')" + }); +``` + +Use `Verify`/`VerifyAsync` with the real HTTP client and dispose the builder. +Request contents can be configured once before the response stage. Response +contents complete the interaction and can be configured once; later headers or +contents are rejected. The plugin owns its configuration schema and binary encoding. + +PactNet still owns HTTP server startup, mismatches, logs, pact writing and plugin +cleanup. Provider verification uses the ordinary `PactVerifier`. This prototype +does not add asynchronous plugin message reification or expose FFI internals. \ No newline at end of file diff --git a/docs/plugin-interactions.md b/docs/plugin-interactions.md new file mode 100644 index 000000000..589d1cc9d --- /dev/null +++ b/docs/plugin-interactions.md @@ -0,0 +1,127 @@ +Plugin Interactions +=================== + +Pact [plugins](https://docs.pact.io/plugins) extend Pact to protocols and content types beyond HTTP and +plain messaging, for example gRPC/protobuf or CSV. PactNet exposes a "raw" plugin API which works with any +plugin, so that a new plugin can be used before a friendlier wrapper library exists for it. + +Currently only **synchronous** plugin interactions are supported: a single request with one or more +responses, such as a gRPC unary call. Asynchronous (message-style) plugin interactions are not yet exposed. + +Prerequisites +------------- + +The plugin itself must be installed on the machine running the tests, on both the consumer and provider side. +Plugins live under `~/.pact/plugins/-` and are installed with the +[plugin CLI](https://docs.pact.io/implementation_guides/pact_plugins/cli), for example: + +```shell +pact-plugin-cli install https://github.com/pact-foundation/pact-protobuf-plugin/releases/tag/v-0.8.0 +``` + +Sample +------ + +See the [gRPC sample](../samples/Grpc/) for a working consumer and provider using the protobuf plugin. + +Consumer Tests +-------------- + +A plugin pact is created from a V4 pact by naming the plugin, its version and the transport the mock +server should use. Each interaction is then defined by handing the plugin a content type it understands +plus a dictionary describing the interaction. The plugin, not PactNet, decides what that dictionary must +contain and how it is split into a request and its responses. + +```csharp +public class GreeterClientTests : IDisposable +{ + private readonly ISynchronousPluginPactBuilderV4 pact; + + public GreeterClientTests(ITestOutputHelper output) + { + IPactV4 v4 = Pact.V4("Greeter Client", "Greeter Service", new PactConfig + { + PactDir = "../../../pacts/", + Outputters = new[] { new XunitOutput(output) } + }); + + this.pact = v4.WithSynchronousPluginInteractions("protobuf", "0.8.0", transport: "grpc"); + } + + [Fact] + public async Task SayHello_ReturnsGreeting() + { + var content = new Dictionary + { + ["pact:proto"] = Path.GetFullPath("../../../Protos/greet.proto"), + ["pact:proto-service"] = "Greeter/SayHello", + ["pact:content-type"] = "application/protobuf", + ["request"] = new { name = "matching(equalTo, 'foo')" }, + ["response"] = new { message = "matching(equalTo, 'Hello foo')" } + }; + + this.pact + .UponReceiving("a request to say hello") + .Given("the greeter is available") + .WithContent("application/grpc", content); + + await this.pact.VerifyAsync(async ctx => + { + var client = new GreeterClient(ctx.MockServerUri); + + string greeting = await client.SayHello("foo"); + + greeting.Should().Be("Hello foo"); + }); + } + + public void Dispose() => this.pact.Dispose(); +} +``` + +`Verify`/`VerifyAsync` starts a mock server using the requested transport, runs your client against it, checks +every interaction was matched, writes the pact file and prints the mock server logs, exactly as for HTTP pacts. +Dispose the builder when the test finishes so the underlying plugin resources are released. + +### Building an interaction + +Each call to `UponReceiving` starts a new interaction and a pact may contain as many as you need. The builder +has two kinds of call: + +- `Given(...)` adds provider states and may be repeated. +- `WithContent(contentType, content)` sets the plugin contents. **It completes the interaction and must be the + last call.** It returns nothing, so it cannot be chained further. + +`WithContent` is deliberately single-shot. The plugin splits one contents dictionary into the request and its +responses. If contents were set a second time on the same interaction the request would be replaced but the +response would be appended, leaving the interaction with two responses, so PactNet does not allow it. Define a +second `UponReceiving` instead. + +### Multiple interactions on one method + +The gRPC mock server tracks whether each service method was called, not each interaction. If two interactions +target the same `Service/Method` and your client only exercises one of them, verification still passes. Give +interactions on the same method distinguishable requests and make sure your test calls each of them. + +Provider Tests +-------------- + +Provider verification uses the normal `PactVerifier`. Point it at the running gRPC server as the HTTP endpoint; +the transport recorded in the pact file tells the verifier to hand the interaction to the plugin. + +```csharp +this.verifier + .WithHttpEndpoint(new Uri("http://localhost:5000")) + .WithFileSource(new FileInfo(pactPath)) + .Verify(); +``` + +Writing a plugin wrapper +------------------------ + +A wrapper library gives a plugin a protocol-specific fluent API on top of the raw builders, without needing +any access to PactNet internals. Wrap `ISynchronousPluginPactBuilderV4`, have your own request/response builders +assemble the contents dictionary, and call `WithContent` once when the user has finished describing the +interaction. Delegate `Verify`, `VerifyAsync` and `Dispose` straight through. The +[`PactNet.Extensions.Grpc`](https://github.com/pact-foundation/pact-net/pull/548) package is the reference +implementation of this pattern. diff --git a/docs/upgrading-to-5.md b/docs/upgrading-to-5.md index 8e9d4dd06..bcbcfbe90 100644 --- a/docs/upgrading-to-5.md +++ b/docs/upgrading-to-5.md @@ -132,3 +132,18 @@ MacOS ARM64 Full Support ------------------------ MacOS now has full x86-64 and ARM support. + +HTTP Request Headers with Multiple Values +----------------------------------------- + +With `libpact_ffi` 0.5.10, a request header configured as separate values can mismatch +the single comma-separated value sent by an HTTP client. Configure the expected header +as the joined value instead: + +```csharp +.WithHeader("X-Request", "request1, request2") +``` + +This replaces separate calls such as `.WithHeader("X-Request", "request1")` and +`.WithHeader("X-Request", "request2")` when those values are sent together in one +request header. diff --git a/samples/Grpc/GrpcGreeter.Tests/GrpcGreeter.Tests.csproj b/samples/Grpc/GrpcGreeter.Tests/GrpcGreeter.Tests.csproj new file mode 100644 index 000000000..1fdf3de2f --- /dev/null +++ b/samples/Grpc/GrpcGreeter.Tests/GrpcGreeter.Tests.csproj @@ -0,0 +1,23 @@ + + + net8.0 + false + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + diff --git a/samples/Grpc/GrpcGreeter.Tests/GrpcGreeterTest.cs b/samples/Grpc/GrpcGreeter.Tests/GrpcGreeterTest.cs new file mode 100644 index 000000000..038aac3b7 --- /dev/null +++ b/samples/Grpc/GrpcGreeter.Tests/GrpcGreeterTest.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.IO; +using FluentAssertions; +using PactNet; +using PactNet.Exceptions; +using PactNet.Infrastructure.Outputters; +using Xunit; +using PactNet.Output.Xunit; +using PactNet.Verifier; +using Xunit.Abstractions; + +namespace GrpcGreeter.Tests +{ + public class GrpcGreeterTests(ITestOutputHelper output, ServerFixture serverFixture) : IClassFixture, IDisposable + { + private readonly PactVerifier verifier = new("Grpc Greeter Api", new PactVerifierConfig + { + LogLevel = PactLogLevel.Information, + Outputters = new List + { + new XunitOutput(output) + } + }); + + private readonly string pactPath = Path.Combine("..", "..", "..", "..", "..", "Grpc", "pacts", + "grpc-greeter-client-grpc-greeter.json"); + + [Fact] + public void VerificationThrowsExceptionWhenNoRunningProvider() + { + var source = this.verifier + .WithHttpEndpoint(new Uri("http://localhost:5060")) + .WithFileSource(new FileInfo(this.pactPath)); + + source.Invoking(s => s.Verify()).Should().Throw(); + } + + [Fact] + public void VerificationSuccessForRunningProvider() + { + verifier.WithHttpEndpoint(serverFixture.ProviderUri) + .WithFileSource(new FileInfo(pactPath)) + .Verify(); + } + + public void Dispose() + { + this.verifier?.Dispose(); + } + } +} diff --git a/samples/Grpc/GrpcGreeter.Tests/ServerFixture.cs b/samples/Grpc/GrpcGreeter.Tests/ServerFixture.cs new file mode 100644 index 000000000..f2f64b202 --- /dev/null +++ b/samples/Grpc/GrpcGreeter.Tests/ServerFixture.cs @@ -0,0 +1,28 @@ +using System; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; +using PactNet; +using PactNet.Interop; + +namespace GrpcGreeter.Tests; + +public class ServerFixture : IDisposable +{ + public readonly Uri ProviderUri = new("http://localhost:5000"); + private readonly IHost server; + + public ServerFixture() + { + this.server = Host.CreateDefaultBuilder() + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseUrls(this.ProviderUri.ToString()); + webBuilder.UseStartup(); + }) + .Build(); + + this.server.Start(); + } + + public void Dispose() => this.server?.Dispose(); +} diff --git a/samples/Grpc/GrpcGreeter/GrpcGreeter.csproj b/samples/Grpc/GrpcGreeter/GrpcGreeter.csproj new file mode 100644 index 000000000..4d475b896 --- /dev/null +++ b/samples/Grpc/GrpcGreeter/GrpcGreeter.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + diff --git a/samples/Grpc/GrpcGreeter/Program.cs b/samples/Grpc/GrpcGreeter/Program.cs new file mode 100644 index 000000000..21afa97ab --- /dev/null +++ b/samples/Grpc/GrpcGreeter/Program.cs @@ -0,0 +1,16 @@ +namespace GrpcGreeter; + +public class GrpcGreeterService +{ + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); +} diff --git a/samples/Grpc/GrpcGreeter/Properties/launchSettings.json b/samples/Grpc/GrpcGreeter/Properties/launchSettings.json new file mode 100644 index 000000000..f67a267d9 --- /dev/null +++ b/samples/Grpc/GrpcGreeter/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5251", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7272;http://localhost:5251", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/samples/Grpc/GrpcGreeter/Protos/greet.proto b/samples/Grpc/GrpcGreeter/Protos/greet.proto new file mode 100644 index 000000000..02343fa08 --- /dev/null +++ b/samples/Grpc/GrpcGreeter/Protos/greet.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; + +option csharp_namespace = "GrpcGreeter"; + +package greet; + +// The greeting service definition. +service Greeter { + // Sends a greeting + rpc SayHello (HelloRequest) returns (HelloReply); +} + +// The request message containing the user's name. +message HelloRequest { + string name = 1; +} + +// The response message containing the greetings. +message HelloReply { + string message = 1; +} diff --git a/samples/Grpc/GrpcGreeter/Services/GreeterService.cs b/samples/Grpc/GrpcGreeter/Services/GreeterService.cs new file mode 100644 index 000000000..bf7a1d324 --- /dev/null +++ b/samples/Grpc/GrpcGreeter/Services/GreeterService.cs @@ -0,0 +1,22 @@ +using Grpc.Core; + +namespace GrpcGreeter.Services +{ + public class GreeterService : Greeter.GreeterBase + { + private readonly ILogger logger; + + public GreeterService(ILogger logger) + { + this.logger = logger; + } + + public override Task SayHello(HelloRequest request, ServerCallContext context) + { + return Task.FromResult(new HelloReply + { + Message = "Hello " + request.Name + }); + } + } +} diff --git a/samples/Grpc/GrpcGreeter/Startup.cs b/samples/Grpc/GrpcGreeter/Startup.cs new file mode 100644 index 000000000..4d4196e85 --- /dev/null +++ b/samples/Grpc/GrpcGreeter/Startup.cs @@ -0,0 +1,37 @@ +using GrpcGreeter.Services; + +namespace GrpcGreeter; + +public class Startup +{ + public IConfiguration Configuration { get; } + + public Startup(IConfiguration configuration) + { + this.Configuration = configuration; + } + + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + // Add services to the container. + services.AddGrpc(); + services.AddGrpcReflection(); + + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + app.UseRouting(); + app.UseEndpoints(b => + { + // Configure the HTTP request pipeline. + b.MapGrpcService(); + b.MapGet("/", + () => + "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909"); + b.MapGrpcReflectionService(); + }); + } +} diff --git a/samples/Grpc/GrpcGreeter/appsettings.Development.json b/samples/Grpc/GrpcGreeter/appsettings.Development.json new file mode 100644 index 000000000..0c208ae91 --- /dev/null +++ b/samples/Grpc/GrpcGreeter/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/samples/Grpc/GrpcGreeter/appsettings.json b/samples/Grpc/GrpcGreeter/appsettings.json new file mode 100644 index 000000000..1aef5074f --- /dev/null +++ b/samples/Grpc/GrpcGreeter/appsettings.json @@ -0,0 +1,14 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Kestrel": { + "EndpointDefaults": { + "Protocols": "Http2" + } + } +} diff --git a/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClient.Tests.csproj b/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClient.Tests.csproj new file mode 100644 index 000000000..e51c7d079 --- /dev/null +++ b/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClient.Tests.csproj @@ -0,0 +1,23 @@ + + + net8.0 + false + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + diff --git a/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClientTest.cs b/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClientTest.cs new file mode 100644 index 000000000..66e202e99 --- /dev/null +++ b/samples/Grpc/GrpcGreeterClient.Tests/GrpcGreeterClientTest.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Threading.Tasks; +using FluentAssertions; +using Xunit; +using System.IO; +using System.Text.Json.Serialization; +using PactNet; +using PactNet.Exceptions; +using PactNet.Output.Xunit; +using Xunit.Abstractions; + +namespace GrpcGreeterClient.Tests +{ + public class GrpcGreeterClientTests : IDisposable + { + private readonly ISynchronousPluginPactBuilderV4 pact; + + public GrpcGreeterClientTests(ITestOutputHelper output) + { + var config = new PactConfig + { + PactDir = "../../../../pacts/", + Outputters = new[] { new XunitOutput(output) }, + DefaultJsonSettings = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter() } + }, + LogLevel = PactLogLevel.Information + }; + + this.pact = Pact.V4("grpc-greeter-client", "grpc-greeter", config) + .WithSynchronousPluginInteractions("protobuf", "0.8.0", transport: "grpc"); + } + + [Fact] + public void ThrowsExceptionWhenNoGrpcClientRequestMade() + { + string protoFilePath = Path.Join(Directory.GetCurrentDirectory(), "..", "..", "..", "..", "GrpcGreeterClient", "Protos", "greet.proto"); + var content = new Dictionary + { + { + "pact:proto", protoFilePath + }, + { "pact:proto-service", "Greeter/SayHello" }, + { "pact:content-type", "application/protobuf" }, + { "request", new { name = "matching(equalTo, 'foo')" } }, + { "response", new { message = "matching(equalTo, 'Hello foo')" } } + }; + + this.pact.UponReceiving("A greeting request to say hello.").WithContent("application/grpc", content); + + this.pact.Invoking(p => p.Verify(_ => { })).Should().Throw(); + } + + [Fact] + public async Task WritesPactForGreeterSayHelloRequest() + { + string protoFilePath = Path.Join(Directory.GetCurrentDirectory(), "..", "..", "..", "..", "GrpcGreeterClient", "Protos", "greet.proto"); + var content = new Dictionary + { + { + "pact:proto", protoFilePath + }, + { "pact:proto-service", "Greeter/SayHello" }, + { "pact:content-type", "application/protobuf" }, + { "request", new { name = "matching(equalTo, 'foo')" } }, + { "response", new { message = "matching(equalTo, 'Hello foo')" } } + }; + + + this.pact.UponReceiving("A greeting request to say hello.").WithContent("application/grpc", content); + + await this.pact.VerifyAsync(async ctx => + { + + // Arrange + var client = new GreeterClientWrapper(ctx.MockServerUri.AbsoluteUri); + + // Act + var greeting = await client.SayHello("foo"); + + // Assert + greeting.Should().Be("Hello foo"); + }); + } + + public void Dispose() => this.pact?.Dispose(); + } +} diff --git a/samples/Grpc/GrpcGreeterClient/GrpcGreeterClient.csproj b/samples/Grpc/GrpcGreeterClient/GrpcGreeterClient.csproj new file mode 100644 index 000000000..91ded7553 --- /dev/null +++ b/samples/Grpc/GrpcGreeterClient/GrpcGreeterClient.csproj @@ -0,0 +1,25 @@ + + + + Exe + net8.0 + enable + enable + + + false + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + diff --git a/samples/Grpc/GrpcGreeterClient/Program.cs b/samples/Grpc/GrpcGreeterClient/Program.cs new file mode 100644 index 000000000..7beb6292f --- /dev/null +++ b/samples/Grpc/GrpcGreeterClient/Program.cs @@ -0,0 +1,32 @@ +using Grpc.Net.Client; +using GrpcGreeterClient; + +public class GreeterClientWrapper +{ + private readonly Greeter.GreeterClient _client; + + public GreeterClientWrapper(string url) + { + var channel = GrpcChannel.ForAddress(url); + _client = new Greeter.GreeterClient(channel); + } + + public async Task SayHello(string name) + { + var reply = await _client.SayHelloAsync(new HelloRequest { Name = name }); + return reply.Message; + } +} + +public class Program +{ + public static async Task Main(string[] args) + { + var client = new GreeterClientWrapper("http://localhost:5099"); + // var client = new GreeterClientWrapper("https://localhost:5099"); + var greeting = await client.SayHello("GreeterClient"); + Console.WriteLine("Greeting: " + greeting); + Console.WriteLine("Press any key to exit..."); + Console.ReadKey(); + } +} diff --git a/samples/Grpc/GrpcGreeterClient/Protos/greet.proto b/samples/Grpc/GrpcGreeterClient/Protos/greet.proto new file mode 100644 index 000000000..1a0159522 --- /dev/null +++ b/samples/Grpc/GrpcGreeterClient/Protos/greet.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; + +option csharp_namespace = "GrpcGreeterClient"; + +package greet; + +// The greeting service definition. +service Greeter { + // Sends a greeting + rpc SayHello (HelloRequest) returns (HelloReply); +} + +// The request message containing the user's name. +message HelloRequest { + string name = 1; +} + +// The response message containing the greetings. +message HelloReply { + string message = 1; +} diff --git a/samples/Grpc/pacts/grpc-greeter-client-grpc-greeter.json b/samples/Grpc/pacts/grpc-greeter-client-grpc-greeter.json new file mode 100644 index 000000000..74ae5ec6c --- /dev/null +++ b/samples/Grpc/pacts/grpc-greeter-client-grpc-greeter.json @@ -0,0 +1,108 @@ +{ + "consumer": { + "name": "grpc-greeter-client" + }, + "interactions": [ + { + "description": "A greeting request to say hello.", + "interactionMarkup": { + "markup": "```protobuf\nmessage HelloReply {\n string message = 1;\n}\n```\n", + "markupType": "COMMON_MARK" + }, + "pending": false, + "pluginConfiguration": { + "protobuf": { + "descriptorKey": "d779ad0dfd0c93ac53c5b1f6fa648d76", + "expectations": { + "request": { + "name": "matching(equalTo, 'foo')" + }, + "response": { + "message": "matching(equalTo, 'Hello foo')" + } + }, + "service": ".greet.Greeter/SayHello" + } + }, + "request": { + "contents": { + "content": "CgNmb28=", + "contentType": "application/protobuf;message=.greet.HelloRequest", + "contentTypeHint": "BINARY", + "encoded": "base64" + }, + "matchingRules": { + "body": { + "$.name": { + "combine": "AND", + "matchers": [ + { + "match": "equality" + } + ] + } + } + }, + "metadata": { + "contentType": "application/protobuf;message=.greet.HelloRequest" + } + }, + "response": [ + { + "contents": { + "content": "CglIZWxsbyBmb28=", + "contentType": "application/protobuf;message=.greet.HelloReply", + "contentTypeHint": "BINARY", + "encoded": "base64" + }, + "matchingRules": { + "body": { + "$.message": { + "combine": "AND", + "matchers": [ + { + "match": "equality" + } + ] + } + } + }, + "metadata": { + "contentType": "application/protobuf;message=.greet.HelloReply" + } + } + ], + "transport": "grpc", + "type": "Synchronous/Messages" + } + ], + "metadata": { + "pactRust": { + "ffi": "0.5.13", + "mockserver": "0.5.13", + "models": "1.3.18" + }, + "pactSpecification": { + "version": "4.0" + }, + "plugins": [ + { + "configuration": { + "d779ad0dfd0c93ac53c5b1f6fa648d76": { + "protoDescriptors": "CvsECgtncmVldC5wcm90bxIFZ3JlZXQiIgoMSGVsbG9SZXF1ZXN0EhIKBG5hbWUYASABKAlSBG5hbWUiJgoKSGVsbG9SZXBseRIYCgdtZXNzYWdlGAEgASgJUgdtZXNzYWdlMj0KB0dyZWV0ZXISMgoIU2F5SGVsbG8SEy5ncmVldC5IZWxsb1JlcXVlc3QaES5ncmVldC5IZWxsb1JlcGx5QhSqAhFHcnBjR3JlZXRlckNsaWVudEq7AwoGEgQAABQBCggKAQISAwQADgo9CgIEABIEDQAPARoxIFRoZSByZXF1ZXN0IG1lc3NhZ2UgY29udGFpbmluZyB0aGUgdXNlcidzIG5hbWUuCgoKCgMEAAESAw0IFAoLCgQEAAIAEgMOAhIKDAoFBAACAAESAw4JDQoMCgUEAAIAAxIDDhARCgwKBQQAAgAFEgMOAggKPAoCBAESBBIAFAEaMCBUaGUgcmVzcG9uc2UgbWVzc2FnZSBjb250YWluaW5nIHRoZSBncmVldGluZ3MuCgoKCgMEAQESAxIIEgoLCgQEAQIAEgMTAhUKDAoFBAECAAESAxMJEAoMCgUEAQIAAxIDExMUCgwKBQQBAgAFEgMTAggKLgoCBgASBAcACgEaIiBUaGUgZ3JlZXRpbmcgc2VydmljZSBkZWZpbml0aW9uLgoKCgoDBgABEgMHCA8KHwoEBgACABIDCQIzGhIgU2VuZHMgYSBncmVldGluZwoKDAoFBgACAAESAwkGDgoMCgUGAAIAAhIDCRAcCgwKBQYAAgADEgMJJzEKCAoBCBIDAgAuCgkKAgglEgMCAC4KCAoBDBIDAAASYgZwcm90bzM=", + "protoFile": "syntax = \"proto3\";\r\n\r\noption csharp_namespace = \"GrpcGreeterClient\";\r\n\r\npackage greet;\r\n\r\n// The greeting service definition.\r\nservice Greeter {\r\n // Sends a greeting\r\n rpc SayHello (HelloRequest) returns (HelloReply);\r\n}\r\n\r\n// The request message containing the user's name.\r\nmessage HelloRequest {\r\n string name = 1;\r\n}\r\n\r\n// The response message containing the greetings.\r\nmessage HelloReply {\r\n string message = 1;\r\n}\r\n" + }, + "e8e1fe144f808b9b0faecd7b2605efea": { + "protoDescriptors": "Cr0BCgtncmVldC5wcm90bxIFZ3JlZXQiIgoMSGVsbG9SZXF1ZXN0EhIKBG5hbWUYASABKAlSBG5hbWUiJgoKSGVsbG9SZXBseRIYCgdtZXNzYWdlGAEgASgJUgdtZXNzYWdlMj0KB0dyZWV0ZXISMgoIU2F5SGVsbG8SEy5ncmVldC5IZWxsb1JlcXVlc3QaES5ncmVldC5IZWxsb1JlcGx5QhSqAhFHcnBjR3JlZXRlckNsaWVudGIGcHJvdG8z", + "protoFile": "syntax = \"proto3\";\r\n\r\noption csharp_namespace = \"GrpcGreeterClient\";\r\n\r\npackage greet;\r\n\r\n// The greeting service definition.\r\nservice Greeter {\r\n // Sends a greeting\r\n rpc SayHello (HelloRequest) returns (HelloReply);\r\n}\r\n\r\n// The request message containing the user's name.\r\nmessage HelloRequest {\r\n string name = 1;\r\n}\r\n\r\n// The response message containing the greetings.\r\nmessage HelloReply {\r\n string message = 1;\r\n}\r\n" + } + }, + "name": "protobuf", + "version": "0.8.0" + } + ] + }, + "provider": { + "name": "grpc-greeter" + } +} \ No newline at end of file diff --git a/samples/OrdersApi/Consumer.Tests/pacts/Fulfilment API-Orders API.json b/samples/OrdersApi/Consumer.Tests/pacts/Fulfilment API-Orders API.json index b6f1a702c..6ad0687eb 100644 --- a/samples/OrdersApi/Consumer.Tests/pacts/Fulfilment API-Orders API.json +++ b/samples/OrdersApi/Consumer.Tests/pacts/Fulfilment API-Orders API.json @@ -69,6 +69,7 @@ }, "status": 200 }, + "transport": "http", "type": "Synchronous/HTTP" }, { @@ -86,6 +87,7 @@ "response": { "status": 404 }, + "transport": "http", "type": "Synchronous/HTTP" }, { @@ -129,6 +131,7 @@ "response": { "status": 204 }, + "transport": "http", "type": "Synchronous/HTTP" }, { @@ -158,8 +161,9 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.13", + "mockserver": "2.2.7", + "models": "1.3.18" }, "pactSpecification": { "version": "4.0" diff --git a/samples/OrdersApi/Provider.Tests/Provider.Tests.csproj b/samples/OrdersApi/Provider.Tests/Provider.Tests.csproj index 1517e0f40..dbae7d988 100644 --- a/samples/OrdersApi/Provider.Tests/Provider.Tests.csproj +++ b/samples/OrdersApi/Provider.Tests/Provider.Tests.csproj @@ -2,6 +2,9 @@ net8.0 false + + false diff --git a/samples/OrdersApi/Provider.Tests/ProviderTests.cs b/samples/OrdersApi/Provider.Tests/ProviderTests.cs index 1feb302ef..e8c6e8ec1 100644 --- a/samples/OrdersApi/Provider.Tests/ProviderTests.cs +++ b/samples/OrdersApi/Provider.Tests/ProviderTests.cs @@ -16,7 +16,7 @@ namespace Provider.Tests { public class ProviderTests : IDisposable { - private static readonly Uri ProviderUri = new("http://localhost:5000"); + private static readonly Uri ProviderUri = new("http://localhost:65098"); private static readonly JsonSerializerOptions Options = new() { @@ -38,7 +38,7 @@ public ProviderTests(ITestOutputHelper output) .Build(); this.server.Start(); - + this.verifier = new PactVerifier("Orders API", new PactVerifierConfig { LogLevel = PactLogLevel.Debug, diff --git a/src/PactNet.Abstractions/IHttpPluginPactBuilder.cs b/src/PactNet.Abstractions/IHttpPluginPactBuilder.cs new file mode 100644 index 000000000..bb9f08308 --- /dev/null +++ b/src/PactNet.Abstractions/IHttpPluginPactBuilder.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; + +namespace PactNet +{ + /// HTTP interactions using a plugin to configure and match their contents. + public interface IHttpPluginPactBuilderV4 : IPactBuilder, IDisposable + { + /// Start an HTTP interaction. + IHttpPluginRequestBuilderV4 UponReceiving(string description); + } + + /// Configure an HTTP request before defining its response. + public interface IHttpPluginRequestBuilderV4 + { + /// Add a provider state. + IHttpPluginRequestBuilderV4 Given(string description); + /// Add a parameterized provider state. + IHttpPluginRequestBuilderV4 Given(string description, string name, string value); + /// Set the HTTP method and path. + IHttpPluginRequestBuilderV4 WithRequest(HttpMethod method, string path); + /// Add a query parameter. + IHttpPluginRequestBuilderV4 WithQuery(string name, string value); + /// Add a request header. + IHttpPluginRequestBuilderV4 WithHeader(string name, string value); + /// Configure request contents once using the plugin's contents schema. + IHttpPluginRequestBuilderV4 WithContent(string contentType, Dictionary content); + /// Complete the request and begin the response. + IHttpPluginResponseBuilderV4 WillRespondWithStatus(int status); + } + + /// Configure an HTTP response using plugin contents. + public interface IHttpPluginResponseBuilderV4 + { + /// Add a response header before setting contents. + IHttpPluginResponseBuilderV4 WithHeader(string name, string value); + /// Configure response contents once, completing this interaction. + void WithContent(string contentType, Dictionary content); + } +} \ No newline at end of file diff --git a/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs b/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs new file mode 100644 index 000000000..cb13585e8 --- /dev/null +++ b/src/PactNet.Abstractions/ISynchronousPluginPactBuilder.cs @@ -0,0 +1,17 @@ +using System; + +namespace PactNet +{ + /// + /// Synchronous plugin-based pact builder + /// + public interface ISynchronousPluginPactBuilderV4 : IPactBuilder, IDisposable + { + /// + /// Add a new interaction to the pact + /// + /// Interaction description + /// Fluent builder + ISynchronousPluginRequestBuilderV4 UponReceiving(string description); + } +} diff --git a/src/PactNet.Abstractions/ISynchronousPluginRequestBuilder.cs b/src/PactNet.Abstractions/ISynchronousPluginRequestBuilder.cs new file mode 100644 index 000000000..ef2c40fdc --- /dev/null +++ b/src/PactNet.Abstractions/ISynchronousPluginRequestBuilder.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; + +namespace PactNet +{ + /// + /// Synchronous plugin request builder for V4 pacts + /// + public interface ISynchronousPluginRequestBuilderV4 + { + /// + /// Add a provider state + /// + /// Provider state description + /// Fluent builder + ISynchronousPluginRequestBuilderV4 Given(string description); + + /// + /// Add a provider state with a parameter to the interaction + /// + /// Provider state description + /// Parameter name + /// Parameter value + ISynchronousPluginRequestBuilderV4 Given(string description, string name, string value); + + /// + /// Set the plugin interaction contents. This completes the interaction and must be the last call. + /// + /// + /// The plugin interprets the contents and splits them into the request and response(s) itself, so + /// this is called exactly once per interaction. Setting the contents again would replace the request + /// but append a further response, which is why the builder does not allow a second call. + /// + /// Content type understood by the plugin, e.g. application/grpc + /// A dictionary containing the plugin content. + void WithContent(string contentType, Dictionary content); + } +} diff --git a/src/PactNet/AbstractPactBuilder.cs b/src/PactNet/AbstractPactBuilder.cs new file mode 100644 index 000000000..6b2cdca00 --- /dev/null +++ b/src/PactNet/AbstractPactBuilder.cs @@ -0,0 +1,137 @@ +using System; +using System.Threading.Tasks; +using PactNet.Drivers; +using PactNet.Exceptions; +using PactNet.Internal; +using PactNet.Models; + +namespace PactNet +{ + /// + /// Abstract pact builder that contains shared functionality of different types of pact interactions. + /// + internal abstract class AbstractPactBuilder : IPactBuilder + { + private readonly ICompletedPactDriver pact; + private readonly PactConfig config; + private readonly int? port; + private readonly IPAddress host; + private readonly string transport; + + /// + /// Initialises a new instance of the class. + /// + /// Pact driver + /// Pact config + /// Optional port, otherwise one is dynamically allocated + /// Optional host, otherwise loopback is used + /// The transport to use (i.e. http, https, grpc). Must be a valid UTF-8 NULL-terminated string, or NULL or empty, in which case http will be used. + protected AbstractPactBuilder(ICompletedPactDriver pact, PactConfig config, int? port, IPAddress host, + string transport = null) + { + this.pact = pact; + this.config = config; + this.port = port; + this.host = host; + this.transport = transport; + } + + /// + /// Verify the configured interactions + /// + /// Action to perform the real interactions against the mock driver + /// Failed to verify the interactions + public virtual void Verify(Action interact) + { + Guard.NotNull(interact, nameof(interact)); + + using IMockServerDriver mockServer = this.StartMockServer(); + + try + { + interact(new ConsumerContext { MockServerUri = mockServer.Uri }); + + this.VerifyInternal(mockServer); + } + finally + { + this.PrintLogs(mockServer); + } + } + + /// + /// Verify the configured interactions + /// + /// Action to perform the real interactions against the mock driver + /// Failed to verify the interactions + public virtual async Task VerifyAsync(Func interact) + { + Guard.NotNull(interact, nameof(interact)); + + using IMockServerDriver mockServer = this.StartMockServer(); + + try + { + await interact(new ConsumerContext { MockServerUri = mockServer.Uri }); + + this.VerifyInternal(mockServer); + } + finally + { + this.PrintLogs(mockServer); + } + } + + /// + /// Start the mock driver + /// + /// Mock driver + private IMockServerDriver StartMockServer() + { + string hostIp = this.host switch + { + IPAddress.Loopback => "127.0.0.1", + IPAddress.Any => "0.0.0.0", + _ => throw new ArgumentOutOfRangeException(nameof(this.host), this.host, "Unsupported IPAddress value") + }; + + // TODO: add TLS support + return this.pact.CreateMockServer(hostIp, this.port, false, transport); + } + + /// + /// Verify the interactions after the consumer client has been invoked + /// + /// Mock server + private void VerifyInternal(IMockServerDriver mockServer) + { + string errors = mockServer.MockServerMismatches(); + + if (string.IsNullOrWhiteSpace(errors) || errors == "[]") + { + this.pact.WritePactFile(mockServer.Port, this.config.PactDir); + return; + } + + this.config.WriteLine(string.Empty); + this.config.WriteLine("Verification mismatches:"); + this.config.WriteLine(string.Empty); + this.config.WriteLine(errors); + + throw new PactFailureException("Pact verification failed. See output for details"); + } + + /// + /// Print logs to the configured outputs + /// + /// Mock server + private void PrintLogs(IMockServerDriver mockServer) + { + string logs = mockServer.MockServerLogs(); + + this.config.WriteLine("Mock driver logs:"); + this.config.WriteLine(string.Empty); + this.config.WriteLine(logs); + } + } +} diff --git a/src/PactNet/ConfiguredMessageVerifier.cs b/src/PactNet/ConfiguredMessageVerifier.cs index 45f125d24..46b758f36 100644 --- a/src/PactNet/ConfiguredMessageVerifier.cs +++ b/src/PactNet/ConfiguredMessageVerifier.cs @@ -1,7 +1,7 @@ using System; using System.Text.Json; using System.Threading.Tasks; -using PactNet.Drivers; +using PactNet.Drivers.Message; using PactNet.Exceptions; using PactNet.Interop; using PactNet.Models; diff --git a/src/PactNet/Drivers/AbstractPactDriver.cs b/src/PactNet/Drivers/AbstractPactDriver.cs index 8e70fc3c2..36d1124b5 100644 --- a/src/PactNet/Drivers/AbstractPactDriver.cs +++ b/src/PactNet/Drivers/AbstractPactDriver.cs @@ -8,7 +8,7 @@ namespace PactNet.Drivers /// internal abstract class AbstractPactDriver : ICompletedPactDriver { - private readonly PactHandle pact; + protected readonly PactHandle pact; /// /// Initialises a new instance of the class. @@ -27,8 +27,23 @@ protected AbstractPactDriver(PactHandle pact) /// Failed to write pact file public void WritePactFile(string directory) { - var result = NativeInterop.WritePactFile(this.pact, directory, false); + int result = NativeInterop.WritePactFile(this.pact, directory, false); + ThrowExceptionOnWritePactFileFailure(result); + } + + /// + /// Write the pact file to disk + /// + /// Port of the mock server + /// Directory of the pact file + public void WritePactFile(int port, string directory) + { + int result = NativeInterop.WritePactFileForPort(port, directory, false); + ThrowExceptionOnWritePactFileFailure(result); + } + private static void ThrowExceptionOnWritePactFileFailure(int result) + { if (result != 0) { throw result switch @@ -40,5 +55,34 @@ public void WritePactFile(string directory) }; } } + + /// + /// Create the mock server for the current pact + /// + /// Host for the mock server + /// Port for the mock server, or null to allocate one automatically + /// Enable TLS + /// The transport to use (i.e. http, https, grpc). Must be a valid UTF-8 NULL-terminated string, or NULL or empty, in which case http will be used. + /// Mock server port + /// Failed to start mock server + public IMockServerDriver CreateMockServer(string host, int? port, bool tls, string transport = null) + { + int result = NativeInterop.CreateMockServerForTransport(this.pact, host, (ushort)port.GetValueOrDefault(0), transport, null); + + if (result > 0) + { + return new MockServerDriver(host, result, tls); + } + + throw result switch + { + -1 => new InvalidOperationException("Invalid handle when starting mock server"), + -3 => new InvalidOperationException("Unable to start mock server"), + -4 => new InvalidOperationException("The pact reference library panicked"), + -5 => new InvalidOperationException("The IPAddress is invalid"), + -6 => new InvalidOperationException("Could not create the TLS configuration with the self-signed certificate"), + _ => new InvalidOperationException($"Unknown mock server error: {result}") + }; + } } } diff --git a/src/PactNet/Drivers/HttpInteractionDriver.cs b/src/PactNet/Drivers/Http/HttpInteractionDriver.cs similarity index 94% rename from src/PactNet/Drivers/HttpInteractionDriver.cs rename to src/PactNet/Drivers/Http/HttpInteractionDriver.cs index a91d6b4f2..6072ca6d3 100644 --- a/src/PactNet/Drivers/HttpInteractionDriver.cs +++ b/src/PactNet/Drivers/Http/HttpInteractionDriver.cs @@ -1,24 +1,21 @@ using System; using PactNet.Interop; -namespace PactNet.Drivers +namespace PactNet.Drivers.Http { /// /// Driver for synchronous HTTP interactions /// internal class HttpInteractionDriver : IHttpInteractionDriver { - private readonly PactHandle pact; private readonly InteractionHandle interaction; /// /// Initialises a new instance of the class. /// - /// Pact handle /// Interaction handle - internal HttpInteractionDriver(PactHandle pact, InteractionHandle interaction) + internal HttpInteractionDriver(InteractionHandle interaction) { - this.pact = pact; this.interaction = interaction; } diff --git a/src/PactNet/Drivers/Http/HttpPactDriver.cs b/src/PactNet/Drivers/Http/HttpPactDriver.cs new file mode 100644 index 000000000..7c8395ff9 --- /dev/null +++ b/src/PactNet/Drivers/Http/HttpPactDriver.cs @@ -0,0 +1,30 @@ +using System; +using PactNet.Interop; + +namespace PactNet.Drivers.Http +{ + /// + /// Driver for synchronous HTTP pacts + /// + internal class HttpPactDriver : AbstractPactDriver, IHttpPactDriver + { + /// + /// Initialises a new instance of the class. + /// + /// Pact handle + internal HttpPactDriver(PactHandle pact) : base(pact) + { + } + + /// + /// Create a new interaction on the current pact + /// + /// Interaction description + /// HTTP interaction handle + public IHttpInteractionDriver NewHttpInteraction(string description) + { + InteractionHandle interaction = NativeInterop.NewInteraction(this.pact, description); + return new HttpInteractionDriver(interaction); + } + } +} diff --git a/src/PactNet/Drivers/IHttpInteractionDriver.cs b/src/PactNet/Drivers/Http/IHttpInteractionDriver.cs similarity index 98% rename from src/PactNet/Drivers/IHttpInteractionDriver.cs rename to src/PactNet/Drivers/Http/IHttpInteractionDriver.cs index ccb1473e0..653ce2fcb 100644 --- a/src/PactNet/Drivers/IHttpInteractionDriver.cs +++ b/src/PactNet/Drivers/Http/IHttpInteractionDriver.cs @@ -1,4 +1,4 @@ -namespace PactNet.Drivers +namespace PactNet.Drivers.Http { /// /// Driver for synchronous HTTP interactions diff --git a/src/PactNet/Drivers/Http/IHttpPactDriver.cs b/src/PactNet/Drivers/Http/IHttpPactDriver.cs new file mode 100644 index 000000000..0194f34b2 --- /dev/null +++ b/src/PactNet/Drivers/Http/IHttpPactDriver.cs @@ -0,0 +1,17 @@ +using System; + +namespace PactNet.Drivers.Http +{ + /// + /// Driver for synchronous HTTP pacts + /// + internal interface IHttpPactDriver : ICompletedPactDriver + { + /// + /// Create a new interaction on the current pact + /// + /// Interaction description + /// HTTP interaction handle + IHttpInteractionDriver NewHttpInteraction(string description); + } +} diff --git a/src/PactNet/Drivers/HttpPactDriver.cs b/src/PactNet/Drivers/HttpPactDriver.cs deleted file mode 100644 index 52026bff8..000000000 --- a/src/PactNet/Drivers/HttpPactDriver.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using PactNet.Interop; - -namespace PactNet.Drivers -{ - /// - /// Driver for synchronous HTTP pacts - /// - internal class HttpPactDriver : AbstractPactDriver, IHttpPactDriver - { - private readonly PactHandle pact; - - /// - /// Initialises a new instance of the class. - /// - /// Pact handle - internal HttpPactDriver(PactHandle pact) : base(pact) - { - this.pact = pact; - } - - /// - /// Create a new interaction on the current pact - /// - /// Interaction description - /// HTTP interaction handle - public IHttpInteractionDriver NewHttpInteraction(string description) - { - InteractionHandle interaction = NativeInterop.NewInteraction(this.pact, description); - return new HttpInteractionDriver(this.pact, interaction); - } - - /// - /// Create the mock server for the current pact - /// - /// Host for the mock server - /// Port for the mock server, or null to allocate one automatically - /// Enable TLS - /// Mock server port - /// Failed to start mock server - public IMockServerDriver CreateMockServer(string host, int? port, bool tls) - { - int result = NativeInterop.CreateMockServerForTransport(this.pact, host, (ushort)port.GetValueOrDefault(0), "http", null); - - if (result > 0) - { - return new MockServerDriver(host, result, tls); - } - - throw result switch - { - -1 => new InvalidOperationException("Invalid handle when starting mock server"), - -3 => new InvalidOperationException("Unable to start mock server"), - -4 => new InvalidOperationException("The pact reference library panicked"), - -5 => new InvalidOperationException("The IPAddress is invalid"), - -6 => new InvalidOperationException("Could not create the TLS configuration with the self-signed certificate"), - _ => new InvalidOperationException($"Unknown mock server error: {result}") - }; - } - } -} diff --git a/src/PactNet/Drivers/ICompletedPactDriver.cs b/src/PactNet/Drivers/ICompletedPactDriver.cs index 199b075d9..eb102950a 100644 --- a/src/PactNet/Drivers/ICompletedPactDriver.cs +++ b/src/PactNet/Drivers/ICompletedPactDriver.cs @@ -14,5 +14,23 @@ internal interface ICompletedPactDriver /// Status code /// Failed to write pact file void WritePactFile(string directory); + + /// + /// Write the pact file to disk + /// + /// Port of the mock server + /// Directory of the pact file + void WritePactFile(int port, string directory); + + /// + /// Create the mock server for the current pact + /// + /// Host for the mock server + /// Port for the mock server, or null to allocate one automatically + /// Enable TLS + /// The transport to use (i.e. http, https, grpc). Must be a valid UTF-8 NULL-terminated string, or NULL or empty, in which case http will be used. + /// Mock server port + /// Failed to start mock server + IMockServerDriver CreateMockServer(string host, int? port, bool tls, string transport = null); } } diff --git a/src/PactNet/Drivers/IHttpPactDriver.cs b/src/PactNet/Drivers/IHttpPactDriver.cs deleted file mode 100644 index 8cb815ffb..000000000 --- a/src/PactNet/Drivers/IHttpPactDriver.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; - -namespace PactNet.Drivers -{ - /// - /// Driver for synchronous HTTP pacts - /// - internal interface IHttpPactDriver : ICompletedPactDriver - { - /// - /// Create a new interaction on the current pact - /// - /// Interaction description - /// HTTP interaction handle - IHttpInteractionDriver NewHttpInteraction(string description); - - /// - /// Create the mock server for the current pact - /// - /// Host for the mock server - /// Port for the mock server, or null to allocate one automatically - /// Enable TLS - /// Mock server port - /// Failed to start mock server - IMockServerDriver CreateMockServer(string host, int? port, bool tls); - } -} diff --git a/src/PactNet/Drivers/IMockServerDriver.cs b/src/PactNet/Drivers/IMockServerDriver.cs index 8060613ea..3d93742e5 100644 --- a/src/PactNet/Drivers/IMockServerDriver.cs +++ b/src/PactNet/Drivers/IMockServerDriver.cs @@ -7,6 +7,11 @@ namespace PactNet.Drivers /// internal interface IMockServerDriver : IDisposable { + /// + /// Mock server port + /// + int Port { get; } + /// /// Mock server URI /// diff --git a/src/PactNet/Drivers/IPactDriver.cs b/src/PactNet/Drivers/IPactDriver.cs index 449aac9a4..a5ce11483 100644 --- a/src/PactNet/Drivers/IPactDriver.cs +++ b/src/PactNet/Drivers/IPactDriver.cs @@ -1,9 +1,12 @@ -using PactNet.Interop; +using PactNet.Drivers.Http; +using PactNet.Drivers.Message; +using PactNet.Drivers.Plugins; +using PactNet.Interop; namespace PactNet.Drivers { /// - /// Driver for creating a new pact and + /// Driver for creating a new pact and /// internal interface IPactDriver { @@ -22,9 +25,20 @@ internal interface IPactDriver /// Consumer name /// Provider name /// Specification version - /// Message pact driver driver + /// Message pact driver IMessagePactDriver NewMessagePact(string consumerName, string providerName, PactSpecification version); + /// + /// Create a new plugin pact + /// + /// Consumer name + /// Provider name + /// Plugin name + /// Plugin version + /// Specification version + /// Plugin pact driver + IPluginPactDriver NewPluginPact(string consumerName, string providerName, string pluginName, string pluginVersion, PactSpecification version); + /// /// Get the driver logs /// diff --git a/src/PactNet/Drivers/IMessageInteractionDriver.cs b/src/PactNet/Drivers/Message/IMessageInteractionDriver.cs similarity index 97% rename from src/PactNet/Drivers/IMessageInteractionDriver.cs rename to src/PactNet/Drivers/Message/IMessageInteractionDriver.cs index 964b8377f..ec3ec38fb 100644 --- a/src/PactNet/Drivers/IMessageInteractionDriver.cs +++ b/src/PactNet/Drivers/Message/IMessageInteractionDriver.cs @@ -1,4 +1,4 @@ -namespace PactNet.Drivers +namespace PactNet.Drivers.Message { /// /// Driver for asynchronous message interactions diff --git a/src/PactNet/Drivers/IMessagePactDriver.cs b/src/PactNet/Drivers/Message/IMessagePactDriver.cs similarity index 95% rename from src/PactNet/Drivers/IMessagePactDriver.cs rename to src/PactNet/Drivers/Message/IMessagePactDriver.cs index 4999226a6..a5c724c86 100644 --- a/src/PactNet/Drivers/IMessagePactDriver.cs +++ b/src/PactNet/Drivers/Message/IMessagePactDriver.cs @@ -1,4 +1,4 @@ -namespace PactNet.Drivers +namespace PactNet.Drivers.Message { /// /// Driver for message pacts diff --git a/src/PactNet/Drivers/MessageInteractionDriver.cs b/src/PactNet/Drivers/Message/MessageInteractionDriver.cs similarity index 98% rename from src/PactNet/Drivers/MessageInteractionDriver.cs rename to src/PactNet/Drivers/Message/MessageInteractionDriver.cs index 035f8f4cc..58ee7128f 100644 --- a/src/PactNet/Drivers/MessageInteractionDriver.cs +++ b/src/PactNet/Drivers/Message/MessageInteractionDriver.cs @@ -2,7 +2,7 @@ using System.Runtime.InteropServices; using PactNet.Interop; -namespace PactNet.Drivers +namespace PactNet.Drivers.Message { /// /// Driver for asynchronous message interactions diff --git a/src/PactNet/Drivers/MessagePactDriver.cs b/src/PactNet/Drivers/Message/MessagePactDriver.cs similarity index 93% rename from src/PactNet/Drivers/MessagePactDriver.cs rename to src/PactNet/Drivers/Message/MessagePactDriver.cs index 11b99c39e..bca25125e 100644 --- a/src/PactNet/Drivers/MessagePactDriver.cs +++ b/src/PactNet/Drivers/Message/MessagePactDriver.cs @@ -1,21 +1,18 @@ using PactNet.Interop; -namespace PactNet.Drivers +namespace PactNet.Drivers.Message { /// /// Driver for message pacts /// internal class MessagePactDriver : AbstractPactDriver, IMessagePactDriver { - private readonly PactHandle pact; - /// /// Initialises a new instance of the class. /// /// Pact handle internal MessagePactDriver(PactHandle pact) : base(pact) { - this.pact = pact; } /// diff --git a/src/PactNet/Drivers/MockServerDriver.cs b/src/PactNet/Drivers/MockServerDriver.cs index bc92485f9..f146404d2 100644 --- a/src/PactNet/Drivers/MockServerDriver.cs +++ b/src/PactNet/Drivers/MockServerDriver.cs @@ -9,7 +9,12 @@ namespace PactNet.Drivers /// internal class MockServerDriver : IMockServerDriver { - private readonly int port; + + /// + /// Mock server port + /// + public int Port { get; } + /// /// Mock server URI @@ -26,7 +31,7 @@ internal MockServerDriver(string host, int port, bool tls) { string scheme = tls ? "https" : "http"; this.Uri = new Uri($"{scheme}://{host}:{port}"); - this.port = port; + this.Port = port; } /// @@ -35,7 +40,7 @@ internal MockServerDriver(string host, int port, bool tls) /// Mismatch string public string MockServerMismatches() { - IntPtr matchesPtr = NativeInterop.MockServerMismatches(this.port); + IntPtr matchesPtr = NativeInterop.MockServerMismatches(this.Port); return matchesPtr == IntPtr.Zero ? string.Empty @@ -48,12 +53,9 @@ public string MockServerMismatches() /// Log string public string MockServerLogs() { - IntPtr logsPtr = NativeInterop.MockServerLogs(this.port); - - return logsPtr == IntPtr.Zero - ? "ERROR: Unable to retrieve mock server logs" - : Marshal.PtrToStringAnsi(logsPtr); + return NativeInterop.FetchLogBuffer(null); } + /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// @@ -76,7 +78,7 @@ public void Dispose() /// private void ReleaseUnmanagedResources() { - NativeInterop.CleanupMockServer(this.port); + NativeInterop.CleanupMockServer(this.Port); } } } diff --git a/src/PactNet/Drivers/PactDriver.cs b/src/PactNet/Drivers/PactDriver.cs index bce352796..c65e54670 100644 --- a/src/PactNet/Drivers/PactDriver.cs +++ b/src/PactNet/Drivers/PactDriver.cs @@ -1,4 +1,8 @@ -using PactNet.Interop; +using PactNet.Drivers.Http; +using PactNet.Drivers.Message; +using PactNet.Drivers.Plugins; +using PactNet.Exceptions; +using PactNet.Interop; namespace PactNet.Drivers { @@ -16,9 +20,7 @@ internal class PactDriver : IPactDriver /// HTTP pact driver public IHttpPactDriver NewHttpPact(string consumerName, string providerName, PactSpecification version) { - PactHandle pact = NativeInterop.NewPact(consumerName, providerName); - NativeInterop.WithSpecification(pact, version).CheckInteropSuccess(); - + PactHandle pact = CreatePactHandle(consumerName, providerName, version); return new HttpPactDriver(pact); } @@ -28,13 +30,54 @@ public IHttpPactDriver NewHttpPact(string consumerName, string providerName, Pac /// Consumer name /// Provider name /// Specification version - /// Message pact driver driver + /// Message pact driver public IMessagePactDriver NewMessagePact(string consumerName, string providerName, PactSpecification version) + { + PactHandle pact = CreatePactHandle(consumerName, providerName, version); + return new MessagePactDriver(pact); + } + + /// + /// Create a new plugin pact + /// + /// Consumer name + /// Provider name + /// Plugin name + /// Plugin version + /// Specification version + /// Plugin pact driver + public IPluginPactDriver NewPluginPact(string consumerName, string providerName, string pluginName, string pluginVersion, PactSpecification version) + { + PactHandle pact = CreatePactHandle(consumerName, providerName, version); + + uint code = NativeInterop.UsingPlugin(pact, pluginName, pluginVersion); + + if (code == 0) + { + return new PluginPactDriver(pact); + } + + throw code switch + { + 1 => new PactFailureException("Unable to setup the plugin - general panic"), + 2 => new PactFailureException("Unable to setup the plugin - invalid plugin name or version"), + 3 => new PactFailureException("Unable to setup the plugin - invalid pact handle"), + _ => new PactFailureException($"Unable to setup the plugin - unknown error {code}") + }; + } + + /// + /// Create a new pact handle and set the specification version + /// + /// Consumer name + /// Provider name + /// Specification version + /// Pact handle + private static PactHandle CreatePactHandle(string consumerName, string providerName, PactSpecification version) { PactHandle pact = NativeInterop.NewPact(consumerName, providerName); NativeInterop.WithSpecification(pact, version).CheckInteropSuccess(); - - return new MessagePactDriver(pact); + return pact; } /// diff --git a/src/PactNet/Drivers/Plugins/HttpPluginInteractionDriver.cs b/src/PactNet/Drivers/Plugins/HttpPluginInteractionDriver.cs new file mode 100644 index 000000000..bc8c0d979 --- /dev/null +++ b/src/PactNet/Drivers/Plugins/HttpPluginInteractionDriver.cs @@ -0,0 +1,35 @@ +using System.Collections.Generic; +using PactNet.Drivers.Http; +using PactNet.Interop; + +namespace PactNet.Drivers.Plugins +{ + internal interface IHttpPluginInteractionDriver : IHttpInteractionDriver + { + void WithPluginContent(InteractionPart part, string contentType, Dictionary content); + } + + internal class HttpPluginInteractionDriver : IHttpPluginInteractionDriver + { + private readonly HttpInteractionDriver http; + private readonly PluginInteractionDriver plugin; + + internal HttpPluginInteractionDriver(InteractionHandle interaction) + { + this.http = new HttpInteractionDriver(interaction); + this.plugin = new PluginInteractionDriver(interaction); + } + + public void Given(string description) => this.http.Given(description); + public void GivenWithParam(string description, string name, string value) => this.http.GivenWithParam(description, name, value); + public void WithRequest(string method, string path) => this.http.WithRequest(method, path); + public void WithQueryParameter(string name, string value, uint index) => this.http.WithQueryParameter(name, value, index); + public void WithRequestHeader(string name, string value, uint index) => this.http.WithRequestHeader(name, value, index); + public void WithResponseHeader(string name, string value, uint index) => this.http.WithResponseHeader(name, value, index); + public void WithResponseStatus(ushort status) => this.http.WithResponseStatus(status); + public void WithRequestBody(string contentType, string body) => this.http.WithRequestBody(contentType, body); + public void WithResponseBody(string contentType, string body) => this.http.WithResponseBody(contentType, body); + public void WithPluginContent(InteractionPart part, string contentType, Dictionary content) + => this.plugin.WithContent(part, contentType, content); + } +} \ No newline at end of file diff --git a/src/PactNet/Drivers/Plugins/IPluginInteractionDriver.cs b/src/PactNet/Drivers/Plugins/IPluginInteractionDriver.cs new file mode 100644 index 000000000..7b6fa41f5 --- /dev/null +++ b/src/PactNet/Drivers/Plugins/IPluginInteractionDriver.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; + +namespace PactNet.Drivers.Plugins +{ + /// + /// Driver for plugin interactions + /// + internal interface IPluginInteractionDriver : IProviderStateDriver + { + /// + /// Add a plugin interaction content + /// + /// Content type + /// A dictionary containing the plugin content. + void WithContent(string contentType, Dictionary content); + } +} diff --git a/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs b/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs new file mode 100644 index 000000000..3d5912daa --- /dev/null +++ b/src/PactNet/Drivers/Plugins/IPluginPactDriver.cs @@ -0,0 +1,18 @@ +using System; + +namespace PactNet.Drivers.Plugins +{ + /// + /// Driver for plugin-based pacts + /// + internal interface IPluginPactDriver : ICompletedPactDriver, IDisposable + { + /// + /// Create a new sync interaction on the current pact + /// + /// Interaction description + /// Interaction driver + IPluginInteractionDriver NewSyncInteraction(string description); + IHttpPluginInteractionDriver NewHttpPluginInteraction(string description); + } +} diff --git a/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs b/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs new file mode 100644 index 000000000..215b8c375 --- /dev/null +++ b/src/PactNet/Drivers/Plugins/PluginInteractionDriver.cs @@ -0,0 +1,67 @@ +using System.Collections.Generic; +using System.Text.Json; +using PactNet.Exceptions; +using PactNet.Interop; + +namespace PactNet.Drivers.Plugins +{ + /// + /// Driver for plugin interactions + /// + internal class PluginInteractionDriver : IPluginInteractionDriver + { + private readonly InteractionHandle interaction; + + /// + /// Initialises a new instance of the class. + /// + /// Interaction handle + public PluginInteractionDriver(InteractionHandle interaction) + { + this.interaction = interaction; + } + + /// + /// Add a provider state to the interaction + /// + /// Provider state description + public void Given(string description) + => NativeInterop.Given(this.interaction, description).CheckInteropSuccess(); + + /// + /// Add a provider state with a parameter to the interaction + /// + /// Provider state description + /// Parameter name + /// Parameter value + public void GivenWithParam(string description, string name, string value) + => NativeInterop.GivenWithParam(this.interaction, description, name, value).CheckInteropSuccess(); + + /// + /// Add plugin interaction content + /// + /// Content type + /// A dictionary containing the plugin content. + public void WithContent(string contentType, Dictionary content) + => this.WithContent(InteractionPart.Request, contentType, content); + + internal void WithContent(InteractionPart part, string contentType, Dictionary content) + { + uint code = NativeInterop.InteractionContents(this.interaction, part, contentType, JsonSerializer.Serialize(content)); + + if (code != 0) + { + throw code switch + { + 1 => new PactFailureException("A general panic was caught"), + 2 => new PactFailureException("The mock server has already been started"), + 3 => new PactFailureException("The interaction handle is invalid"), + 4 => new PactFailureException("The content type is not valid"), + 5 => new PactFailureException("The contents JSON is not valid JSON"), + 6 => new PactFailureException("The plugin returned an error"), + _ => new PactFailureException($"An unknown error occurred when setting the interaction contents: {code}"), + }; + } + } + } +} diff --git a/src/PactNet/Drivers/Plugins/PluginPactDriver.cs b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs new file mode 100644 index 000000000..33c6b0e2b --- /dev/null +++ b/src/PactNet/Drivers/Plugins/PluginPactDriver.cs @@ -0,0 +1,61 @@ +using System; +using PactNet.Interop; + +namespace PactNet.Drivers.Plugins +{ + /// + /// Driver for plugin-based pacts + /// + internal class PluginPactDriver : AbstractPactDriver, IPluginPactDriver + { + /// + /// Initialize a new instance of the class. + /// + /// Pact handle + internal PluginPactDriver(PactHandle pact) : base(pact) + { + } + + /// + /// Create a new sync interaction on the current pact + /// + /// Interaction description + /// Interaction driver + public IPluginInteractionDriver NewSyncInteraction(string description) + { + InteractionHandle interaction = NativeInterop.NewSyncMessageInteraction(this.pact, description); + return new PluginInteractionDriver(interaction); + } + + public IHttpPluginInteractionDriver NewHttpPluginInteraction(string description) + { + InteractionHandle interaction = NativeInterop.NewInteraction(this.pact, description); + return new HttpPluginInteractionDriver(interaction); + } + + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public void Dispose() + { + this.ReleaseUnmanagedResources(); + GC.SuppressFinalize(this); + } + + /// + /// Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. + /// + ~PluginPactDriver() + { + this.ReleaseUnmanagedResources(); + } + + /// + /// Release unmanaged resources + /// + private void ReleaseUnmanagedResources() + { + NativeInterop.CleanupPlugins(pact); + } + } +} diff --git a/src/PactNet/HttpPluginPactBuilder.cs b/src/PactNet/HttpPluginPactBuilder.cs new file mode 100644 index 000000000..045761243 --- /dev/null +++ b/src/PactNet/HttpPluginPactBuilder.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using PactNet.Drivers.Plugins; +using PactNet.Interop; +using PactNet.Models; + +namespace PactNet +{ + internal class HttpPluginPactBuilder : AbstractPactBuilder, IHttpPluginPactBuilderV4 + { + private readonly IPluginPactDriver pact; + + internal HttpPluginPactBuilder(IPluginPactDriver pact, PactConfig config, int? port = null, + IPAddress host = IPAddress.Loopback) : base(pact, config, port, host, "http") + { + this.pact = pact; + } + + public IHttpPluginRequestBuilderV4 UponReceiving(string description) + => new HttpPluginRequestBuilder(this.pact.NewHttpPluginInteraction(description)); + + public void Dispose() => this.pact.Dispose(); + } + + internal class HttpPluginRequestBuilder : IHttpPluginRequestBuilderV4 + { + private readonly IHttpPluginInteractionDriver driver; + private readonly Dictionary headers = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary queries = new(); + private bool requestConfigured; + private bool contentsConfigured; + private bool responseStarted; + + internal HttpPluginRequestBuilder(IHttpPluginInteractionDriver driver) => this.driver = driver; + + private void EnsureMutable() + { + if (this.responseStarted) throw new InvalidOperationException("The request has already been completed."); + } + + public IHttpPluginRequestBuilderV4 Given(string description) + { + this.EnsureMutable(); + this.driver.Given(description); + return this; + } + + public IHttpPluginRequestBuilderV4 Given(string description, string name, string value) + { + this.EnsureMutable(); + this.driver.GivenWithParam(description, name, value); + return this; + } + + public IHttpPluginRequestBuilderV4 WithRequest(HttpMethod method, string path) + { + this.EnsureMutable(); + if (this.requestConfigured) throw new InvalidOperationException("Request has already been configured."); + if (method == null) throw new ArgumentNullException(nameof(method)); + if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("A request path is required.", nameof(path)); + this.driver.WithRequest(method.Method, path); + this.requestConfigured = true; + return this; + } + + public IHttpPluginRequestBuilderV4 WithQuery(string name, string value) + { + this.EnsureMutable(); + this.queries.TryGetValue(name, out uint index); + this.driver.WithQueryParameter(name, value, index); + this.queries[name] = index + 1; + return this; + } + + public IHttpPluginRequestBuilderV4 WithHeader(string name, string value) + { + this.EnsureMutable(); + this.headers.TryGetValue(name, out uint index); + this.driver.WithRequestHeader(name, value, index); + this.headers[name] = index + 1; + return this; + } + + public IHttpPluginRequestBuilderV4 WithContent(string contentType, Dictionary content) + { + this.EnsureMutable(); + if (this.contentsConfigured) throw new InvalidOperationException("Request contents have already been configured."); + this.driver.WithPluginContent(InteractionPart.Request, contentType, content); + this.contentsConfigured = true; + return this; + } + + public IHttpPluginResponseBuilderV4 WillRespondWithStatus(int status) + { + this.EnsureMutable(); + if (!this.requestConfigured) throw new InvalidOperationException("Configure the HTTP request first."); + if (status < 100 || status > 599) throw new ArgumentOutOfRangeException(nameof(status)); + this.driver.WithResponseStatus((ushort)status); + this.responseStarted = true; + return new HttpPluginResponseBuilder(this.driver); + } + } + + internal class HttpPluginResponseBuilder : IHttpPluginResponseBuilderV4 + { + private readonly IHttpPluginInteractionDriver driver; + private readonly Dictionary headers = new(StringComparer.OrdinalIgnoreCase); + private bool completed; + + internal HttpPluginResponseBuilder(IHttpPluginInteractionDriver driver) => this.driver = driver; + + private void EnsureMutable() + { + if (this.completed) throw new InvalidOperationException("Response contents have already been configured."); + } + + public IHttpPluginResponseBuilderV4 WithHeader(string name, string value) + { + this.EnsureMutable(); + this.headers.TryGetValue(name, out uint index); + this.driver.WithResponseHeader(name, value, index); + this.headers[name] = index + 1; + return this; + } + + public void WithContent(string contentType, Dictionary content) + { + this.EnsureMutable(); + this.driver.WithPluginContent(InteractionPart.Response, contentType, content); + this.completed = true; + } + } +} \ No newline at end of file diff --git a/src/PactNet/Interop/LogLevelExtensions.cs b/src/PactNet/Interop/LogLevelExtensions.cs new file mode 100644 index 000000000..57c18079b --- /dev/null +++ b/src/PactNet/Interop/LogLevelExtensions.cs @@ -0,0 +1,43 @@ +using System; + +namespace PactNet.Interop +{ + /// + /// PactLogLevel extension methods + /// + internal static class LogLevelExtensions + { + private static readonly object LogLocker = new object(); + private static bool LogInitialised = false; + + /// + /// Direct all logging in the native library to a task local memory buffer. + /// + /// Log level + /// Invalid log level + /// Logging can only be initialised **once**. Subsequent calls will have no effect + public static void LogToBuffer(this PactLogLevel level) + { + lock (LogLocker) + { + if (LogInitialised) + { + return; + } + + NativeInterop.LogToBuffer(level switch + { + PactLogLevel.Trace => LevelFilter.Trace, + PactLogLevel.Debug => LevelFilter.Debug, + PactLogLevel.Information => LevelFilter.Info, + PactLogLevel.Warn => LevelFilter.Warn, + PactLogLevel.Error => LevelFilter.Error, + PactLogLevel.None => LevelFilter.Off, + _ => throw new ArgumentOutOfRangeException(nameof(level), level, "Invalid log level") + }); + + LogInitialised = true; + } + } + } +} diff --git a/src/PactNet/Interop/NativeInterop.cs b/src/PactNet/Interop/NativeInterop.cs index 92bdc9116..803b530a6 100644 --- a/src/PactNet/Interop/NativeInterop.cs +++ b/src/PactNet/Interop/NativeInterop.cs @@ -21,15 +21,15 @@ internal static class NativeInterop [DllImport(DllName, EntryPoint = "pactffi_mock_server_mismatches")] public static extern IntPtr MockServerMismatches(int mockServerPort); - [DllImport(DllName, EntryPoint = "pactffi_mock_server_logs")] - public static extern IntPtr MockServerLogs(int mockServerPort); - [DllImport(DllName, EntryPoint = "pactffi_cleanup_mock_server")] public static extern bool CleanupMockServer(int mockServerPort); [DllImport(DllName, EntryPoint = "pactffi_pact_handle_write_file")] public static extern int WritePactFile(PactHandle pact, string directory, bool overwrite); + [DllImport(DllName, EntryPoint = "pactffi_write_pact_file")] + public static extern int WritePactFileForPort(int port, string directory, bool overwrite); + [DllImport(DllName, EntryPoint = "pactffi_fetch_log_buffer")] public static extern string FetchLogBuffer(string logId); @@ -42,6 +42,9 @@ internal static class NativeInterop [DllImport(DllName, EntryPoint = "pactffi_new_interaction")] public static extern InteractionHandle NewInteraction(PactHandle pact, string description); + [DllImport(DllName, EntryPoint = "pactffi_new_sync_message_interaction")] + public static extern InteractionHandle NewSyncMessageInteraction(PactHandle pact, string description); + [DllImport(DllName, EntryPoint = "pactffi_given")] public static extern bool Given(InteractionHandle interaction, string description); @@ -168,5 +171,18 @@ public static extern void VerifierBrokerSourceWithSelectors(IntPtr handle, public static extern IntPtr VerifierOutput(IntPtr handle, byte stripAnsi); #endregion + + #region Plugins + + [DllImport(DllName, EntryPoint = "pactffi_using_plugin")] + public static extern uint UsingPlugin(PactHandle pact, string name, string version); + + [DllImport(DllName, EntryPoint = "pactffi_interaction_contents")] + public static extern uint InteractionContents(InteractionHandle interaction, InteractionPart part, string contentType, string body); + + [DllImport(DllName, EntryPoint = "pactffi_cleanup_plugins")] + public static extern void CleanupPlugins(PactHandle pact); + + #endregion } } diff --git a/src/PactNet/MessageBuilder.cs b/src/PactNet/MessageBuilder.cs index 83c7cffe4..571a98472 100644 --- a/src/PactNet/MessageBuilder.cs +++ b/src/PactNet/MessageBuilder.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Text.Json; -using PactNet.Drivers; +using PactNet.Drivers.Message; using PactNet.Interop; namespace PactNet diff --git a/src/PactNet/MessagePactBuilder.cs b/src/PactNet/MessagePactBuilder.cs index 0cd17567d..c70e23497 100644 --- a/src/PactNet/MessagePactBuilder.cs +++ b/src/PactNet/MessagePactBuilder.cs @@ -1,5 +1,5 @@ using System; -using PactNet.Drivers; +using PactNet.Drivers.Message; using PactNet.Interop; namespace PactNet diff --git a/src/PactNet/PactBuilder.cs b/src/PactNet/PactBuilder.cs index fe311c885..e0eb138a7 100644 --- a/src/PactNet/PactBuilder.cs +++ b/src/PactNet/PactBuilder.cs @@ -1,8 +1,4 @@ -using System; -using System.Threading.Tasks; -using PactNet.Drivers; -using PactNet.Exceptions; -using PactNet.Internal; +using PactNet.Drivers.Http; using PactNet.Models; namespace PactNet @@ -10,12 +6,10 @@ namespace PactNet /// /// Pact builder for the native backend /// - internal class PactBuilder : IPactBuilderV2, IPactBuilderV3, IPactBuilderV4 + internal class PactBuilder : AbstractPactBuilder, IPactBuilderV2, IPactBuilderV3, IPactBuilderV4 { private readonly IHttpPactDriver pact; private readonly PactConfig config; - private readonly int? port; - private readonly IPAddress host; /// /// Initialises a new instance of the class. @@ -24,12 +18,14 @@ internal class PactBuilder : IPactBuilderV2, IPactBuilderV3, IPactBuilderV4 /// Pact config /// Optional port, otherwise one is dynamically allocated /// Optional host, otherwise loopback is used - internal PactBuilder(IHttpPactDriver pact, PactConfig config, int? port = null, IPAddress host = IPAddress.Loopback) + internal PactBuilder(IHttpPactDriver pact, + PactConfig config, + int? port = null, + IPAddress host = IPAddress.Loopback) + : base(pact, config, port, host, "http") { this.pact = pact; this.config = config; - this.port = port; - this.host = host; } /// @@ -68,109 +64,5 @@ internal RequestBuilder UponReceiving(string description) var requestBuilder = new RequestBuilder(interactions, this.config.DefaultJsonSettings); return requestBuilder; } - - /// - /// Verify the configured interactions - /// - /// Action to perform the real interactions against the mock driver - /// Failed to verify the interactions - public void Verify(Action interact) - { - Guard.NotNull(interact, nameof(interact)); - - using IMockServerDriver mockServer = this.StartMockServer(); - - try - { - interact(new ConsumerContext - { - MockServerUri = mockServer.Uri - }); - - this.VerifyInternal(mockServer); - } - finally - { - this.PrintLogs(mockServer); - } - } - - /// - /// Verify the configured interactions - /// - /// Action to perform the real interactions against the mock driver - /// Failed to verify the interactions - public async Task VerifyAsync(Func interact) - { - Guard.NotNull(interact, nameof(interact)); - - using IMockServerDriver mockServer = this.StartMockServer(); - - try - { - await interact(new ConsumerContext - { - MockServerUri = mockServer.Uri - }); - - this.VerifyInternal(mockServer); - } - finally - { - this.PrintLogs(mockServer); - } - } - - /// - /// Start the mock driver - /// - /// Mock driver - private IMockServerDriver StartMockServer() - { - string hostIp = this.host switch - { - IPAddress.Loopback => "127.0.0.1", - IPAddress.Any => "0.0.0.0", - _ => throw new ArgumentOutOfRangeException(nameof(this.host), this.host, "Unsupported IPAddress value") - }; - - // TODO: add TLS support - return this.pact.CreateMockServer(hostIp, this.port, false); - } - - /// - /// Verify the interactions after the consumer client has been invoked - /// - /// Mock server - private void VerifyInternal(IMockServerDriver mockServer) - { - string errors = mockServer.MockServerMismatches(); - - if (string.IsNullOrWhiteSpace(errors) || errors == "[]") - { - this.pact.WritePactFile(this.config.PactDir); - return; - } - - this.config.WriteLine(string.Empty); - this.config.WriteLine("Verification mismatches:"); - this.config.WriteLine(string.Empty); - this.config.WriteLine(errors); - - throw new PactFailureException("Pact verification failed. See output for details"); - } - - /// - /// Print logs to the configured outputs - /// - /// Mock server - private void PrintLogs(IMockServerDriver mockServer) - { - string logs = mockServer.MockServerLogs(); - - this.config.WriteLine("Mock driver logs:"); - this.config.WriteLine(string.Empty); - this.config.WriteLine(logs); - } } } diff --git a/src/PactNet/PactExtensions.cs b/src/PactNet/PactExtensions.cs index 32aa358fb..53211fabe 100644 --- a/src/PactNet/PactExtensions.cs +++ b/src/PactNet/PactExtensions.cs @@ -1,5 +1,7 @@ -using System; using PactNet.Drivers; +using PactNet.Drivers.Http; +using PactNet.Drivers.Message; +using PactNet.Drivers.Plugins; using PactNet.Interop; using PactNet.Models; @@ -10,9 +12,6 @@ namespace PactNet /// public static class PactExtensions { - private static readonly object LogLocker = new object(); - private static bool LogInitialised = false; - /// /// Establish a new pact using the native backend /// @@ -27,7 +26,7 @@ public static class PactExtensions /// public static IPactBuilderV2 WithHttpInteractions(this IPactV2 pact, int? port = null, IPAddress host = IPAddress.Loopback) { - InitialiseLogging(pact.Config.LogLevel); + pact.Config.LogLevel.LogToBuffer(); IPactDriver driver = new PactDriver(); IHttpPactDriver httpPact = driver.NewHttpPact(pact.Consumer, pact.Provider, PactSpecification.V2); @@ -50,7 +49,7 @@ public static IPactBuilderV2 WithHttpInteractions(this IPactV2 pact, int? port = /// public static IPactBuilderV3 WithHttpInteractions(this IPactV3 pact, int? port = null, IPAddress host = IPAddress.Loopback) { - InitialiseLogging(pact.Config.LogLevel); + pact.Config.LogLevel.LogToBuffer(); IPactDriver driver = new PactDriver(); IHttpPactDriver httpPact = driver.NewHttpPact(pact.Consumer, pact.Provider, PactSpecification.V3); @@ -73,7 +72,7 @@ public static IPactBuilderV3 WithHttpInteractions(this IPactV3 pact, int? port = /// public static IPactBuilderV4 WithHttpInteractions(this IPactV4 pact, int? port = null, IPAddress host = IPAddress.Loopback) { - InitialiseLogging(pact.Config.LogLevel); + pact.Config.LogLevel.LogToBuffer(); IPactDriver driver = new PactDriver(); IHttpPactDriver httpPact = driver.NewHttpPact(pact.Consumer, pact.Provider, PactSpecification.V4); @@ -89,7 +88,7 @@ public static IPactBuilderV4 WithHttpInteractions(this IPactV4 pact, int? port = /// Pact builder public static IMessagePactBuilderV3 WithMessageInteractions(this IPactV3 pact) { - InitialiseLogging(pact.Config.LogLevel); + pact.Config.LogLevel.LogToBuffer(); IPactDriver driver = new PactDriver(); IMessagePactDriver messagePact = driver.NewMessagePact(pact.Consumer, pact.Provider, PactSpecification.V3); @@ -105,7 +104,7 @@ public static IMessagePactBuilderV3 WithMessageInteractions(this IPactV3 pact) /// Pact builder public static IMessagePactBuilderV4 WithMessageInteractions(this IPactV4 pact) { - InitialiseLogging(pact.Config.LogLevel); + pact.Config.LogLevel.LogToBuffer(); IPactDriver driver = new PactDriver(); IMessagePactDriver messagePact = driver.NewMessagePact(pact.Consumer, pact.Provider, PactSpecification.V4); @@ -115,33 +114,46 @@ public static IMessagePactBuilderV4 WithMessageInteractions(this IPactV4 pact) } /// - /// Initialise logging in the native library + /// Establish a new pact with synchronous plugin interactions. /// - /// Log level - /// Invalid log level - /// Logging can only be initialised **once**. Subsequent calls will have no effect - private static void InitialiseLogging(PactLogLevel level) + /// + /// Plugin name + /// Plugin version + /// The transport to use (i.e. http, https, grpc). Must be a valid UTF-8 NULL-terminated string, or NULL or empty, in which case http will be used. + /// Port for the mock server. If null, one will be assigned automatically + /// Host for the mock server + /// Synchronous plugin builder + public static ISynchronousPluginPactBuilderV4 WithSynchronousPluginInteractions(this IPactV4 pact, + string pluginName, + string pluginVersion, + string transport = null, + int? port = null, + IPAddress host = IPAddress.Loopback) + { + pact.Config.LogLevel.LogToBuffer(); + + IPactDriver driver = new PactDriver(); + IPluginPactDriver pluginDriver = driver.NewPluginPact(pact.Consumer, pact.Provider, pluginName, pluginVersion, PactSpecification.V4); + + return new SynchronousPluginPactBuilder(pluginDriver, pact.Config, port, host, transport); + } + + /// Create HTTP interactions with plugin-defined request or response contents. + /// Pact details. + /// Content plugin name. + /// Optional plugin version. + /// Optional mock server port. + /// Mock server host. + /// HTTP plugin builder. + public static IHttpPluginPactBuilderV4 WithHttpPluginInteractions(this IPactV4 pact, + string pluginName, string pluginVersion = null, int? port = null, + IPAddress host = IPAddress.Loopback) { - lock (LogLocker) - { - if (LogInitialised) - { - return; - } - - NativeInterop.LogToBuffer(level switch - { - PactLogLevel.Trace => LevelFilter.Trace, - PactLogLevel.Debug => LevelFilter.Debug, - PactLogLevel.Information => LevelFilter.Info, - PactLogLevel.Warn => LevelFilter.Warn, - PactLogLevel.Error => LevelFilter.Error, - PactLogLevel.None => LevelFilter.Off, - _ => throw new ArgumentOutOfRangeException(nameof(level), level, "Invalid log level") - }); - - LogInitialised = true; - } + pact.Config.LogLevel.LogToBuffer(); + IPactDriver driver = new PactDriver(); + IPluginPactDriver pluginDriver = driver.NewPluginPact(pact.Consumer, pact.Provider, + pluginName, pluginVersion, PactSpecification.V4); + return new HttpPluginPactBuilder(pluginDriver, pact.Config, port, host); } } } diff --git a/src/PactNet/RequestBuilder.cs b/src/PactNet/RequestBuilder.cs index d245cfbfc..20204fbc1 100644 --- a/src/PactNet/RequestBuilder.cs +++ b/src/PactNet/RequestBuilder.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Net.Http; using System.Text.Json; -using PactNet.Drivers; +using PactNet.Drivers.Http; using PactNet.Matchers; namespace PactNet diff --git a/src/PactNet/ResponseBuilder.cs b/src/PactNet/ResponseBuilder.cs index badb0e96d..21abfd229 100644 --- a/src/PactNet/ResponseBuilder.cs +++ b/src/PactNet/ResponseBuilder.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Net; using System.Text.Json; -using PactNet.Drivers; +using PactNet.Drivers.Http; using PactNet.Matchers; namespace PactNet diff --git a/src/PactNet/SynchronousPluginPactBuilder.cs b/src/PactNet/SynchronousPluginPactBuilder.cs new file mode 100644 index 000000000..438020650 --- /dev/null +++ b/src/PactNet/SynchronousPluginPactBuilder.cs @@ -0,0 +1,43 @@ +using PactNet.Drivers.Plugins; +using PactNet.Models; + +namespace PactNet +{ + /// + /// Synchronous plugin pact builder + /// + internal class SynchronousPluginPactBuilder : AbstractPactBuilder, ISynchronousPluginPactBuilderV4 + { + private readonly IPluginPactDriver pact; + + /// + /// Intialises a new instance of the class. + /// + /// Pact handle + /// Pact configuration + /// Mock server port + /// Mock server host + /// Plugin transport + public SynchronousPluginPactBuilder(IPluginPactDriver pact, + PactConfig config, + int? port, + IPAddress host, + string transport = null) + : base(pact, config, port, host, transport) + { + this.pact = pact; + } + + /// + /// Add a new interaction to the pact + /// + /// Interaction description + /// Fluent builder + public ISynchronousPluginRequestBuilderV4 UponReceiving(string description) + { + return new SynchronousPluginRequestBuilder(this.pact.NewSyncInteraction(description)); + } + + public void Dispose() => this.pact?.Dispose(); + } +} diff --git a/src/PactNet/SynchronousPluginRequestBuilder.cs b/src/PactNet/SynchronousPluginRequestBuilder.cs new file mode 100644 index 000000000..7bf567f7f --- /dev/null +++ b/src/PactNet/SynchronousPluginRequestBuilder.cs @@ -0,0 +1,55 @@ +using System.Collections.Generic; +using PactNet.Drivers.Plugins; + +namespace PactNet +{ + /// + /// Synchronous plugin request builder + /// + internal class SynchronousPluginRequestBuilder : ISynchronousPluginRequestBuilderV4 + { + private readonly IPluginInteractionDriver interactionDriver; + + /// + /// Initialises a new instance of the class. + /// + /// Interaction driver + public SynchronousPluginRequestBuilder(IPluginInteractionDriver interactionDriver) + { + this.interactionDriver = interactionDriver; + } + + /// + /// Add a provider state + /// + /// Provider state description + /// Fluent builder + public ISynchronousPluginRequestBuilderV4 Given(string description) + { + this.interactionDriver.Given(description); + return this; + } + + /// + /// Add a provider state with a parameter to the interaction + /// + /// Provider state description + /// Parameter name + /// Parameter value + public ISynchronousPluginRequestBuilderV4 Given(string description, string name, string value) + { + this.interactionDriver.GivenWithParam(description, name, value); + return this; + } + + /// + /// Set the plugin interaction contents. This completes the interaction and must be the last call. + /// + /// Content type understood by the plugin + /// A dictionary containing the plugin content. + public void WithContent(string contentType, Dictionary content) + { + this.interactionDriver.WithContent(contentType, content); + } + } +} diff --git a/src/PactNet/Verifier/InteropVerifierProvider.cs b/src/PactNet/Verifier/InteropVerifierProvider.cs index c0245296f..8de20a676 100644 --- a/src/PactNet/Verifier/InteropVerifierProvider.cs +++ b/src/PactNet/Verifier/InteropVerifierProvider.cs @@ -31,17 +31,7 @@ public InteropVerifierProvider(PactVerifierConfig config) /// public void Initialise() { - NativeInterop.LogToBuffer(config.LogLevel switch - { - PactLogLevel.Trace => LevelFilter.Trace, - PactLogLevel.Debug => LevelFilter.Debug, - PactLogLevel.Information => LevelFilter.Info, - PactLogLevel.Warn => LevelFilter.Warn, - PactLogLevel.Error => LevelFilter.Error, - PactLogLevel.None => LevelFilter.Off, - _ => throw new ArgumentOutOfRangeException(nameof(config.LogLevel), config.LogLevel, "Invalid log level") - }); - + this.config.LogLevel.LogToBuffer(); this.handle = NativeInterop.VerifierNewForApplication("pact-net", typeof(InteropVerifierProvider).Assembly.GetName().Version.ToString()); } diff --git a/tests/PactNet.Tests/ConfiguredMessageVerifierTests.cs b/tests/PactNet.Tests/ConfiguredMessageVerifierTests.cs index 6b9bb0a7b..577b2a27e 100644 --- a/tests/PactNet.Tests/ConfiguredMessageVerifierTests.cs +++ b/tests/PactNet.Tests/ConfiguredMessageVerifierTests.cs @@ -4,7 +4,7 @@ using System.Threading.Tasks; using FluentAssertions; using Moq; -using PactNet.Drivers; +using PactNet.Drivers.Message; using PactNet.Exceptions; using PactNet.Interop; using PactNet.Models; diff --git a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs index 81ab072e2..dc876bed3 100644 --- a/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs +++ b/tests/PactNet.Tests/Drivers/FfiIntegrationTests.cs @@ -6,6 +6,8 @@ using System.Threading.Tasks; using FluentAssertions; using PactNet.Drivers; +using PactNet.Drivers.Http; +using PactNet.Drivers.Message; using PactNet.Interop; using Xunit; using Xunit.Abstractions; @@ -22,8 +24,7 @@ public class FfiIntegrationTests public FfiIntegrationTests(ITestOutputHelper output) { this.output = output; - - NativeInterop.LogToBuffer(LevelFilter.Trace); + PactLogLevel.Trace.LogToBuffer(); } [Fact] @@ -36,14 +37,12 @@ public async Task HttpInteraction_v3_CreatesPactFile() IHttpPactDriver pact = driver.NewHttpPact("NativeDriverTests-Consumer-V3", "NativeDriverTests-Provider", PactSpecification.V3); - IHttpInteractionDriver interaction = pact.NewHttpInteraction("a sample interaction"); interaction.Given("provider state"); interaction.GivenWithParam("state with param", "foo", "bar"); interaction.WithRequest("POST", "/path"); - interaction.WithRequestHeader("X-Request-Header", "request1", 0); - interaction.WithRequestHeader("X-Request-Header", "request2", 1); + interaction.WithRequestHeader("X-Request-Header", "request1, request2", 0); interaction.WithQueryParameter("param", "value", 0); interaction.WithRequestBody("application/json", @"{""foo"":42}"); @@ -52,7 +51,7 @@ public async Task HttpInteraction_v3_CreatesPactFile() interaction.WithResponseHeader("X-Response-Header", "value2", 1); interaction.WithResponseBody("application/json", @"{""foo"":42}"); - using IMockServerDriver mockServer = pact.CreateMockServer("127.0.0.1", null, false); + using IMockServerDriver mockServer = pact.CreateMockServer("127.0.0.1", null, false, "http"); var client = new HttpClient { BaseAddress = mockServer.Uri }; client.DefaultRequestHeaders.Add("X-Request-Header", new[] { "request1", "request2" }); @@ -67,7 +66,6 @@ public async Task HttpInteraction_v3_CreatesPactFile() mockServer.MockServerMismatches().Should().Be("[]"); string logs = mockServer.MockServerLogs(); - logs.Should().NotBeEmpty(); this.output.WriteLine("Mock Server Logs"); this.output.WriteLine("----------------"); diff --git a/tests/PactNet.Tests/HttpPluginPactBuilderTests.cs b/tests/PactNet.Tests/HttpPluginPactBuilderTests.cs new file mode 100644 index 000000000..a93f1f539 --- /dev/null +++ b/tests/PactNet.Tests/HttpPluginPactBuilderTests.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using Moq; +using PactNet.Drivers.Plugins; +using PactNet.Interop; +using Xunit; + +namespace PactNet.Tests; + +public class HttpPluginPactBuilderTests +{ + private readonly Mock driver = new(); + + [Fact] + public void Contents_AreSentToTheCorrectHttpPart() + { + var request = new HttpPluginRequestBuilder(this.driver.Object); + var contents = new Dictionary(); + request.WithRequest(HttpMethod.Post, "/avro") + .WithContent("avro/binary", contents) + .WillRespondWithStatus(201).WithContent("avro/binary", contents); + this.driver.Verify(value => value.WithRequest("POST", "/avro"), Times.Once); + this.driver.Verify(value => value.WithResponseStatus(201), Times.Once); + this.driver.Verify(value => value.WithPluginContent(InteractionPart.Request, "avro/binary", contents), Times.Once); + this.driver.Verify(value => value.WithPluginContent(InteractionPart.Response, "avro/binary", contents), Times.Once); + } + + [Fact] + public void Response_RejectsRepeatedContentsAndHeadersAfterCompletion() + { + var response = new HttpPluginResponseBuilder(this.driver.Object); + var contents = new Dictionary(); + response.WithContent("avro/binary", contents); + Assert.Throws(() => response.WithContent("avro/binary", contents)); + Assert.Throws(() => response.WithHeader("Content-Type", "avro/binary")); + } + + [Fact] + public void Request_RejectsReuseAndInvalidOrdering() + { + var request = new HttpPluginRequestBuilder(this.driver.Object); + Assert.Throws(() => request.WillRespondWithStatus(200)); + request.WithRequest(HttpMethod.Get, "/avro"); + Assert.Throws(() => request.WithRequest(HttpMethod.Post, "/avro")); + Assert.Throws(() => request.WillRespondWithStatus(600)); + request.WithContent("avro/binary", new Dictionary()); + Assert.Throws(() => request.WithContent("avro/binary", new Dictionary())); + request.WillRespondWithStatus(200); + Assert.Throws(() => request.WillRespondWithStatus(200)); + Assert.Throws(() => request.Given("late state")); + } + + [Fact] + public void RepeatedHeadersAndQueries_UseIndependentIndexes() + { + var request = new HttpPluginRequestBuilder(this.driver.Object); + request.WithHeader("Accept", "one").WithHeader("accept", "two") + .WithQuery("id", "one").WithQuery("id", "two"); + var response = new HttpPluginResponseBuilder(this.driver.Object); + response.WithHeader("X-Test", "one").WithHeader("x-test", "two"); + this.driver.Verify(value => value.WithRequestHeader("accept", "two", 1), Times.Once); + this.driver.Verify(value => value.WithQueryParameter("id", "two", 1), Times.Once); + this.driver.Verify(value => value.WithResponseHeader("x-test", "two", 1), Times.Once); + } + + [Fact] + public void Pact_UsesHttpInteractionFactoryAndDelegatesDisposal() + { + var pact = new Mock(); + pact.Setup(value => value.NewHttpPluginInteraction("an avro request")).Returns(this.driver.Object); + using (var builder = new HttpPluginPactBuilder(pact.Object, new PactConfig())) + { + builder.UponReceiving("an avro request"); + } + pact.Verify(value => value.NewHttpPluginInteraction("an avro request"), Times.Once); + pact.Verify(value => value.Dispose(), Times.Once); + } +} \ No newline at end of file diff --git a/tests/PactNet.Tests/MessageBuilderTests.cs b/tests/PactNet.Tests/MessageBuilderTests.cs index 4fa72c5c5..34a7e922f 100644 --- a/tests/PactNet.Tests/MessageBuilderTests.cs +++ b/tests/PactNet.Tests/MessageBuilderTests.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Text.Json; using Moq; -using PactNet.Drivers; +using PactNet.Drivers.Message; using PactNet.Interop; using Xunit; using Match = PactNet.Matchers.Match; diff --git a/tests/PactNet.Tests/MessagePactBuilderTests.cs b/tests/PactNet.Tests/MessagePactBuilderTests.cs index cff2f18cc..daee234da 100644 --- a/tests/PactNet.Tests/MessagePactBuilderTests.cs +++ b/tests/PactNet.Tests/MessagePactBuilderTests.cs @@ -1,7 +1,7 @@ using System; using FluentAssertions; using Moq; -using PactNet.Drivers; +using PactNet.Drivers.Message; using PactNet.Interop; using Xunit; diff --git a/tests/PactNet.Tests/PactBuilderTests.cs b/tests/PactNet.Tests/PactBuilderTests.cs index fd6453043..a152bf72a 100644 --- a/tests/PactNet.Tests/PactBuilderTests.cs +++ b/tests/PactNet.Tests/PactBuilderTests.cs @@ -3,6 +3,7 @@ using FluentAssertions; using Moq; using PactNet.Drivers; +using PactNet.Drivers.Http; using PactNet.Exceptions; using PactNet.Infrastructure.Outputters; using Xunit; @@ -11,6 +12,7 @@ namespace PactNet.Tests { public class PactBuilderTests { + private const int MockServerPort = 5000; private readonly PactBuilder builder; private readonly Mock mockDriver; @@ -27,12 +29,13 @@ public PactBuilderTests() this.mockDriver = new Mock(MockBehavior.Strict); this.mockInteractions = new Mock(MockBehavior.Strict); this.mockServer = new Mock(MockBehavior.Strict); + this.mockServer.Setup(s => s.Port).Returns(MockServerPort); this.mockOutput = new Mock(); this.fixture = new Fixture(); var customization = new SupportMutableValueTypesCustomization(); customization.Customize(this.fixture); - + this.serverUri = this.fixture.Create(); this.config = new PactConfig { @@ -40,9 +43,9 @@ public PactBuilderTests() }; // set some default mock setups - this.mockDriver.Setup(s => s.CreateMockServer("127.0.0.1", null, false)).Returns(this.mockServer.Object); + this.mockDriver.Setup(s => s.CreateMockServer("127.0.0.1", null, false, "http")).Returns(this.mockServer.Object); this.mockDriver.Setup(s => s.NewHttpInteraction(It.IsAny())).Returns(this.mockInteractions.Object); - this.mockDriver.Setup(s => s.WritePactFile(this.config.PactDir)); + this.mockDriver.Setup(s => s.WritePactFile(MockServerPort, this.config.PactDir)); this.mockServer.Setup(s => s.Uri).Returns(this.serverUri); this.mockServer.Setup(s => s.MockServerLogs()).Returns(string.Empty); @@ -67,14 +70,14 @@ public void Verify_WhenCalled_StartsMockServer() { this.builder.Verify(Success); - this.mockDriver.Verify(d => d.CreateMockServer("127.0.0.1", null, false)); + this.mockDriver.Verify(d => d.CreateMockServer("127.0.0.1", null, false, "http")); } [Fact] public void Verify_ErrorStartingMockServer_ThrowsInvalidOperationException() { this.mockDriver - .Setup(s => s.CreateMockServer(It.IsAny(), It.IsAny(), It.IsAny())) + .Setup(s => s.CreateMockServer(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Throws(); Action action = () => this.builder.Verify(Success); @@ -106,7 +109,7 @@ public void Verify_NoMismatches_WritesPactFile() { this.builder.Verify(Success); - this.mockDriver.Verify(s => s.WritePactFile(this.config.PactDir)); + this.mockDriver.Verify(s => s.WritePactFile(MockServerPort, this.config.PactDir)); } [Fact] @@ -121,7 +124,7 @@ public void Verify_NoMismatches_ShutsDownMockServer() public void Verify_FailedToWritePactFile_ThrowsInvalidOperationException() { this.mockDriver - .Setup(s => s.WritePactFile(It.IsAny())) + .Setup(s => s.WritePactFile(It.IsAny(), It.IsAny())) .Throws(); Action action = () => this.builder.Verify(Success); diff --git a/tests/PactNet.Tests/RequestBuilderTests.cs b/tests/PactNet.Tests/RequestBuilderTests.cs index d4be96244..a55a204bb 100644 --- a/tests/PactNet.Tests/RequestBuilderTests.cs +++ b/tests/PactNet.Tests/RequestBuilderTests.cs @@ -4,7 +4,7 @@ using System.Text.Json; using FluentAssertions; using Moq; -using PactNet.Drivers; +using PactNet.Drivers.Http; using Xunit; using Match = PactNet.Matchers.Match; diff --git a/tests/PactNet.Tests/ResponseBuilderTests.cs b/tests/PactNet.Tests/ResponseBuilderTests.cs index d92cee718..cd71e771b 100644 --- a/tests/PactNet.Tests/ResponseBuilderTests.cs +++ b/tests/PactNet.Tests/ResponseBuilderTests.cs @@ -1,7 +1,7 @@ using System.Net; using System.Text.Json; using Moq; -using PactNet.Drivers; +using PactNet.Drivers.Http; using Xunit; using Match = PactNet.Matchers.Match; diff --git a/tests/PactNet.Tests/SynchronousPluginPactBuilderTests.cs b/tests/PactNet.Tests/SynchronousPluginPactBuilderTests.cs new file mode 100644 index 000000000..0c6438681 --- /dev/null +++ b/tests/PactNet.Tests/SynchronousPluginPactBuilderTests.cs @@ -0,0 +1,102 @@ +using System; +using FluentAssertions; +using Moq; +using PactNet.Drivers; +using PactNet.Drivers.Plugins; +using PactNet.Infrastructure.Outputters; +using PactNet.Models; +using Xunit; + +namespace PactNet.Tests +{ + public class SynchronousPluginPactBuilderTests + { + private const int MockServerPort = 5000; + private readonly SynchronousPluginPactBuilder builder; + + private readonly Mock mockDriver; + private readonly Mock mockInteractions; + private readonly Mock mockServer; + private readonly Mock mockOutput; + + private readonly PactConfig config; + + public SynchronousPluginPactBuilderTests() + { + this.mockDriver = new Mock(MockBehavior.Strict); + this.mockInteractions = new Mock(MockBehavior.Strict); + this.mockServer = new Mock(MockBehavior.Strict); + this.mockServer.Setup(s => s.Port).Returns(MockServerPort); + this.mockOutput = new Mock(); + + this.config = new PactConfig + { + Outputters = new[] { this.mockOutput.Object } + }; + + this.mockDriver.Setup(s => s.CreateMockServer("127.0.0.1", null, false, "grpc")).Returns(this.mockServer.Object); + this.mockDriver.Setup(s => s.NewSyncInteraction(It.IsAny())).Returns(this.mockInteractions.Object); + this.mockDriver.Setup(s => s.WritePactFile(MockServerPort, this.config.PactDir)); + this.mockDriver.Setup(s => s.Dispose()); + + this.mockServer.Setup(s => s.Uri).Returns(new Uri("http://127.0.0.1:5000")); + this.mockServer.Setup(s => s.MockServerLogs()).Returns(string.Empty); + this.mockServer.Setup(s => s.MockServerMismatches()).Returns(string.Empty); + this.mockServer.Setup(s => s.Dispose()); + + this.builder = new SynchronousPluginPactBuilder(this.mockDriver.Object, this.config, null, IPAddress.Loopback, "grpc"); + } + + [Fact] + public void UponReceiving_WhenCalled_CreatesNewSyncInteraction() + { + this.builder.UponReceiving("a plugin interaction"); + + this.mockDriver.Verify(d => d.NewSyncInteraction("a plugin interaction")); + } + + [Fact] + public void UponReceiving_CalledTwice_CreatesTwoInteractions() + { + this.builder.UponReceiving("first interaction"); + this.builder.UponReceiving("second interaction"); + + this.mockDriver.Verify(d => d.NewSyncInteraction("first interaction"), Times.Once); + this.mockDriver.Verify(d => d.NewSyncInteraction("second interaction"), Times.Once); + } + + [Fact] + public void Verify_WhenCalled_StartsMockServerWithPluginTransport() + { + this.builder.Verify(_ => { }); + + this.mockDriver.Verify(d => d.CreateMockServer("127.0.0.1", null, false, "grpc")); + } + + [Fact] + public void Verify_NoMismatches_WritesPactFile() + { + this.builder.Verify(_ => { }); + + this.mockDriver.Verify(d => d.WritePactFile(MockServerPort, this.config.PactDir)); + } + + [Fact] + public void Verify_WhenCalled_PassesMockServerUriToConsumer() + { + Uri actual = null; + + this.builder.Verify(ctx => actual = ctx.MockServerUri); + + actual.Should().Be(new Uri("http://127.0.0.1:5000")); + } + + [Fact] + public void Dispose_WhenCalled_DisposesPact() + { + this.builder.Dispose(); + + this.mockDriver.Verify(d => d.Dispose()); + } + } +} diff --git a/tests/PactNet.Tests/SynchronousPluginRequestBuilderTests.cs b/tests/PactNet.Tests/SynchronousPluginRequestBuilderTests.cs new file mode 100644 index 000000000..0915c6796 --- /dev/null +++ b/tests/PactNet.Tests/SynchronousPluginRequestBuilderTests.cs @@ -0,0 +1,71 @@ +using System.Collections.Generic; +using FluentAssertions; +using Moq; +using PactNet.Drivers.Plugins; +using Xunit; + +namespace PactNet.Tests +{ + public class SynchronousPluginRequestBuilderTests + { + private readonly ISynchronousPluginRequestBuilderV4 builder; + + private readonly Mock mockDriver; + + public SynchronousPluginRequestBuilderTests() + { + this.mockDriver = new Mock(); + + this.builder = new SynchronousPluginRequestBuilder(this.mockDriver.Object); + } + + [Fact] + public void Given_WhenCalled_AddsProviderState() + { + this.builder.Given("provider state"); + + this.mockDriver.Verify(d => d.Given("provider state")); + } + + [Fact] + public void Given_WhenCalled_ReturnsSameBuilder() + { + ISynchronousPluginRequestBuilderV4 result = this.builder.Given("provider state"); + + result.Should().BeSameAs(this.builder); + } + + [Fact] + public void Given_WithParam_AddsProviderState() + { + this.builder.Given("provider state", "foo", "bar"); + + this.mockDriver.Verify(d => d.GivenWithParam("provider state", "foo", "bar")); + } + + [Fact] + public void Given_WithParam_ReturnsSameBuilder() + { + ISynchronousPluginRequestBuilderV4 result = this.builder.Given("provider state", "foo", "bar"); + + result.Should().BeSameAs(this.builder); + } + + [Fact] + public void WithContent_WhenCalled_SetsInteractionContents() + { + var content = new Dictionary + { + ["pact:proto"] = "greet.proto", + ["pact:proto-service"] = "Greeter/SayHello", + ["pact:content-type"] = "application/protobuf", + ["request"] = new { name = "matching(type, 'foo')" }, + ["response"] = new { message = "matching(type, 'Hello foo')" } + }; + + this.builder.WithContent("application/grpc", content); + + this.mockDriver.Verify(d => d.WithContent("application/grpc", content), Times.Once); + } + } +} diff --git a/tests/PactNet.Tests/data/v2-consumer-integration.json b/tests/PactNet.Tests/data/v2-consumer-integration.json index 9484eef44..096da8f42 100644 --- a/tests/PactNet.Tests/data/v2-consumer-integration.json +++ b/tests/PactNet.Tests/data/v2-consumer-integration.json @@ -74,8 +74,9 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.13", + "mockserver": "2.2.7", + "models": "1.3.18" }, "pactSpecification": { "version": "2.0.0" diff --git a/tests/PactNet.Tests/data/v3-consumer-integration.json b/tests/PactNet.Tests/data/v3-consumer-integration.json index b220eb497..461cd3c59 100644 --- a/tests/PactNet.Tests/data/v3-consumer-integration.json +++ b/tests/PactNet.Tests/data/v3-consumer-integration.json @@ -130,8 +130,9 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.13", + "mockserver": "2.2.7", + "models": "1.3.18" }, "pactSpecification": { "version": "3.0.0" diff --git a/tests/PactNet.Tests/data/v3-message-consumer-integration.json b/tests/PactNet.Tests/data/v3-message-consumer-integration.json index 494ea2258..5e44b239f 100644 --- a/tests/PactNet.Tests/data/v3-message-consumer-integration.json +++ b/tests/PactNet.Tests/data/v3-message-consumer-integration.json @@ -36,8 +36,8 @@ "language": "C#" }, "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.13", + "models": "1.3.18" }, "pactSpecification": { "version": "3.0.0" diff --git a/tests/PactNet.Tests/data/v3-message-integration.json b/tests/PactNet.Tests/data/v3-message-integration.json index 4a3ace22b..07786942d 100644 --- a/tests/PactNet.Tests/data/v3-message-integration.json +++ b/tests/PactNet.Tests/data/v3-message-integration.json @@ -16,8 +16,8 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.13", + "models": "1.3.18" }, "pactSpecification": { "version": "3.0.0" diff --git a/tests/PactNet.Tests/data/v3-server-integration.json b/tests/PactNet.Tests/data/v3-server-integration.json index c5050bd5b..10db5b914 100644 --- a/tests/PactNet.Tests/data/v3-server-integration.json +++ b/tests/PactNet.Tests/data/v3-server-integration.json @@ -46,8 +46,8 @@ ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.13", + "models": "1.3.18" }, "pactSpecification": { "version": "3.0.0" diff --git a/tests/PactNet.Tests/data/v4-combined-integration.json b/tests/PactNet.Tests/data/v4-combined-integration.json index 618085116..097d43975 100644 --- a/tests/PactNet.Tests/data/v4-combined-integration.json +++ b/tests/PactNet.Tests/data/v4-combined-integration.json @@ -145,6 +145,7 @@ }, "status": 201 }, + "transport": "http", "type": "Synchronous/HTTP" }, { @@ -185,8 +186,8 @@ "language": "C#" }, "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.13", + "models": "1.3.18" }, "pactSpecification": { "version": "4.0" diff --git a/tests/PactNet.Tests/data/v4-consumer-integration.json b/tests/PactNet.Tests/data/v4-consumer-integration.json index 87ef562b3..5fb1d2372 100644 --- a/tests/PactNet.Tests/data/v4-consumer-integration.json +++ b/tests/PactNet.Tests/data/v4-consumer-integration.json @@ -145,13 +145,15 @@ }, "status": 201 }, + "transport": "http", "type": "Synchronous/HTTP" } ], "metadata": { "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.13", + "mockserver": "2.2.7", + "models": "1.3.18" }, "pactSpecification": { "version": "4.0" diff --git a/tests/PactNet.Tests/data/v4-message-consumer-integration.json b/tests/PactNet.Tests/data/v4-message-consumer-integration.json index 8861180b5..ddd378f10 100644 --- a/tests/PactNet.Tests/data/v4-message-consumer-integration.json +++ b/tests/PactNet.Tests/data/v4-message-consumer-integration.json @@ -41,8 +41,8 @@ "language": "C#" }, "pactRust": { - "ffi": "0.4.27", - "models": "1.2.8" + "ffi": "0.5.13", + "models": "1.3.18" }, "pactSpecification": { "version": "4.0"