diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 24caba99a..25691fa9f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -249,6 +249,11 @@ jobs: working-directory: ${{ env.WORKSPACE_ROOT }}/c/provider run: PACT_FFI_PREBUILT_DIR="$WORKSPACE_ROOT/rust/pact_ffi/build/install" just run + # Runs the compatibility suite through the C API, against the library and header installed above. + - name: Run FFI compatibility suite + working-directory: ${{ env.WORKSPACE_ROOT }}/compatibility-suite-ffi + run: cargo test --no-fail-fast + - name: Save Conan packages if: github.ref == 'refs/heads/master' && steps.conan-cache.outputs.cache-hit != 'true' uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 diff --git a/.gitignore b/.gitignore index 3a8ab2db8..a73c42f77 100644 --- a/.gitignore +++ b/.gitignore @@ -32,3 +32,4 @@ build/ pkg/ compatibility-suite/Cargo.lock +compatibility-suite-ffi/Cargo.lock diff --git a/compatibility-suite-ffi/Cargo.toml b/compatibility-suite-ffi/Cargo.toml new file mode 100644 index 000000000..79648f790 --- /dev/null +++ b/compatibility-suite-ffi/Cargo.toml @@ -0,0 +1,41 @@ +[package] +name = "pact-ffi-compat" +version = "0.1.0" +edition = "2021" +publish = false +description = "Pact compatibility suite driven only through the pact_ffi C ABI, logging each step's FFI calls" + +[dependencies] +anyhow = "1" +base64 = "0.22" +cucumber = "0.23" +libloading = "0.8" +regex = "1" +reqwest = { version = "0.12", default-features = false } +roxmltree = "0.20" +serde_json = "1" +tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "io-util"] } +url = "2" + +[build-dependencies] +bindgen = "0.72" + +[[test]] +name = "consumer" +harness = false + +[[test]] +name = "provider" +harness = false + +[[test]] +name = "matching" +harness = false + +[[test]] +name = "generators" +harness = false + +[[test]] +name = "message" +harness = false diff --git a/compatibility-suite-ffi/README.md b/compatibility-suite-ffi/README.md new file mode 100644 index 000000000..36c0d5c3e --- /dev/null +++ b/compatibility-suite-ffi/README.md @@ -0,0 +1,42 @@ +# FFI compatibility suite + +Runs the [Pact compatibility suite](https://github.com/pact-foundation/pact-compatibility-suite) through the +`pact_ffi` C API instead of the Rust crates. It uses the same copy of the suite as `../compatibility-suite` +(`../compatibility-suite/pact-compatibility-suite`), so the two runners check the same features. + +The bindings are generated from `pact.h` at build time and the library is loaded at run time, so one build of the +runner can test any `libpact_ffi`. + +## Running + +Build and install pact_ffi first (this also generates the header, which needs the nightly toolchain for cbindgen): + +```bash +.github/scripts/ffi-examples.sh +``` + +Then, from this directory: + +```bash +cargo test --no-fail-fast +``` + +| Variable | Default | +|-------------------|---------------------------------------------------------------------------------| +| `PACT_FFI_HEADER` | `../rust/pact_ffi/build/install/include/pact.h` (read at build time) | +| `PACT_FFI_LIB` | `../rust/pact_ffi/build/install/lib/` | +| `FFI_TRACE_DIR` | `target/ffi-trace`: each scenario's FFI calls, one file per scenario | + +## Tests + +| Test | Features | +|--------------|----------------------------------------------------------------------------------| +| `consumer` | V1–V4 `http_consumer` | +| `provider` | V1–V4 `*provider` (HTTP and message providers) | +| `matching` | V3 `http_matching` and `matching_rules`, V4 `matching_rules` | +| `generators` | V3 `generators` and `http_generators`, V4 `generators` | +| `message` | V3 `message_consumer`, V4 `message_consumer`, `synchronous_message_consumer`, `v4` | + +Scenarios tagged `wip` are skipped. `tests/matching.rs` also skips one known failure: the mock server reads a +0-byte body as no body, so the V4 "not empty matcher with binary data (negative case)" scenario can't get its +mismatch. diff --git a/compatibility-suite-ffi/build.rs b/compatibility-suite-ffi/build.rs new file mode 100644 index 000000000..18af3306d --- /dev/null +++ b/compatibility-suite-ffi/build.rs @@ -0,0 +1,22 @@ +// Generates runtime-loaded bindings for pact.h, so one binary can run against any libpact_ffi. +// The header defaults to the one `.github/scripts/ffi-examples.sh` installs; set PACT_FFI_HEADER to use another. +use std::{env, path::PathBuf}; + +fn main() { + let header = env::var("PACT_FFI_HEADER").unwrap_or_else(|_| { + concat!(env!("CARGO_MANIFEST_DIR"), "/../rust/pact_ffi/build/install/include/pact.h").to_string() + }); + println!("cargo:rerun-if-env-changed=PACT_FFI_HEADER"); + println!("cargo:rerun-if-changed={header}"); + bindgen::Builder::default() + .header(&header) + .allowlist_function("pactffi_.*") + .allowlist_type("PactHandle|InteractionHandle|InteractionPart|PactSpecification|VerifierHandle|MessageContents|AsynchronousMessage|SynchronousMessage|PactAsyncMessageIterator|PactSyncMessageIterator|MessageMetadataIterator|MessageMetadataPair|Generator|GeneratorCategoryIterator|GeneratorKeyValuePair|GeneratorCategory") + .prepend_enum_name(false) + .dynamic_library_name("PactFfi") + .dynamic_link_require_all(false) + .generate() + .expect("bindgen failed on pact.h") + .write_to_file(PathBuf::from(env::var("OUT_DIR").unwrap()).join("bindings.rs")) + .unwrap(); +} diff --git a/compatibility-suite-ffi/src/ffi.rs b/compatibility-suite-ffi/src/ffi.rs new file mode 100644 index 000000000..7d555076c --- /dev/null +++ b/compatibility-suite-ffi/src/ffi.rs @@ -0,0 +1,537 @@ +//! Safe wrappers over the pact_ffi C ABI. Every wrapper records the call, its arguments and its +//! result in the step trace, so the trace reads as the exact call sequence a client language makes. + +use std::ffi::{c_char, CStr, CString}; +use std::ptr; +use std::sync::OnceLock; + +use crate::trace; + +#[allow(non_camel_case_types, non_snake_case, non_upper_case_globals, dead_code, clippy::all)] +mod sys { + include!(concat!(env!("OUT_DIR"), "/bindings.rs")); +} + +pub use sys::{InteractionHandle, InteractionPart, PactHandle, PactSpecification}; +pub use sys::{InteractionPart_Request, InteractionPart_Response}; +pub use sys::{PactSpecification_V1, PactSpecification_V1_1, PactSpecification_V2, PactSpecification_V3, PactSpecification_V4}; + +static LIB: OnceLock = OnceLock::new(); + +/// Loads libpact_ffi from `path`. Must be called once before any other function here. +pub fn load(path: &str) -> anyhow::Result<()> { + let lib = unsafe { sys::PactFfi::new(path)? }; + LIB.set(lib).map_err(|_| anyhow::anyhow!("pact_ffi already loaded")) +} + +fn lib() -> &'static sys::PactFfi { + LIB.get().expect("pact_ffi not loaded") +} + +fn c(s: &str) -> CString { + CString::new(s).expect("string contains a NUL byte") +} + +/// Renders a string argument as a C literal, eliding long bodies. +fn lit(s: &str) -> String { + if s.chars().count() > 120 { + let head: String = s.chars().take(100).collect(); + format!("{head:?}/* …{} bytes */", s.len()) + } else { + format!("{s:?}") + } +} + +fn part(p: InteractionPart) -> &'static str { + if p == InteractionPart_Request { "InteractionPart_Request" } else { "InteractionPart_Response" } +} + +#[allow(non_upper_case_globals)] +pub fn spec_name(s: PactSpecification) -> &'static str { + match s { + PactSpecification_V1 => "PactSpecification_V1", + PactSpecification_V1_1 => "PactSpecification_V1_1", + PactSpecification_V2 => "PactSpecification_V2", + PactSpecification_V3 => "PactSpecification_V3", + PactSpecification_V4 => "PactSpecification_V4", + _ => "PactSpecification_Unknown", + } +} + +pub fn new_pact(consumer: &str, provider: &str) -> PactHandle { + let r = unsafe { lib().pactffi_new_pact(c(consumer).as_ptr(), c(provider).as_ptr()) }; + trace::call(format!("pactffi_new_pact({}, {})", lit(consumer), lit(provider)), r); + r +} + +pub fn with_specification(pact: PactHandle, spec: PactSpecification) -> bool { + let r = unsafe { lib().pactffi_with_specification(pact, spec) }; + trace::call(format!("pactffi_with_specification({pact}, {})", spec_name(spec)), r); + r +} + +pub fn new_interaction(pact: PactHandle, description: &str) -> InteractionHandle { + let r = unsafe { lib().pactffi_new_interaction(pact, c(description).as_ptr()) }; + trace::call(format!("pactffi_new_interaction({pact}, {})", lit(description)), r); + r +} + +pub fn with_request(i: InteractionHandle, method: &str, path: &str) -> bool { + let r = unsafe { lib().pactffi_with_request(i, c(method).as_ptr(), c(path).as_ptr()) }; + trace::call(format!("pactffi_with_request({i}, {}, {})", lit(method), lit(path)), r); + r +} + +pub fn with_query_parameter_v2(i: InteractionHandle, name: &str, index: usize, value: &str) -> bool { + let r = unsafe { lib().pactffi_with_query_parameter_v2(i, c(name).as_ptr(), index, c(value).as_ptr()) }; + trace::call(format!("pactffi_with_query_parameter_v2({i}, {}, {index}, {})", lit(name), lit(value)), r); + r +} + +pub fn with_header_v2(i: InteractionHandle, p: InteractionPart, name: &str, index: usize, value: &str) -> bool { + let r = unsafe { lib().pactffi_with_header_v2(i, p, c(name).as_ptr(), index, c(value).as_ptr()) }; + trace::call(format!("pactffi_with_header_v2({i}, {}, {}, {index}, {})", part(p), lit(name), lit(value)), r); + r +} + +/// `rules` is a JSON object of matching rules, V2 style (`{"$.body.a": {"match": "type"}}`) or V3+ by category. +pub fn with_matching_rules(i: InteractionHandle, p: InteractionPart, rules: &str) -> bool { + let r = unsafe { lib().pactffi_with_matching_rules(i, p, c(rules).as_ptr()) }; + trace::call(format!("pactffi_with_matching_rules({i}, {}, {})", part(p), lit(rules)), r); + r +} + +pub fn response_status(i: InteractionHandle, status: u16) -> bool { + let r = unsafe { lib().pactffi_response_status(i, status) }; + trace::call(format!("pactffi_response_status({i}, {status})"), r); + r +} + +pub fn with_body(i: InteractionHandle, p: InteractionPart, content_type: &str, body: &str) -> bool { + let r = unsafe { lib().pactffi_with_body(i, p, c(content_type).as_ptr(), c(body).as_ptr()) }; + trace::call(format!("pactffi_with_body({i}, {}, {}, {})", part(p), lit(content_type), lit(body)), r); + r +} + +pub fn with_binary_body(i: InteractionHandle, p: InteractionPart, content_type: &str, body: &[u8]) -> bool { + let r = unsafe { lib().pactffi_with_binary_body(i, p, c(content_type).as_ptr(), body.as_ptr(), body.len()) }; + trace::call(format!("pactffi_with_binary_body({i}, {}, {}, /* {} bytes */, {})", part(p), lit(content_type), + body.len(), body.len()), r); + r +} + +pub fn create_mock_server_for_transport(pact: PactHandle, addr: &str, port: u16, transport: &str) -> i32 { + let r = unsafe { + lib().pactffi_create_mock_server_for_transport(pact, c(addr).as_ptr(), port, c(transport).as_ptr(), ptr::null()) + }; + trace::call(format!("pactffi_create_mock_server_for_transport({pact}, {}, {port}, {}, NULL)", lit(addr), lit(transport)), r); + r +} + +pub fn mock_server_matched(port: i32) -> bool { + let r = unsafe { lib().pactffi_mock_server_matched(port) }; + trace::call(format!("pactffi_mock_server_matched({port})"), r); + r +} + +/// The returned string is owned by the mock server and freed by `pactffi_cleanup_mock_server`, +/// so it is copied here and must not be passed to `pactffi_string_delete`. +pub fn mock_server_mismatches(port: i32) -> Option { + let p: *mut c_char = unsafe { lib().pactffi_mock_server_mismatches(port) }; + let r = (!p.is_null()).then(|| unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned()); + trace::call(format!("pactffi_mock_server_mismatches({port})"), r.as_deref().map(lit).unwrap_or("NULL".into())); + r +} + +pub fn write_pact_file(port: i32, dir: &str, overwrite: bool) -> i32 { + let r = unsafe { lib().pactffi_write_pact_file(port, c(dir).as_ptr(), overwrite) }; + trace::call(format!("pactffi_write_pact_file({port}, {}, {overwrite})", lit(dir)), r); + r +} + +pub fn cleanup_mock_server(port: i32) -> bool { + let r = unsafe { lib().pactffi_cleanup_mock_server(port) }; + trace::call(format!("pactffi_cleanup_mock_server({port})"), r); + r +} + +pub fn free_pact_handle(pact: PactHandle) -> u32 { + let r = unsafe { lib().pactffi_free_pact_handle(pact) }; + trace::call(format!("pactffi_free_pact_handle({pact})"), r); + r +} + +pub fn given(i: InteractionHandle, state: &str) -> bool { + let r = unsafe { lib().pactffi_given(i, c(state).as_ptr()) }; + trace::call(format!("pactffi_given({i}, {})", lit(state)), r); + r +} + +/// `params` is a JSON object of the state's parameters. +pub fn given_with_params(i: InteractionHandle, state: &str, params: &str) -> i32 { + let r = unsafe { lib().pactffi_given_with_params(i, c(state).as_ptr(), c(params).as_ptr()) }; + trace::call(format!("pactffi_given_with_params({i}, {}, {})", lit(state), lit(params)), r); + r +} + +/// Writes the pact for a handle that never had a mock server, as a provider test fixture would. +pub fn pact_handle_write_file(pact: PactHandle, dir: &str, overwrite: bool) -> i32 { + let r = unsafe { lib().pactffi_pact_handle_write_file(pact, c(dir).as_ptr(), overwrite) }; + trace::call(format!("pactffi_pact_handle_write_file({pact}, {}, {overwrite})", lit(dir)), r); + r +} + +/// An opaque `VerifierHandle *`. Not `Send` in C terms, but the verifier owns no thread-affine state, +/// so the pointer is carried across to the blocking thread that runs the verification. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Verifier(usize); + +impl Verifier { + fn h(self) -> *mut sys::VerifierHandle { + self.0 as *mut sys::VerifierHandle + } +} + +impl std::fmt::Display for Verifier { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "handle") + } +} + +fn opt(s: Option<&str>) -> (Option, String) { + match s { + Some(s) => (Some(c(s)), lit(s)), + None => (None, "NULL".into()), + } +} + +fn opt_ptr(s: &Option) -> *const c_char { + s.as_ref().map(|s| s.as_ptr()).unwrap_or(ptr::null()) +} + +/// Copies and frees a string the verifier handed over; these are caller-owned (`pactffi_string_delete`). +fn take_string(p: *const c_char) -> Option { + if p.is_null() { + return None; + } + let s = unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned(); + unsafe { lib().pactffi_string_delete(p as *mut c_char) }; + Some(s) +} + +pub fn verifier_new_for_application(name: &str, version: &str) -> Verifier { + let h = unsafe { lib().pactffi_verifier_new_for_application(c(name).as_ptr(), c(version).as_ptr()) }; + trace::call(format!("handle = pactffi_verifier_new_for_application({}, {})", lit(name), lit(version)), + if h.is_null() { "NULL" } else { "VerifierHandle *" }); + Verifier(h as usize) +} + +pub fn verifier_set_provider_info(v: Verifier, name: &str, scheme: &str, host: &str, port: u16, path: &str) { + unsafe { + lib().pactffi_verifier_set_provider_info(v.h(), c(name).as_ptr(), c(scheme).as_ptr(), c(host).as_ptr(), port, + c(path).as_ptr()) + }; + trace::call(format!("pactffi_verifier_set_provider_info({v}, {}, {}, {}, {port}, {})", lit(name), lit(scheme), + lit(host), lit(path)), "void"); +} + +pub fn verifier_set_provider_state(v: Verifier, url: &str, teardown: bool, body: bool) { + unsafe { lib().pactffi_verifier_set_provider_state(v.h(), c(url).as_ptr(), teardown as u8, body as u8) }; + trace::call(format!("pactffi_verifier_set_provider_state({v}, {}, {}, {})", lit(url), teardown as u8, body as u8), + "void"); +} + +pub fn verifier_set_publish_options(v: Verifier, provider_version: &str) -> i32 { + let r = unsafe { + lib().pactffi_verifier_set_publish_options(v.h(), c(provider_version).as_ptr(), ptr::null(), ptr::null(), 0, + ptr::null()) + }; + trace::call(format!("pactffi_verifier_set_publish_options({v}, {}, NULL, NULL, 0, NULL)", lit(provider_version)), r); + r +} + +pub fn verifier_add_custom_header(v: Verifier, name: &str, value: &str) { + unsafe { lib().pactffi_verifier_add_custom_header(v.h(), c(name).as_ptr(), c(value).as_ptr()) }; + trace::call(format!("pactffi_verifier_add_custom_header({v}, {}, {})", lit(name), lit(value)), "void"); +} + +pub fn verifier_add_file_source(v: Verifier, file: &str) { + unsafe { lib().pactffi_verifier_add_file_source(v.h(), c(file).as_ptr()) }; + trace::call(format!("pactffi_verifier_add_file_source({v}, {})", lit(file)), "void"); +} + +/// A broker source with dynamic configuration (`pacts for verification`), no auth, selectors, tags or branch. +pub fn verifier_broker_source_with_selectors(v: Verifier, url: &str, enable_pending: bool, branch: Option<&str>) + -> i32 { + let (branch_c, branch_lit) = opt(branch); + let r = unsafe { + lib().pactffi_verifier_broker_source_with_selectors(v.h(), c(url).as_ptr(), ptr::null(), ptr::null(), + ptr::null(), enable_pending as u8, ptr::null(), ptr::null(), 0, opt_ptr(&branch_c), ptr::null(), 0, + ptr::null(), 0) + }; + trace::call(format!("pactffi_verifier_broker_source_with_selectors({v}, {}, NULL, NULL, NULL, {}, NULL, NULL, 0, \ + {branch_lit}, NULL, 0, NULL, 0)", lit(url), enable_pending as u8), r); + r +} + +/// Blocks until the verification has run against every source. 0 is success, 1 a failed verification. +pub fn verifier_execute(v: Verifier) -> i32 { + let r = unsafe { lib().pactffi_verifier_execute(v.h()) }; + trace::call(format!("pactffi_verifier_execute({v})"), r); + r +} + +pub fn verifier_json(v: Verifier) -> Option { + let r = take_string(unsafe { lib().pactffi_verifier_json(v.h()) }); + trace::call(format!("json = pactffi_verifier_json({v})"), r.as_deref().map(lit).unwrap_or("NULL".into())); + if r.is_some() { + trace::call("pactffi_string_delete(json)".into(), "void"); + } + r +} + +pub fn verifier_output(v: Verifier, strip_ansi: bool) -> Option { + let r = take_string(unsafe { lib().pactffi_verifier_output(v.h(), strip_ansi as u8) }); + trace::call(format!("output = pactffi_verifier_output({v}, {})", strip_ansi as u8), + r.as_deref().map(lit).unwrap_or("NULL".into())); + if r.is_some() { + trace::call("pactffi_string_delete(output)".into(), "void"); + } + r +} + +pub fn verifier_shutdown(v: Verifier) { + unsafe { lib().pactffi_verifier_shutdown(v.h()) }; + trace::call(format!("pactffi_verifier_shutdown({v})"), "void"); +} + +// ---- V3/V4 interaction setters ---- + +/// `generators` is a JSON object of generators by category (`{"body": {"$.a": {"type": "RandomInt"}}}`). +pub fn with_generators(i: InteractionHandle, p: InteractionPart, generators: &str) -> bool { + let r = unsafe { lib().pactffi_with_generators(i, p, c(generators).as_ptr()) }; + trace::call(format!("pactffi_with_generators({i}, {}, {})", part(p), lit(generators)), r); + r +} + +pub fn given_with_param(i: InteractionHandle, state: &str, name: &str, value: &str) -> bool { + let r = unsafe { lib().pactffi_given_with_param(i, c(state).as_ptr(), c(name).as_ptr(), c(value).as_ptr()) }; + trace::call(format!("pactffi_given_with_param({i}, {}, {}, {})", lit(state), lit(name), lit(value)), r); + r +} + +/// `value` is parsed as JSON where it can be, else kept as a string. +pub fn with_metadata(i: InteractionHandle, key: &str, value: &str, p: InteractionPart) -> bool { + let r = unsafe { lib().pactffi_with_metadata(i, c(key).as_ptr(), c(value).as_ptr(), p) }; + trace::call(format!("pactffi_with_metadata({i}, {}, {}, {})", lit(key), lit(value), part(p)), r); + r +} + +pub fn set_pending(i: InteractionHandle, pending: bool) -> bool { + let r = unsafe { lib().pactffi_set_pending(i, pending) }; + trace::call(format!("pactffi_set_pending({i}, {pending})"), r); + r +} + +pub fn set_key(i: InteractionHandle, key: &str) -> bool { + let r = unsafe { lib().pactffi_set_key(i, c(key).as_ptr()) }; + trace::call(format!("pactffi_set_key({i}, {})", lit(key)), r); + r +} + +pub fn set_comment(i: InteractionHandle, key: &str, value: &str) -> bool { + let r = unsafe { lib().pactffi_set_comment(i, c(key).as_ptr(), c(value).as_ptr()) }; + trace::call(format!("pactffi_set_comment({i}, {}, {})", lit(key), lit(value)), r); + r +} + +pub fn add_text_comment(i: InteractionHandle, comment: &str) -> bool { + let r = unsafe { lib().pactffi_add_text_comment(i, c(comment).as_ptr()) }; + trace::call(format!("pactffi_add_text_comment({i}, {})", lit(comment)), r); + r +} + +pub fn interaction_test_name(i: InteractionHandle, name: &str) -> u32 { + let r = unsafe { lib().pactffi_interaction_test_name(i, c(name).as_ptr()) }; + trace::call(format!("pactffi_interaction_test_name({i}, {})", lit(name)), r); + r +} + +pub fn new_message_interaction(pact: PactHandle, description: &str) -> InteractionHandle { + let r = unsafe { lib().pactffi_new_message_interaction(pact, c(description).as_ptr()) }; + trace::call(format!("pactffi_new_message_interaction({pact}, {})", lit(description)), r); + r +} + +pub fn new_sync_message_interaction(pact: PactHandle, description: &str) -> InteractionHandle { + let r = unsafe { lib().pactffi_new_sync_message_interaction(pact, c(description).as_ptr()) }; + trace::call(format!("pactffi_new_sync_message_interaction({pact}, {})", lit(description)), r); + r +} + +pub fn verifier_add_provider_transport(v: Verifier, protocol: &str, port: u16, path: &str, scheme: &str) { + unsafe { + lib().pactffi_verifier_add_provider_transport(v.h(), c(protocol).as_ptr(), port, c(path).as_ptr(), + c(scheme).as_ptr()) + }; + trace::call(format!("pactffi_verifier_add_provider_transport({v}, {}, {port}, {}, {})", lit(protocol), lit(path), + lit(scheme)), "void"); +} + +// ---- Reading messages back ---- + +/// One message's contents with generators applied: the body bytes and the metadata, values as JSON text. +#[derive(Debug, Clone, Default)] +pub struct Contents { + pub body: Option>, + pub metadata: Vec<(String, String)>, +} + +impl Contents { + pub fn body_str(&self) -> Option { + self.body.as_ref().map(|b| String::from_utf8_lossy(b).into_owned()) + } +} + +/// Reads a `MessageContents *` the caller owns, then frees it with `pactffi_message_contents_delete`. +fn read_contents(contents: *const sys::MessageContents, name: &str) -> Contents { + let lib = lib(); + let mut out = Contents::default(); + if contents.is_null() { + return out; + } + let len = unsafe { lib.pactffi_message_contents_get_contents_length(contents) }; + trace::call(format!("pactffi_message_contents_get_contents_length({name})"), len); + if len > 0 { + let p = unsafe { lib.pactffi_message_contents_get_contents_bin(contents) }; + trace::call(format!("pactffi_message_contents_get_contents_bin({name})"), format!("/* {len} bytes */")); + if !p.is_null() { + out.body = Some(unsafe { std::slice::from_raw_parts(p, len) }.to_vec()); + } + } + let iter = unsafe { lib.pactffi_message_contents_get_metadata_iter(contents) }; + trace::call(format!("meta = pactffi_message_contents_get_metadata_iter({name})"), if iter.is_null() { "NULL" } else { "iter" }); + if !iter.is_null() { + loop { + let pair = unsafe { lib.pactffi_message_metadata_iter_next(iter) }; + if pair.is_null() { + trace::call("pactffi_message_metadata_iter_next(meta)".into(), "NULL"); + break; + } + let (k, v) = unsafe { + (CStr::from_ptr((*pair).key).to_string_lossy().into_owned(), CStr::from_ptr((*pair).value).to_string_lossy().into_owned()) + }; + trace::call("pactffi_message_metadata_iter_next(meta)".into(), format!("{{{}, {}}}", lit(&k), lit(&v))); + unsafe { lib.pactffi_message_metadata_pair_delete(pair) }; + out.metadata.push((k, v)); + } + unsafe { lib.pactffi_message_metadata_iter_delete(iter) }; + trace::call("pactffi_message_metadata_iter_delete(meta)".into(), "void"); + } + unsafe { lib.pactffi_message_contents_delete(contents as *mut _) }; + trace::call(format!("pactffi_message_contents_delete({name})"), "void"); + out +} + +/// Every async message in the pact, generated as a consumer test would see it. +pub fn async_messages(pact: PactHandle) -> Vec { + let lib = lib(); + let iter = unsafe { lib.pactffi_pact_handle_get_async_message_iter(pact) }; + trace::call(format!("iter = pactffi_pact_handle_get_async_message_iter({pact})"), if iter.is_null() { "NULL" } else { "iter" }); + let mut out = vec![]; + if iter.is_null() { + return out; + } + loop { + let m = unsafe { lib.pactffi_pact_async_message_iter_next(iter) }; + trace::call("message = pactffi_pact_async_message_iter_next(iter)".into(), if m.is_null() { "NULL" } else { "message" }); + if m.is_null() { + break; + } + let contents = unsafe { lib.pactffi_async_message_generate_contents(m) }; + trace::call("contents = pactffi_async_message_generate_contents(message)".into(), if contents.is_null() { "NULL" } else { "contents" }); + out.push(read_contents(contents, "contents")); + } + unsafe { lib.pactffi_pact_async_message_iter_delete(iter) }; + trace::call("pactffi_pact_async_message_iter_delete(iter)".into(), "void"); + out +} + +/// Every sync message in the pact as (request, responses), generated. +pub fn sync_messages(pact: PactHandle) -> Vec<(Contents, Vec)> { + let lib = lib(); + let iter = unsafe { lib.pactffi_pact_handle_get_sync_message_iter(pact) }; + trace::call(format!("iter = pactffi_pact_handle_get_sync_message_iter({pact})"), if iter.is_null() { "NULL" } else { "iter" }); + let mut out = vec![]; + if iter.is_null() { + return out; + } + loop { + let m = unsafe { lib.pactffi_pact_sync_message_iter_next(iter) }; + trace::call("message = pactffi_pact_sync_message_iter_next(iter)".into(), if m.is_null() { "NULL" } else { "message" }); + if m.is_null() { + break; + } + let req = unsafe { lib.pactffi_sync_message_generate_request_contents(m) }; + trace::call("request = pactffi_sync_message_generate_request_contents(message)".into(), if req.is_null() { "NULL" } else { "request" }); + let request = read_contents(req, "request"); + let n = unsafe { lib.pactffi_sync_message_get_number_responses(m) }; + trace::call("pactffi_sync_message_get_number_responses(message)".into(), n); + let responses = (0..n).map(|idx| { + let r = unsafe { lib.pactffi_sync_message_generate_response_contents(m, idx) }; + trace::call(format!("response = pactffi_sync_message_generate_response_contents(message, {idx})"), if r.is_null() { "NULL" } else { "response" }); + read_contents(r, "response") + }).collect(); + out.push((request, responses)); + } + unsafe { lib.pactffi_pact_sync_message_iter_delete(iter) }; + trace::call("pactffi_pact_sync_message_iter_delete(iter)".into(), "void"); + out +} + +/// The first async message's body generators, each run with `context` (a JSON object), as (path, value). +/// There's no call that generates contents with a context, so a client walks the generators itself. +pub fn async_body_generators_with_context(pact: PactHandle, context: &str) -> Vec<(String, Option)> { + let lib = lib(); + let iter = unsafe { lib.pactffi_pact_handle_get_async_message_iter(pact) }; + trace::call(format!("iter = pactffi_pact_handle_get_async_message_iter({pact})"), if iter.is_null() { "NULL" } else { "iter" }); + let mut out = vec![]; + if iter.is_null() { + return out; + } + let m = unsafe { lib.pactffi_pact_async_message_iter_next(iter) }; + trace::call("message = pactffi_pact_async_message_iter_next(iter)".into(), if m.is_null() { "NULL" } else { "message" }); + if !m.is_null() { + let contents = unsafe { lib.pactffi_async_message_get_contents(m) }; + trace::call("contents = pactffi_async_message_get_contents(message)".into(), if contents.is_null() { "NULL" } else { "contents" }); + let gens = unsafe { lib.pactffi_message_contents_get_generators_iter(contents, sys::GeneratorCategory_BODY) }; + trace::call("gens = pactffi_message_contents_get_generators_iter(contents, GeneratorCategory_BODY)".into(), + if gens.is_null() { "NULL" } else { "gens" }); + if !gens.is_null() { + loop { + let pair = unsafe { lib.pactffi_generators_iter_next(gens) }; + if pair.is_null() { + trace::call("pactffi_generators_iter_next(gens)".into(), "NULL"); + break; + } + let path = unsafe { CStr::from_ptr((*pair).path) }.to_string_lossy().into_owned(); + trace::call("pair = pactffi_generators_iter_next(gens)".into(), format!("{{path: {}, generator}}", lit(&path))); + let v = unsafe { lib.pactffi_generator_generate_string((*pair).generator, c(context).as_ptr()) }; + let value = take_string(v); + trace::call(format!("value = pactffi_generator_generate_string(pair->generator, {})", lit(context)), + value.as_deref().map(lit).unwrap_or("NULL".into())); + if value.is_some() { + trace::call("pactffi_string_delete(value)".into(), "void"); + } + unsafe { lib.pactffi_generators_iter_pair_delete(pair) }; + trace::call("pactffi_generators_iter_pair_delete(pair)".into(), "void"); + out.push((path, value)); + } + unsafe { lib.pactffi_generators_iter_delete(gens) }; + trace::call("pactffi_generators_iter_delete(gens)".into(), "void"); + } + } + unsafe { lib.pactffi_pact_async_message_iter_delete(iter) }; + trace::call("pactffi_pact_async_message_iter_delete(iter)".into(), "void"); + out +} diff --git a/compatibility-suite-ffi/src/lib.rs b/compatibility-suite-ffi/src/lib.rs new file mode 100644 index 000000000..aee08b14f --- /dev/null +++ b/compatibility-suite-ffi/src/lib.rs @@ -0,0 +1,6 @@ +//! A Pact compatibility suite runner that drives the core only through the pact_ffi C ABI. + +pub mod ffi; +pub mod model; +pub mod server; +pub mod trace; diff --git a/compatibility-suite-ffi/src/model.rs b/compatibility-suite-ffi/src/model.rs new file mode 100644 index 000000000..b86bd22e2 --- /dev/null +++ b/compatibility-suite-ffi/src/model.rs @@ -0,0 +1,215 @@ +//! The suite's interaction tables as plain data, and how they are registered through the FFI. +//! Mirrors `setup_common_interactions` / `setup_body` in the pact-reference compatibility suite. + +use std::collections::HashMap; +use std::env::{self, consts::{DLL_PREFIX, DLL_SUFFIX}}; +use std::fs; + +use crate::ffi::{self, InteractionHandle, InteractionPart, InteractionPart_Request, InteractionPart_Response, PactHandle}; + +/// The copy of the suite that `compatibility-suite` also runs. +pub const FEATURES: &str = "../compatibility-suite/pact-compatibility-suite/features"; +pub const FIXTURES: &str = "../compatibility-suite/pact-compatibility-suite/fixtures"; + +/// The libpact_ffi to load: `PACT_FFI_LIB`, or the one `.github/scripts/ffi-examples.sh` installs. +pub fn ffi_lib() -> String { + env::var("PACT_FFI_LIB") + .unwrap_or_else(|_| format!("../rust/pact_ffi/build/install/lib/{DLL_PREFIX}pact_ffi{DLL_SUFFIX}")) +} + +#[derive(Debug, Clone, Default)] +pub struct Part { + pub headers: Vec<(String, String)>, + pub body: Option>, + /// Matching rules as JSON text, passed to the FFI unchanged. + pub matching_rules: Option, +} + +impl Part { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()) + } + + pub fn set_header(&mut self, name: &str, value: &str) { + self.headers.retain(|(k, _)| !k.eq_ignore_ascii_case(name)); + self.headers.push((name.to_string(), value.to_string())); + } +} + +#[derive(Debug, Clone, Default)] +pub struct Interaction { + pub description: String, + pub method: String, + pub path: String, + pub query: String, + pub request: Part, + pub status: u16, + pub response: Part, +} + +/// Builds interactions from a Gherkin table whose first row names the columns. +pub fn setup_common_interactions(rows: &[Vec]) -> Vec { + let cols: HashMap<&str, usize> = rows[0].iter().enumerate().map(|(i, h)| (h.as_str(), i)).collect(); + rows.iter().skip(1).enumerate().map(|(row, values)| { + let get = |name: &str| cols.get(name).and_then(|i| values.get(*i)).cloned().unwrap_or_default(); + let mut interaction = Interaction { + description: format!("Interaction {row}"), + method: get("method"), + path: get("path"), + query: get("query"), + status: get("response").parse().unwrap_or(200), + ..Interaction::default() + }; + interaction.request.headers = parse_headers(&get("headers")); + setup_body(&get("body"), &mut interaction.request); + interaction.response.headers = parse_headers(&get("response headers")); + setup_body(&get("response body"), &mut interaction.response); + interaction.request.matching_rules = matching_rules(&get("matching rules")); + interaction.response.matching_rules = matching_rules(&get("response matching rules")); + interaction + }).collect() +} + +/// A `matching rules` cell: a fixture file name or inline `JSON: {...}`. +pub fn matching_rules(cell: &str) -> Option { + if cell.is_empty() { + None + } else if let Some(json) = cell.strip_prefix("JSON:") { + Some(json.trim().to_string()) + } else { + Some(fs::read_to_string(format!("{FIXTURES}/{}", cell.trim())).unwrap_or_else(|e| panic!("fixture {cell}: {e}"))) + } +} + +/// Parses `'Name: value', 'Other: value'` cells. +pub fn parse_headers(cell: &str) -> Vec<(String, String)> { + if cell.is_empty() { + return vec![]; + } + cell.split(',').filter_map(|h| { + let h = h.trim(); + let h = h.strip_prefix('\'').unwrap_or(h); + let h = h.strip_suffix('\'').unwrap_or(h); + h.split_once(':').map(|(k, v)| (k.trim().to_string(), v.trim().to_string())) + }).collect() +} + +/// Query string to ordered (name, value) pairs, percent-decoded. +pub fn parse_query(query: &str) -> Vec<(String, String)> { + url::form_urlencoded::parse(query.as_bytes()).into_owned().collect() +} + +/// Query pairs grouped by name, for order-insensitive comparison. +pub fn query_map(pairs: &[(String, String)]) -> HashMap> { + let mut map: HashMap> = HashMap::new(); + for (k, v) in pairs { + map.entry(k.clone()).or_default().push(v.clone()); + } + map +} + +pub fn setup_body(cell: &str, part: &mut Part) { + setup_body_as(cell, part, None) +} + +/// As `setup_body`, with the content type a table's "content type" column gives, where it has one. +pub fn setup_body_as(cell: &str, part: &mut Part, content_type_override: Option<&str>) { + if cell.is_empty() { + return; + } + let (content_type, body) = if let Some(json) = cell.strip_prefix("JSON:") { + ("application/json".to_string(), json.trim().as_bytes().to_vec()) + } else if let Some(xml) = cell.strip_prefix("XML:") { + ("application/xml".to_string(), xml.trim().as_bytes().to_vec()) + } else if let Some(file) = cell.strip_prefix("file:") { + let file = file.trim(); + if file.ends_with("-body.xml") { + let (ct, contents) = body_fixture(file); + (ct, contents.into_bytes()) + } else { + let bytes = fs::read(format!("{FIXTURES}/{file}")).unwrap_or_else(|e| panic!("fixture {file}: {e}")); + (determine_content_type(file, part), bytes) + } + } else { + let body = if cell == "EMPTY" { "" } else { cell }; + (determine_content_type(body, part), body.as_bytes().to_vec()) + }; + let content_type = content_type_override.map(str::to_string).unwrap_or(content_type); + part.set_header("content-type", &content_type); + part.body = Some(body); +} + +fn determine_content_type(body: &str, part: &Part) -> String { + let ct = if body.ends_with(".json") { + "application/json" + } else if body.ends_with(".xml") { + "application/xml" + } else if body.ends_with(".jpg") { + "image/jpeg" + } else if body.ends_with(".pdf") { + "application/pdf" + } else { + part.header("content-type").unwrap_or("text/plain") + }; + ct.to_string() +} + +/// Reads a `*-body.xml` fixture: ``. +fn body_fixture(file: &str) -> (String, String) { + let xml = fs::read_to_string(format!("{FIXTURES}/{file}")).unwrap_or_else(|e| panic!("fixture {file}: {e}")); + let doc = roxmltree::Document::parse(&xml).unwrap_or_else(|e| panic!("fixture {file}: {e}")); + let text = |name: &str| { + doc.root_element().children().find(|n| n.has_tag_name(name)).map(|n| { + let s: String = n.children().filter_map(|c| c.text()).map(str::trim).collect(); + // The XML parser normalises line endings to LF, even on a Windows checkout with CRLF files + if n.attribute("eol") == Some("CRLF") { s.replace("\r\n", "\n").replace('\n', "\r\n") } else { s } + }) + }; + (text("contentType").unwrap_or_else(|| "text/plain".into()), text("contents").unwrap_or_default()) +} + +pub fn is_binary(content_type: &str, body: &[u8]) -> bool { + let ct = content_type.to_ascii_lowercase(); + ct.starts_with("image/") || ct.starts_with("application/pdf") || ct.starts_with("application/octet-stream") + || std::str::from_utf8(body).is_err() +} + +pub fn register_part(i: InteractionHandle, p: InteractionPart, part: &Part) { + let mut index: HashMap = HashMap::new(); + for (k, v) in &part.headers { + // The content type travels with the body; pactffi_with_body sets the header from it. + if part.body.is_some() && k.eq_ignore_ascii_case("content-type") { + continue; + } + let n = index.entry(k.to_ascii_lowercase()).or_default(); + ffi::with_header_v2(i, p, k, *n, v); + *n += 1; + } + if let Some(body) = &part.body { + let ct = part.header("content-type").unwrap_or("text/plain"); + if is_binary(ct, body) { + ffi::with_binary_body(i, p, ct, body); + } else { + ffi::with_body(i, p, ct, std::str::from_utf8(body).unwrap()); + } + } + if let Some(rules) = &part.matching_rules { + ffi::with_matching_rules(i, p, rules); + } +} + +/// Adds one HTTP interaction to `pact` with the calls a client library would make. +pub fn register(pact: PactHandle, interaction: &Interaction) -> InteractionHandle { + let i = ffi::new_interaction(pact, &interaction.description); + ffi::with_request(i, &interaction.method, &interaction.path); + let mut index: HashMap = HashMap::new(); + for (k, v) in parse_query(&interaction.query) { + let n = index.entry(k.clone()).or_default(); + ffi::with_query_parameter_v2(i, &k, *n, &v); + *n += 1; + } + register_part(i, InteractionPart_Request, &interaction.request); + ffi::response_status(i, interaction.status); + register_part(i, InteractionPart_Response, &interaction.response); + i +} diff --git a/compatibility-suite-ffi/src/server.rs b/compatibility-suite-ffi/src/server.rs new file mode 100644 index 000000000..071de1c4e --- /dev/null +++ b/compatibility-suite-ffi/src/server.rs @@ -0,0 +1,136 @@ +//! A minimal recording HTTP/1.1 server, used as the provider under test, the provider state callback and +//! a stand-in Pact broker. Each connection serves one request and closes, which is all the verifier needs. + +use std::sync::{Arc, Mutex}; + +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; +use tokio::task::JoinHandle; + +#[derive(Debug, Clone, Default)] +pub struct Request { + pub method: String, + /// Path and query, as sent. + pub path: String, + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +impl Request { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()) + } + + pub fn path_only(&self) -> &str { + self.path.split('?').next().unwrap_or_default() + } +} + +#[derive(Debug, Clone, Default)] +pub struct Response { + pub status: u16, + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +impl Response { + pub fn json(status: u16, body: &serde_json::Value) -> Response { + Response { + status, + headers: vec![("Content-Type".into(), "application/json".into())], + body: body.to_string().into_bytes(), + } + } +} + +pub type Handler = Arc Response + Send + Sync>; + +#[derive(Debug)] +pub struct Server { + pub port: u16, + requests: Arc>>, + task: JoinHandle<()>, +} + +impl Server { + /// Binds 127.0.0.1 on a free port. The handler also gets the port, for absolute links in responses. + pub async fn start(handler: Handler) -> anyhow::Result { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let port = listener.local_addr()?.port(); + let requests: Arc>> = Arc::default(); + let recorded = requests.clone(); + let task = tokio::spawn(async move { + while let Ok((mut stream, _)) = listener.accept().await { + let handler = handler.clone(); + let recorded = recorded.clone(); + tokio::spawn(async move { + let Some(req) = read_request(&mut stream).await else { return }; + let res = handler(&req, port); + recorded.lock().unwrap().push(req); + let _ = stream.write_all(&encode(&res)).await; + let _ = stream.shutdown().await; + }); + } + }); + Ok(Server { port, requests, task }) + } + + pub fn url(&self) -> String { + format!("http://127.0.0.1:{}", self.port) + } + + pub fn requests(&self) -> Vec { + self.requests.lock().unwrap().clone() + } +} + +impl Drop for Server { + fn drop(&mut self) { + self.task.abort(); + } +} + +async fn read_request(stream: &mut tokio::net::TcpStream) -> Option { + let mut buf = Vec::new(); + let mut chunk = [0u8; 8192]; + let head_end = loop { + if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + break i; + } + let n = stream.read(&mut chunk).await.ok()?; + if n == 0 { + return None; + } + buf.extend_from_slice(&chunk[..n]); + }; + let head = String::from_utf8_lossy(&buf[..head_end]).into_owned(); + let mut lines = head.split("\r\n"); + let mut start = lines.next()?.split(' '); + let method = start.next()?.to_string(); + let path = start.next()?.to_string(); + let headers: Vec<(String, String)> = lines + .filter_map(|l| l.split_once(':').map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))) + .collect(); + let len: usize = headers.iter().find(|(k, _)| k.eq_ignore_ascii_case("content-length")) + .and_then(|(_, v)| v.parse().ok()).unwrap_or(0); + let mut body = buf[head_end + 4..].to_vec(); + while body.len() < len { + let n = stream.read(&mut chunk).await.ok()?; + if n == 0 { + break; + } + body.extend_from_slice(&chunk[..n]); + } + Some(Request { method, path, headers, body }) +} + +fn encode(res: &Response) -> Vec { + let mut out = format!("HTTP/1.1 {} X\r\n", res.status); + for (k, v) in &res.headers { + out.push_str(&format!("{k}: {v}\r\n")); + } + out.push_str(&format!("Content-Length: {}\r\nConnection: close\r\n\r\n", res.body.len())); + let mut bytes = out.into_bytes(); + bytes.extend_from_slice(&res.body); + bytes +} diff --git a/compatibility-suite-ffi/src/trace.rs b/compatibility-suite-ffi/src/trace.rs new file mode 100644 index 000000000..6e644a33e --- /dev/null +++ b/compatibility-suite-ffi/src/trace.rs @@ -0,0 +1,56 @@ +//! Per-scenario log of Gherkin steps and the pact_ffi calls each one made. Scenarios run one at a +//! time, so a single global log is enough. + +use std::fmt::Display; +use std::fs; +use std::path::Path; +use std::sync::Mutex; + +enum Entry { + Step(String), + Call(String), + Note(String), +} + +static LOG: Mutex> = Mutex::new(Vec::new()); + +pub fn reset() { + LOG.lock().unwrap().clear(); +} + +pub fn step(keyword: &str, text: &str) { + LOG.lock().unwrap().push(Entry::Step(format!("{}{}", keyword, text))); +} + +pub fn call(call: String, result: impl Display) { + LOG.lock().unwrap().push(Entry::Call(format!("{call}; // -> {result}"))); +} + +/// Something the client does outside the FFI, e.g. the HTTP request it sends to the mock server. +pub fn note(note: impl Into) { + LOG.lock().unwrap().push(Entry::Note(note.into())); +} + +/// Writes the log as Markdown. Steps that made no FFI calls are kept so the scenario still reads in full. +pub fn write(path: &Path, feature: &str, scenario: &str) -> std::io::Result<()> { + let log = LOG.lock().unwrap(); + let mut out = format!("# {feature}\n\n## {scenario}\n"); + let mut open = false; + for entry in log.iter() { + match entry { + Entry::Step(s) => { + if open { out.push_str("```\n"); open = false; } + out.push_str(&format!("\n**{}**\n", s.trim())); + } + Entry::Call(s) | Entry::Note(s) => { + if !open { out.push_str("\n```c\n"); open = true; } + if let Entry::Note(_) = entry { out.push_str("// "); } + out.push_str(s); + out.push('\n'); + } + } + } + if open { out.push_str("```\n"); } + if let Some(dir) = path.parent() { fs::create_dir_all(dir)?; } + fs::write(path, out) +} diff --git a/compatibility-suite-ffi/tests/consumer.rs b/compatibility-suite-ffi/tests/consumer.rs new file mode 100644 index 000000000..18d2046fd --- /dev/null +++ b/compatibility-suite-ffi/tests/consumer.rs @@ -0,0 +1,670 @@ +//! V1 to V4 HTTP consumer features, driven only through pact_ffi. Mirrors `v1_consumer.rs`, `v2_consumer.rs` and +//! `shared_steps/consumer.rs` in the pact-reference compatibility suite. + +use std::collections::HashMap; +use std::env; +use std::fs; +use std::path::{Path, PathBuf}; + +use anyhow::{anyhow, bail}; +use cucumber::gherkin::Step; +use cucumber::{given, then, when, World}; +use serde_json::Value; + +use pact_ffi_compat::ffi::{self, PactHandle, PactSpecification, PactSpecification_V1, PactSpecification_V2, + PactSpecification_V3, PactSpecification_V4, InteractionHandle}; +use pact_ffi_compat::model::{self, Interaction, FIXTURES}; +use pact_ffi_compat::trace; + +#[derive(Debug, Default)] +struct Response { + status: u16, + headers: Vec<(String, String)>, + body: Vec, +} + +#[derive(Debug, Default, World)] +struct ConsumerWorld { + /// "v1" to "v4", from the feature's directory. + version: String, + scenario_id: String, + interactions: Vec, + pact: Option, + port: Option, + /// Captured when the pact test is done, after which the mock server is gone. + mismatches: Option>, + response: Response, + pact_json: Value, + /// The single interaction the V3/V4 "being defined for a consumer test" scenarios build up. + interaction: Option, +} + +impl ConsumerWorld { + fn spec(&self) -> PactSpecification { + match self.version.as_str() { + "v4" => PactSpecification_V4, + "v3" => PactSpecification_V3, + "v2" => PactSpecification_V2, + _ => PactSpecification_V1, + } + } + + fn consumer(&self) -> String { + format!("{}-compatibility-suite-c", self.version) + } + + fn pact_file(&self) -> PathBuf { + self.pact_dir().join(format!("{}-p.json", self.consumer())) + } + + fn pact_dir(&self) -> PathBuf { + env::current_dir().unwrap().join("target/compatibility-suite").join(&self.version).join(&self.scenario_id) + } + + fn mismatches(&self) -> Vec { + if let Some(m) = &self.mismatches { + return m.clone(); + } + let port = self.port.expect("mock server not started"); + ffi::mock_server_mismatches(port).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default() + } + + fn request_mismatches(&self) -> Vec { + self.mismatches().iter() + .filter(|m| m["type"] == "request-mismatch") + .flat_map(|m| m["mismatches"].as_array().cloned().unwrap_or_default()) + .collect() + } + + fn shutdown(&mut self) { + if let Some(port) = self.port.take() { + ffi::cleanup_mock_server(port); + } + if let Some(pact) = self.pact.take() { + ffi::free_pact_handle(pact); + } + } + + fn interaction(&self, n: usize) -> &Interaction { + &self.interactions[n - 1] + } + + fn pact_interaction(&self, nth: &str) -> anyhow::Result<&Value> { + let i = match nth { "first" => 0, "second" => 1, "third" => 2, _ => bail!("bad ordinal {nth}") }; + self.pact_json["interactions"].get(i).ok_or_else(|| anyhow!("no {nth} interaction in the pact file")) + } +} + +fn traced(step: &Step) { + trace::step(&step.keyword, &step.value); +} + +fn table(step: &Step) -> Vec> { + step.table.as_ref().map(|t| t.rows.clone()).unwrap_or_default() +} + +fn start(world: &mut ConsumerWorld, interactions: &[Interaction]) -> anyhow::Result<()> { + let pact = ffi::new_pact(&world.consumer(), "p"); + ffi::with_specification(pact, world.spec()); + for i in interactions { + model::register(pact, i); + } + world.pact = Some(pact); + let port = ffi::create_mock_server_for_transport(pact, "::1", 0, "http"); + if port < 0 { + bail!("pactffi_create_mock_server_for_transport failed with {port}"); + } + world.port = Some(port); + Ok(()) +} + +async fn send(world: &mut ConsumerWorld, method: &str, path: &str, query: &str, headers: &[(String, String)], + body: Option<&[u8]>) -> anyhow::Result<()> { + let port = world.port.ok_or_else(|| anyhow!("mock server not started"))?; + let mut url = format!("http://[::1]:{port}{path}"); + if !query.is_empty() { + url.push('?'); + url.push_str(query); + } + let mut req = reqwest::Client::new().request(method.parse()?, &url); + for (k, v) in headers { + req = req.header(k, v); + } + if let Some(body) = body { + req = req.body(body.to_vec()); + } + let res = req.send().await?; + let status = res.status().as_u16(); + let headers = res.headers().iter() + .map(|(k, v)| (k.to_string(), String::from_utf8_lossy(v.as_bytes()).into_owned())) + .collect(); + let body = res.bytes().await?.to_vec(); + trace::note(format!("HTTP {method} {url} -> {status}")); + world.response = Response { status, headers, body }; + Ok(()) +} + +#[given("the following HTTP interactions have been defined:")] +fn interactions_defined(world: &mut ConsumerWorld, step: &Step) { + traced(step); + world.interactions = model::setup_common_interactions(&table(step)); +} + +#[when(expr = "the mock server is started with interaction {int}")] +fn started_with_interaction(world: &mut ConsumerWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let i = world.interaction(n).clone(); + start(world, &[i]) +} + +/// Applies a `| method | path | query | headers | body |` changes table. `raw headers` are +/// added on top of `headers` rather than replacing them, to send repeated headers. +fn apply_changes(i: &mut Interaction, rows: &[Vec]) { + let mut raw_headers = vec![]; + for (field, value) in rows[0].iter().zip(&rows[1]) { + match field.as_str() { + "method" => i.method = value.clone(), + "path" => i.path = value.clone(), + "query" => i.query = value.clone(), + "headers" => i.request.headers = model::parse_headers(value), + "body" => model::setup_body(value, &mut i.request), + "raw headers" => raw_headers = model::parse_headers(value), + "matching rules" => i.request.matching_rules = model::matching_rules(value), + _ => {} + } + } + i.request.headers.extend(raw_headers); +} + +#[when(expr = "the mock server is started with interaction {int} but with the following changes:")] +fn started_with_changes(world: &mut ConsumerWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let mut i = world.interaction(n).clone(); + apply_changes(&mut i, &table(step)); + start(world, &[i]) +} + +#[when(expr = "the mock server is started with interactions {string}")] +fn started_with_interactions(world: &mut ConsumerWorld, step: &Step, list: String) -> anyhow::Result<()> { + traced(step); + let numbers = list.split(',').map(|n| n.trim().parse()).collect::, _>>()?; + let interactions: Vec = numbers.iter().map(|n| world.interaction(*n).clone()).collect(); + start(world, &interactions) +} + +#[when(expr = "request {int} is made to the mock server")] +async fn request_made(world: &mut ConsumerWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let i = world.interaction(n).clone(); + send(world, &i.method, &i.path, &i.query, &i.request.headers, i.request.body.as_deref()).await +} + +#[when(expr = "request {int} is made to the mock server with the following changes:")] +async fn request_made_with_changes(world: &mut ConsumerWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let mut i = world.interaction(n).clone(); + apply_changes(&mut i, &table(step)); + send(world, &i.method, &i.path, &i.query, &i.request.headers, i.request.body.as_deref()).await +} + +#[then(expr = "a {int} success response is returned")] +fn success_response(world: &mut ConsumerWorld, step: &Step, status: u16) -> anyhow::Result<()> { + traced(step); + if world.response.status != status { + bail!("Expected a success response of {status} but got {:?}", world.response); + } + Ok(()) +} + +#[then(expr = "a {int} error response is returned")] +fn error_response(world: &mut ConsumerWorld, step: &Step, status: u16) -> anyhow::Result<()> { + traced(step); + if world.response.status != status { + bail!("Expected an error response of {status} but got {:?}", world.response); + } + Ok(()) +} + +#[then(expr = "the payload will contain the {string} JSON document")] +fn payload_json(world: &mut ConsumerWorld, step: &Step, name: String) -> anyhow::Result<()> { + traced(step); + // pactffi_with_body parses JSON bodies (to pull out matchers), so the mock server returns them + // re-serialised. Through the FFI only the JSON value survives, not the fixture's formatting. + let expected = fs::read(format!("{FIXTURES}/{name}.json"))?; + let same = world.response.body == expected + || serde_json::from_slice::(&world.response.body).ok() == serde_json::from_slice::(&expected).ok(); + if !same { + bail!("Expected payload {} but got {}", String::from_utf8_lossy(&expected), + String::from_utf8_lossy(&world.response.body)); + } + Ok(()) +} + +#[then(expr = "the content type will be set as {string}")] +fn content_type_set(world: &mut ConsumerWorld, step: &Step, expected: String) -> anyhow::Result<()> { + traced(step); + match world.response.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case("content-type")) { + Some((_, v)) if *v == expected => Ok(()), + Some((_, v)) => bail!("Expected response content-type of '{expected}' but was '{v}'"), + None => bail!("Response does not contain a content-type header"), + } +} + +#[when("the pact test is done")] +fn pact_test_done(world: &mut ConsumerWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let port = world.port.ok_or_else(|| anyhow!("mock server not started"))?; + let mismatches = world.mismatches(); + ffi::mock_server_matched(port); + if mismatches.is_empty() { + let dir = world.pact_dir(); + fs::create_dir_all(&dir)?; + let rc = ffi::write_pact_file(port, &dir.to_string_lossy(), true); + if rc != 0 { + bail!("pactffi_write_pact_file failed with {rc}"); + } + } + world.mismatches = Some(mismatches); + world.shutdown(); + Ok(()) +} + +#[then(regex = r"^the mock server will write out a Pact file for the interactions? when done$")] +fn pact_written(world: &mut ConsumerWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let file = world.pact_file(); + if !file.exists() { + bail!("No pact file found: {}", file.display()); + } + world.pact_json = serde_json::from_str(&fs::read_to_string(file)?)?; + let expected = if world.version == "v2" { "2.0.0" } else { "1.0.0" }; + let version = &world.pact_json["metadata"]["pactSpecification"]["version"]; + if version != expected { + bail!("Expected a {expected} pact file but metadata.pactSpecification.version was {version}"); + } + Ok(()) +} + +#[then(regex = r"^the mock server will NOT write out a Pact file for the interactions? when done$")] +fn pact_not_written(world: &mut ConsumerWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let file = world.pact_file(); + if file.exists() { + bail!("Expected no pact file, but found {}", file.display()); + } + Ok(()) +} + +#[then("the mock server status will be OK")] +fn status_ok(world: &mut ConsumerWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let m = world.mismatches(); + if !m.is_empty() { + bail!("Mock server has {} mismatches: {}", m.len(), Value::from(m)); + } + Ok(()) +} + +#[then(regex = r"^the mock server status will (?:NOT be OK|be mismatches)$")] +fn status_not_ok(world: &mut ConsumerWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + if world.mismatches().is_empty() { + bail!("Mock server has no mismatches"); + } + Ok(()) +} + +#[then(regex = r"^the pact file will contain \{(\d+)\} interactions?$")] +fn pact_interaction_count(world: &mut ConsumerWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let count = world.pact_json["interactions"].as_array().map(Vec::len).unwrap_or(0); + if count != n { + bail!("Expected the pact file to contain {n} interaction(s), but had {count}"); + } + Ok(()) +} + +#[then(regex = r#"^the \{(first|second|third)\} interaction request will be for a "(\w+)"$"#)] +fn pact_request_method(world: &mut ConsumerWorld, step: &Step, nth: String, method: String) -> anyhow::Result<()> { + traced(step); + let actual = &world.pact_interaction(&nth)?["request"]["method"]; + if !actual.as_str().is_some_and(|m| m.eq_ignore_ascii_case(&method)) { + bail!("Expected request method {method} but was {actual}"); + } + Ok(()) +} + +/// A V1 pact stores the query as a string; later formats use a map of name to values. +fn pact_query(query: &Value) -> HashMap> { + match query { + Value::String(s) => model::query_map(&model::parse_query(s)), + Value::Object(map) => map.iter().map(|(k, v)| { + let values = match v { + Value::Array(a) => a.iter().map(|x| x.as_str().unwrap_or_default().to_string()).collect(), + other => vec![other.as_str().unwrap_or_default().to_string()], + }; + (k.clone(), values) + }).collect(), + _ => HashMap::new(), + } +} + +#[then(regex = r#"^the \{(first|second|third)\} interaction request query parameters will be "(.*)"$"#)] +fn pact_request_query(world: &mut ConsumerWorld, step: &Step, nth: String, query: String) -> anyhow::Result<()> { + traced(step); + let actual = &world.pact_interaction(&nth)?["request"]["query"]; + if pact_query(actual) != model::query_map(&model::parse_query(&query)) { + bail!("Expected query {query} but was {actual}"); + } + Ok(()) +} + +fn pact_header<'a>(part: &'a Value, name: &str) -> Option<&'a str> { + part["headers"].as_object()?.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).and_then(|(_, v)| v.as_str()) +} + +#[then(regex = r#"^the \{(first|second|third)\} interaction request will contain the header "(.*)" with value "(.*)"$"#)] +fn pact_request_header(world: &mut ConsumerWorld, step: &Step, nth: String, name: String, value: String) + -> anyhow::Result<()> { + traced(step); + let request = &world.pact_interaction(&nth)?["request"]; + match pact_header(request, &name) { + Some(v) if v == value => Ok(()), + other => bail!("Expected header {name}: {value} but was {other:?}"), + } +} + +#[then(regex = r#"^the \{(first|second|third)\} interaction request content type will be "(.*)"$"#)] +fn pact_request_content_type(world: &mut ConsumerWorld, step: &Step, nth: String, ct: String) -> anyhow::Result<()> { + traced(step); + let request = &world.pact_interaction(&nth)?["request"]; + let actual = pact_header(request, "content-type").or_else(|| match request["body"] { + Value::Object(_) | Value::Array(_) => Some("application/json"), + _ => None, + }); + if actual != Some(ct.as_str()) { + bail!("Expected request content type {ct} but was {actual:?}"); + } + Ok(()) +} + +fn compare_body(body: &Value, fixture: &str) -> anyhow::Result<()> { + let path = Path::new(FIXTURES).join(fixture); + if fixture.ends_with(".json") { + let expected: Value = serde_json::from_str(&fs::read_to_string(&path)?)?; + if *body != expected { + bail!("Expected body {expected} but was {body}"); + } + } else { + let expected = fs::read_to_string(&path)?; + if body.as_str() != Some(expected.as_str()) { + bail!("Expected body {expected:?} but was {body}"); + } + } + Ok(()) +} + +#[then(regex = r#"^the \{(first|second|third)\} interaction (request|response) will contain the "(.*)" document$"#)] +fn pact_body(world: &mut ConsumerWorld, step: &Step, nth: String, part: String, fixture: String) + -> anyhow::Result<()> { + traced(step); + compare_body(&world.pact_interaction(&nth)?[part.as_str()]["body"], &fixture) +} + +fn mismatch_matches(m: &Value, kind: &str, error: &str) -> bool { + let t = m["type"].as_str().unwrap_or_default(); + let correct_type = if t == "BodyTypeMismatch" { kind == "body-content-type" } else { t.to_lowercase().starts_with(kind) }; + correct_type && m["mismatch"].as_str().is_some_and(|d| d.contains(error)) +} + +#[then(expr = "the mismatches will contain a {string} mismatch with error {string}")] +fn mismatch_with_error(world: &mut ConsumerWorld, step: &Step, kind: String, error: String) -> anyhow::Result<()> { + traced(step); + let all = world.request_mismatches(); + if !all.iter().any(|m| mismatch_matches(m, &kind, &error)) { + bail!("Did not find a {kind} mismatch with error {error:?} in {}", Value::from(all)); + } + Ok(()) +} + +#[then(expr = "the mismatches will contain a {string} mismatch with path {string} with error {string}")] +fn mismatch_with_path(world: &mut ConsumerWorld, step: &Step, kind: String, path: String, error: String) + -> anyhow::Result<()> { + traced(step); + let all = world.request_mismatches(); + let found = all.iter().any(|m| { + let actual_path = match m["type"].as_str().unwrap_or_default() { + "QueryMismatch" => &m["parameter"], + "HeaderMismatch" => &m["key"], + "BodyMismatch" => &m["path"], + _ => &Value::Null, + }; + mismatch_matches(m, &kind, &error) && actual_path.as_str() == Some(path.as_str()) + }); + if !found { + bail!("Did not find a {kind} mismatch at {path} with error {error:?} in {}", Value::from(all)); + } + Ok(()) +} + +#[then(regex = r#"^the mock server status will be an unexpected "(\w+)" request received error for interaction \{(\d+)\}$"#)] +fn unexpected_request_for_interaction(world: &mut ConsumerWorld, step: &Step, method: String, n: usize) + -> anyhow::Result<()> { + traced(step); + let i = world.interaction(n).clone(); + let expected_query = model::query_map(&model::parse_query(&i.query)); + let all = world.mismatches(); + let found = all.iter().any(|m| { + m["type"] == "request-not-found" && m["method"] == method.as_str() && m["path"] == i.path.as_str() + && pact_query(&m["request"]["query"]) == expected_query + }); + if !found { + bail!("Did not find an unexpected {method} request for interaction {n} in {}", Value::from(all)); + } + Ok(()) +} + +#[then(regex = r#"^the mock server status will be an unexpected "(\w+)" request received error for path "(.*)"$"#)] +fn unexpected_request_for_path(world: &mut ConsumerWorld, step: &Step, method: String, path: String) + -> anyhow::Result<()> { + traced(step); + let all = world.mismatches(); + if !all.iter().any(|m| m["type"] == "request-not-found" && m["method"] == method.as_str() && m["path"] == path.as_str()) { + bail!("Did not find an unexpected {method} request for {path} in {}", Value::from(all)); + } + Ok(()) +} + +#[then(regex = r"^the mock server status will be an expected but not received error for interaction \{(\d+)\}$")] +fn missing_request(world: &mut ConsumerWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let i = world.interaction(n).clone(); + let all = world.mismatches(); + if !all.iter().any(|m| m["type"] == "missing-request" && m["method"] == i.method.as_str() && m["path"] == i.path.as_str()) { + bail!("Did not find a missing request for interaction {n} in {}", Value::from(all)); + } + Ok(()) +} + +// V3 and V4: interactions defined without a mock server, then written straight from the pact handle. + +#[given(regex = r"^an (integration|HTTP interaction) is being defined for a consumer test$")] +fn interaction_being_defined(world: &mut ConsumerWorld, step: &Step, _kind: String) { + traced(step); + let pact = ffi::new_pact(&world.consumer(), "p"); + ffi::with_specification(pact, world.spec()); + let i = ffi::new_interaction(pact, "interaction for a consumer test"); + ffi::with_request(i, "GET", "/"); + world.pact = Some(pact); + world.interaction = Some(i); +} + +fn defined(world: &ConsumerWorld) -> anyhow::Result { + world.interaction.ok_or_else(|| anyhow!("no interaction is being defined")) +} + +#[given(expr = "a provider state {string} is specified")] +fn provider_state(world: &mut ConsumerWorld, step: &Step, state: String) -> anyhow::Result<()> { + traced(step); + if !ffi::given(defined(world)?, &state) { + bail!("pactffi_given failed"); + } + Ok(()) +} + +/// The table's first row names the parameters; the second holds their values as JSON. +#[given(expr = "a provider state {string} is specified with the following data:")] +fn provider_state_with_data(world: &mut ConsumerWorld, step: &Step, state: String) -> anyhow::Result<()> { + traced(step); + let rows = table(step); + let params: serde_json::Map = rows[0].iter().zip(&rows[1]) + .map(|(k, v)| Ok((k.clone(), serde_json::from_str(v)?))) + .collect::>()?; + let rc = ffi::given_with_params(defined(world)?, &state, &Value::Object(params).to_string()); + if rc != 0 { + bail!("pactffi_given_with_params failed with {rc}"); + } + Ok(()) +} + +#[given(expr = "a key of {string} is specified for the HTTP interaction")] +fn key_specified(world: &mut ConsumerWorld, step: &Step, key: String) -> anyhow::Result<()> { + traced(step); + if !ffi::set_key(defined(world)?, &key) { + bail!("pactffi_set_key failed"); + } + Ok(()) +} + +#[given("the HTTP interaction is marked as pending")] +fn marked_pending(world: &mut ConsumerWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + if !ffi::set_pending(defined(world)?, true) { + bail!("pactffi_set_pending failed"); + } + Ok(()) +} + +#[given(expr = "a comment {string} is added to the HTTP interaction")] +fn comment_added(world: &mut ConsumerWorld, step: &Step, comment: String) -> anyhow::Result<()> { + traced(step); + if !ffi::add_text_comment(defined(world)?, &comment) { + bail!("pactffi_add_text_comment failed"); + } + Ok(()) +} + +#[when("the Pact file for the test is generated")] +fn pact_generated(world: &mut ConsumerWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let pact = world.pact.ok_or_else(|| anyhow!("no pact is being defined"))?; + let dir = world.pact_dir(); + fs::create_dir_all(&dir)?; + let rc = ffi::pact_handle_write_file(pact, &dir.to_string_lossy(), true); + if rc != 0 { + bail!("pactffi_pact_handle_write_file failed with {rc}"); + } + world.pact_json = serde_json::from_str(&fs::read_to_string(world.pact_file())?)?; + Ok(()) +} + +fn provider_states(world: &ConsumerWorld) -> Vec { + world.pact_json["interactions"][0]["providerStates"].as_array().cloned().unwrap_or_default() +} + +#[then(regex = r"^the interaction in the Pact file will contain (\d+) provider states?$")] +fn provider_state_count(world: &mut ConsumerWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let states = provider_states(world); + if states.len() != n { + bail!("Expected {n} provider states but found {}", Value::from(states)); + } + Ok(()) +} + +#[then(expr = "the interaction in the Pact file will contain provider state {string}")] +fn provider_state_present(world: &mut ConsumerWorld, step: &Step, state: String) -> anyhow::Result<()> { + traced(step); + let states = provider_states(world); + if !states.iter().any(|s| s["name"] == state.as_str()) { + bail!("No provider state '{state}' in {}", Value::from(states)); + } + Ok(()) +} + +#[then(expr = "the provider state {string} in the Pact file will contain the following parameters:")] +fn provider_state_params(world: &mut ConsumerWorld, step: &Step, state: String) -> anyhow::Result<()> { + traced(step); + let expected: Value = serde_json::from_str(&table(step)[1][0])?; + let states = provider_states(world); + let s = states.iter().find(|s| s["name"] == state.as_str()) + .ok_or_else(|| anyhow!("No provider state '{state}' in {}", Value::from(states.clone())))?; + if s["params"] != expected { + bail!("Expected parameters {expected} but were {}", s["params"]); + } + Ok(()) +} + +#[then(expr = "the first interaction in the Pact file will have a type of {string}")] +fn interaction_type(world: &mut ConsumerWorld, step: &Step, expected: String) -> anyhow::Result<()> { + traced(step); + let actual = &world.pact_interaction("first")?["type"]; + if actual != expected.as_str() { + bail!("Expected type '{expected}' but was {actual}"); + } + Ok(()) +} + +/// The expected value is JSON in single quotes. +#[then(regex = r#"^the first interaction in the Pact file will have "([^"]+)" = '(.*)'$"#)] +fn interaction_attribute(world: &mut ConsumerWorld, step: &Step, name: String, value: String) -> anyhow::Result<()> { + traced(step); + let expected: Value = serde_json::from_str(&value)?; + let actual = &world.pact_interaction("first")?[name.as_str()]; + if *actual != expected { + bail!("Expected {name} = {expected} but was {actual}"); + } + Ok(()) +} + +fn trace_path(feature: &str, scenario: &str) -> PathBuf { + let dir = env::var("FFI_TRACE_DIR").unwrap_or_else(|_| "target/ffi-trace".into()); + let safe = |s: &str| s.replace(['/', '\\', ':'], "_"); + PathBuf::from(dir).join(safe(feature)).join(format!("{}.md", safe(scenario))) +} + +/// `features/V2/http_consumer.feature` -> "v2". +fn feature_version(feature: &cucumber::gherkin::Feature) -> String { + feature.path.as_ref().and_then(|p| p.parent()?.file_name()?.to_str().map(str::to_lowercase)).unwrap_or_default() +} + +#[tokio::main] +async fn main() { + let lib = model::ffi_lib(); + ffi::load(&lib).unwrap_or_else(|e| panic!("could not load {lib}: {e}")); + + ConsumerWorld::cucumber() + .max_concurrent_scenarios(1) + .fail_on_skipped() + .before(|feature, _rule, scenario, world| Box::pin(async move { + trace::reset(); + world.version = feature_version(feature); + world.scenario_id = scenario.name.clone(); + let _ = fs::remove_dir_all(world.pact_dir()); + })) + .after(|feature, _rule, scenario, _ev, world| Box::pin(async move { + if let Some(world) = world { + world.shutdown(); + } + let path = trace_path(&format!("{} {}", feature_version(feature).to_uppercase(), feature.name), &scenario.name); + if let Err(e) = trace::write(&path, &feature.name, &scenario.name) { + eprintln!("could not write trace {}: {e}", path.display()); + } + })) + .filter_run_and_exit(model::FEATURES, |feature, _rule, scenario| { + matches!(feature_version(feature).as_str(), "v1" | "v2" | "v3" | "v4") + && feature.path.as_ref().is_some_and(|p| p.ends_with("http_consumer.feature")) + && feature.tags.iter().any(|t| t == "consumer") && !scenario.tags.iter().any(|t| t == "wip") + }) + .await; +} diff --git a/compatibility-suite-ffi/tests/generators.rs b/compatibility-suite-ffi/tests/generators.rs new file mode 100644 index 000000000..318e791f5 --- /dev/null +++ b/compatibility-suite-ffi/tests/generators.rs @@ -0,0 +1,447 @@ +//! V3 generators, V3 HTTP generators and V4 generators features, driven only through pact_ffi. Mirrors +//! `v3_steps/generators.rs` and `v4_steps/generators.rs` in the pact-reference compatibility suite. +//! +//! pact_ffi has no call that generates a request or response. A client sees generated values by running them +//! through the parts of the library that apply generators: a request is prepared by verifying a pact against a +//! provider that records what it receives (provider mode, with a state change server for a provider state +//! context), and a response by sending a request to a mock server (consumer mode). The mock server URL generator +//! only runs with a mock server context in consumer mode, which an HTTP client can't supply, so that scenario +//! walks a V4 message's body generators with `pactffi_generator_generate_string`. + +use std::env; +use std::fs; +use std::path::PathBuf; +use std::sync::Arc; + +use anyhow::{anyhow, bail}; +use cucumber::gherkin::Step; +use cucumber::{given, then, when, World}; +use regex::Regex; +use serde_json::Value; + +use pact_ffi_compat::ffi::{self, InteractionPart_Request, InteractionPart_Response, PactSpecification, + PactSpecification_V3, PactSpecification_V4}; +use pact_ffi_compat::model::{self, Part, FIXTURES}; +use pact_ffi_compat::server::{Request as ServerRequest, Response as ServerResponse, Server}; +use pact_ffi_compat::trace; + +#[derive(Debug, Clone, Default)] +struct Generated { + status: u16, + /// Path and query as sent. + path: String, + headers: Vec<(String, String)>, + body: Vec, +} + +impl Generated { + fn header(&self, name: &str) -> Option<&str> { + self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()) + } +} + +#[derive(Debug, Default, World)] +struct GeneratorsWorld { + /// "v3" or "v4", from the feature's directory. + version: String, + scenario_id: String, + request: Part, + request_generators: Option, + response: Part, + response_generators: Option, + mode: String, + generated_request: Option, + generated_response: Option, +} + +impl GeneratorsWorld { + fn spec(&self) -> PactSpecification { + if self.version == "v4" { PactSpecification_V4 } else { PactSpecification_V3 } + } + + fn consumer(&self) -> String { + format!("{}-compatibility-suite-c", self.version) + } + + fn pact_dir(&self) -> PathBuf { + env::current_dir().unwrap().join("target/compatibility-suite").join(&self.version).join(&self.scenario_id) + } + + /// The body that was generated, from whichever side was prepared. + fn generated_body(&self) -> anyhow::Result { + let g = self.generated_request.as_ref().or(self.generated_response.as_ref()) + .ok_or_else(|| anyhow!("nothing was prepared"))?; + serde_json::from_slice(&g.body).map_err(|e| anyhow!("generated body is not JSON ({e}): {:?}", + String::from_utf8_lossy(&g.body))) + } + + fn original_body(&self) -> Value { + let part = if self.generated_request.is_some() { &self.request } else { &self.response }; + part.body.as_ref().and_then(|b| serde_json::from_slice(b).ok()).unwrap_or(Value::Null) + } +} + +fn traced(step: &Step) { + trace::step(&step.keyword, &step.value); +} + +fn table(step: &Step) -> Vec> { + step.table.as_ref().map(|t| t.rows.clone()).unwrap_or_default() +} + +/// A `| body | generators |` table: the part's body, and the generators as JSON text. +fn configure(step: &Step) -> (Part, Option) { + let rows = table(step); + let mut part = Part::default(); + let mut generators = None; + for (field, value) in rows[0].iter().zip(&rows[1]) { + match field.as_str() { + "body" => model::setup_body(value, &mut part), + "generators" => { + let json = match value.strip_prefix("JSON:") { + Some(json) => json.trim().to_string(), + None => fs::read_to_string(format!("{FIXTURES}/{value}")) + .unwrap_or_else(|e| panic!("fixture {value}: {e}")), + }; + generators = Some(json); + } + _ => {} + } + } + (part, generators) +} + +#[given("a request configured with the following generators:")] +fn request_generators(world: &mut GeneratorsWorld, step: &Step) { + traced(step); + let (part, generators) = configure(step); + world.request = part; + world.request_generators = generators; +} + +#[given("a response configured with the following generators:")] +fn response_generators(world: &mut GeneratorsWorld, step: &Step) { + traced(step); + let (part, generators) = configure(step); + world.response = part; + world.response_generators = generators; +} + +#[given(expr = "the generator test mode is set as {string}")] +fn test_mode(world: &mut GeneratorsWorld, step: &Step, mode: String) { + traced(step); + world.mode = mode; +} + +/// Verifies a pact holding the configured request against a provider that records it, and returns the first +/// request the provider received. With a provider state context, a state change server returns it as JSON, which +/// the verifier adds to the generator context. +async fn prepare_request(world: &GeneratorsWorld, state: Option) -> anyhow::Result { + let dir = world.pact_dir(); + let pact = ffi::new_pact(&world.consumer(), "p"); + ffi::with_specification(pact, world.spec()); + let i = ffi::new_interaction(pact, "a request with generators"); + if state.is_some() { + ffi::given(i, "a state"); + } + ffi::with_request(i, "GET", "/path/one"); + model::register_part(i, InteractionPart_Request, &world.request); + if let Some(generators) = &world.request_generators { + ffi::with_generators(i, InteractionPart_Request, generators); + } + ffi::response_status(i, 200); + fs::create_dir_all(&dir)?; + let rc = ffi::pact_handle_write_file(pact, dir.to_str().unwrap(), true); + ffi::free_pact_handle(pact); + if rc != 0 { + bail!("pactffi_pact_handle_write_file failed with {rc}"); + } + let file = dir.join(format!("{}-p.json", world.consumer())); + + let provider = Server::start(Arc::new(|_req: &ServerRequest, _port| ServerResponse { status: 200, + ..ServerResponse::default() })).await?; + let state_server = match &state { + Some(context) => { + let context = context.clone(); + Some(Server::start(Arc::new(move |_req: &ServerRequest, _port| ServerResponse::json(200, &context))).await?) + } + None => None, + }; + let v = ffi::verifier_new_for_application("pact-ffi-compat", env!("CARGO_PKG_VERSION")); + ffi::verifier_set_provider_info(v, "p", "http", "127.0.0.1", provider.port, "/"); + if let Some(s) = &state_server { + ffi::verifier_set_provider_state(v, &s.url(), false, true); + } + ffi::verifier_add_file_source(v, file.to_str().unwrap()); + tokio::task::spawn_blocking(move || ffi::verifier_execute(v)).await?; + ffi::verifier_shutdown(v); + + let req = provider.requests().into_iter().next().ok_or_else(|| anyhow!("the provider received no request"))?; + trace::note(format!("provider received {} {}", req.method, req.path)); + Ok(Generated { status: 0, path: req.path.clone(), headers: req.headers.clone(), body: req.body.clone() }) +} + +/// Builds a V4 message whose contents are the configured request body, runs its body generators with `context`, +/// and writes each generated value into the body. +fn prepare_message_body(world: &GeneratorsWorld, context: &Value) -> anyhow::Result { + let pact = ffi::new_pact(&world.consumer(), "p"); + ffi::with_specification(pact, PactSpecification_V4); + let i = ffi::new_message_interaction(pact, "a message with generators"); + let ct = world.request.header("content-type").unwrap_or("application/json").to_string(); + let body = world.request.body.clone().unwrap_or_default(); + ffi::with_body(i, InteractionPart_Request, &ct, std::str::from_utf8(&body)?); + if let Some(generators) = &world.request_generators { + ffi::with_generators(i, InteractionPart_Request, generators); + } + let generated = ffi::async_body_generators_with_context(pact, &context.to_string()); + ffi::free_pact_handle(pact); + + let mut json: Value = serde_json::from_slice(&body)?; + for (path, value) in generated { + let value = value.ok_or_else(|| anyhow!("no value generated for {path}"))?; + let pointer = path.strip_prefix('$').unwrap_or(&path).replace('.', "/"); + let slot = json.pointer_mut(&pointer).ok_or_else(|| anyhow!("{path} is not in the body"))?; + *slot = Value::String(value); + } + Ok(Generated { body: serde_json::to_vec(&json)?, ..Generated::default() }) +} + +#[when("the request is prepared for use")] +async fn request_prepared(world: &mut GeneratorsWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + world.generated_request = Some(prepare_request(world, None).await?); + Ok(()) +} + +#[when(expr = "the request is prepared for use with a {string} context:")] +async fn request_prepared_with_context(world: &mut GeneratorsWorld, step: &Step, kind: String) + -> anyhow::Result<()> { + traced(step); + let context: Value = serde_json::from_str(&table(step)[0][0])?; + let generated = match kind.as_str() { + "providerState" => prepare_request(world, Some(context)).await?, + "mockServer" => { + let href = context["href"].clone(); + prepare_message_body(world, &serde_json::json!({ "mockServer": { "url": href, "href": href } }))? + } + other => bail!("unknown context {other}"), + }; + world.generated_request = Some(generated); + Ok(()) +} + +#[when("the response is prepared for use")] +async fn response_prepared(world: &mut GeneratorsWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let pact = ffi::new_pact(&world.consumer(), "p"); + ffi::with_specification(pact, world.spec()); + let i = ffi::new_interaction(pact, "a response with generators"); + ffi::with_request(i, "GET", "/path/one"); + ffi::response_status(i, 200); + model::register_part(i, InteractionPart_Response, &world.response); + if let Some(generators) = &world.response_generators { + ffi::with_generators(i, InteractionPart_Response, generators); + } + let port = ffi::create_mock_server_for_transport(pact, "127.0.0.1", 0, "http"); + if port < 0 { + ffi::free_pact_handle(pact); + bail!("pactffi_create_mock_server_for_transport failed with {port}"); + } + let url = format!("http://127.0.0.1:{port}/path/one"); + let sent = reqwest::get(&url).await; + ffi::cleanup_mock_server(port); + ffi::free_pact_handle(pact); + let res = sent?; + let status = res.status().as_u16(); + trace::note(format!("HTTP GET {url} -> {status}")); + let headers = res.headers().iter() + .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or_default().to_string())).collect(); + let body = res.bytes().await?.to_vec(); + world.generated_response = Some(Generated { status, path: String::new(), headers, body }); + Ok(()) +} + +fn json_to_string(v: &Value) -> String { + match v { + Value::String(s) => s.clone(), + other => other.to_string(), + } +} + +/// Body path `$.one` -> the value at `/one`. +fn body_value<'a>(body: &'a Value, path: &str) -> anyhow::Result<&'a Value> { + let pointer = path.strip_prefix('$').unwrap_or(path).replace('.', "/"); + body.pointer(&pointer).ok_or_else(|| anyhow!("{path} is not in the body {body}")) +} + +fn assert_value_type(kind: &str, v: &Value) -> anyhow::Result<()> { + let s = json_to_string(v); + let pattern = match kind { + "integer" => r"^-?\d+$", + "decimal number" => r"^-?\d+\.\d+$", + "hexadecimal number" => r"^[a-fA-F0-9]+$", + "random string" | "string from the regex" if !v.is_string() => bail!("expected a string, got {v}"), + "random string" => return Ok(()), + "string from the regex" => r"^\d{1,8}$", + "date" => r"^\d{4}-\d{2}-\d{2}$", + "time" => r"^\d{2}:\d{2}:\d{2}$", + "date-time" => r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?", + "UUID" | "simple UUID" | "lower-case-hyphenated UUID" | "upper-case-hyphenated UUID" | "URN UUID" => + r"^(urn:uuid:)?[a-fA-F0-9]{8}-?[a-fA-F0-9]{4}-?[a-fA-F0-9]{4}-?[a-fA-F0-9]{4}-?[a-fA-F0-9]{12}$", + "boolean" => r"^(true|false)$", + other => bail!("unknown value type {other}"), + }; + if !Regex::new(pattern)?.is_match(&s) { + bail!("expected a(n) {kind}, got {v}"); + } + Ok(()) +} + +#[then(expr = "the body value for {string} will have been replaced with a(n) {string}")] +fn body_replaced_with_type(world: &mut GeneratorsWorld, step: &Step, path: String, kind: String) + -> anyhow::Result<()> { + traced(step); + let body = world.generated_body()?; + let original = world.original_body(); + let value = body_value(&body, &path)?; + if Some(value) == body_value(&original, &path).ok() { + bail!("{path} was not replaced: {value}"); + } + assert_value_type(&kind, value) +} + +#[then(expr = "the body value for {string} will have been replaced with {string}")] +fn body_replaced_with_value(world: &mut GeneratorsWorld, step: &Step, path: String, expected: String) + -> anyhow::Result<()> { + traced(step); + let body = world.generated_body()?; + let original = world.original_body(); + let value = body_value(&body, &path)?; + if Some(value) == body_value(&original, &path).ok() { + bail!("{path} was not replaced: {value}"); + } + if json_to_string(value) != expected { + bail!("expected {path} to be {expected:?}, got {value}"); + } + Ok(()) +} + +/// `header[X-TEST]` -> ("header", "X-TEST"); `path` -> ("path", ""). +fn field(name: &str) -> (String, String) { + let key = Regex::new(r"\[(.*)]").unwrap(); + match key.captures(name) { + Some(c) => (name[..c.get(0).unwrap().start()].to_string(), c[1].to_string()), + None => (name.to_string(), String::new()), + } +} + +fn request_field(g: &Generated, name: &str) -> anyhow::Result { + let (f, key) = field(name); + match f.as_str() { + "path" => Ok(g.path.split('?').next().unwrap_or_default().to_string()), + "header" => g.header(&key).map(str::to_string).ok_or_else(|| anyhow!("no {key} header in {:?}", g.headers)), + "queryParameter" => { + let query = g.path.split_once('?').map(|(_, q)| q).unwrap_or_default(); + model::parse_query(query).into_iter().find(|(k, _)| *k == key).map(|(_, v)| v) + .ok_or_else(|| anyhow!("no {key} query parameter in {:?}", g.path)) + } + other => bail!("unknown request field {other}"), + } +} + +fn response_field(g: &Generated, name: &str) -> anyhow::Result { + let (f, key) = field(name); + match f.as_str() { + "status" => Ok(g.status.to_string()), + "header" => g.header(&key).map(str::to_string).ok_or_else(|| anyhow!("no {key} header in {:?}", g.headers)), + other => bail!("unknown response field {other}"), + } +} + +#[then(expr = "the request {string} will be set as {string}")] +fn request_set_as(world: &mut GeneratorsWorld, step: &Step, name: String, expected: String) -> anyhow::Result<()> { + traced(step); + let g = world.generated_request.as_ref().ok_or_else(|| anyhow!("the request was not prepared"))?; + let actual = request_field(g, &name)?; + if actual != expected { + bail!("expected request {name} to be {expected:?}, got {actual:?}"); + } + Ok(()) +} + +#[then(expr = "the request {string} will match {string}")] +fn request_matches(world: &mut GeneratorsWorld, step: &Step, name: String, pattern: String) -> anyhow::Result<()> { + traced(step); + let g = world.generated_request.as_ref().ok_or_else(|| anyhow!("the request was not prepared"))?; + let actual = request_field(g, &name)?; + if !Regex::new(&format!("^{pattern}$"))?.is_match(&actual) { + bail!("expected request {name} to match {pattern:?}, got {actual:?}"); + } + Ok(()) +} + +#[then(expr = "the response {string} will not be {string}")] +fn response_not(world: &mut GeneratorsWorld, step: &Step, name: String, value: String) -> anyhow::Result<()> { + traced(step); + let g = world.generated_response.as_ref().ok_or_else(|| anyhow!("the response was not prepared"))?; + let actual = response_field(g, &name)?; + if actual == value { + bail!("expected response {name} not to be {value:?}"); + } + Ok(()) +} + +#[then(expr = "the response {string} will match {string}")] +fn response_matches(world: &mut GeneratorsWorld, step: &Step, name: String, pattern: String) -> anyhow::Result<()> { + traced(step); + let g = world.generated_response.as_ref().ok_or_else(|| anyhow!("the response was not prepared"))?; + let actual = response_field(g, &name)?; + if !Regex::new(&format!("^{pattern}$"))?.is_match(&actual) { + bail!("expected response {name} to match {pattern:?}, got {actual:?}"); + } + Ok(()) +} + +fn trace_path(feature: &str, scenario: &str) -> PathBuf { + let dir = env::var("FFI_TRACE_DIR").unwrap_or_else(|_| "target/ffi-trace".into()); + let safe = |s: &str| s.replace(['/', '\\', ':'], "_"); + PathBuf::from(dir).join(safe(feature)).join(format!("{}.md", safe(scenario))) +} + +/// `features/V3/generators.feature` -> "v3". +fn feature_version(feature: &cucumber::gherkin::Feature) -> String { + feature.path.as_ref().and_then(|p| p.parent()?.file_name()?.to_str().map(str::to_lowercase)).unwrap_or_default() +} + +fn feature_file(feature: &cucumber::gherkin::Feature) -> String { + feature.path.as_ref().and_then(|p| p.file_stem()?.to_str().map(str::to_string)).unwrap_or_default() +} + +#[tokio::main] +async fn main() { + let lib = model::ffi_lib(); + ffi::load(&lib).unwrap_or_else(|e| panic!("could not load {lib}: {e}")); + + GeneratorsWorld::cucumber() + .max_concurrent_scenarios(1) + .fail_on_skipped() + .before(|feature, _rule, scenario, world| Box::pin(async move { + trace::reset(); + world.version = feature_version(feature); + world.scenario_id = scenario.name.clone(); + let _ = fs::remove_dir_all(world.pact_dir()); + })) + .after(|feature, _rule, scenario, _ev, _world| Box::pin(async move { + let path = trace_path(&format!("{} {}", feature_version(feature).to_uppercase(), feature.name), &scenario.name); + if let Err(e) = trace::write(&path, &feature.name, &scenario.name) { + eprintln!("could not write trace {}: {e}", path.display()); + } + })) + .filter_run_and_exit(model::FEATURES, |feature, _rule, scenario| { + let v = feature_version(feature); + let f = feature_file(feature); + ((v == "v3" && (f == "generators" || f == "http_generators")) || (v == "v4" && f == "generators")) + && !scenario.tags.iter().any(|t| t == "wip") + }) + .await; +} diff --git a/compatibility-suite-ffi/tests/matching.rs b/compatibility-suite-ffi/tests/matching.rs new file mode 100644 index 000000000..0a6f218d3 --- /dev/null +++ b/compatibility-suite-ffi/tests/matching.rs @@ -0,0 +1,375 @@ +//! V3 HTTP matching and V3/V4 matching rules features, driven only through pact_ffi. Mirrors `v3_steps/http_matching.rs` +//! and `v4_steps/http_matching.rs` in the pact-reference compatibility suite. +//! +//! pact_ffi has no call that compares a request with an expected one. A client gets a comparison by starting a mock +//! server with the expected request and sending it the received one; the mismatches come back from +//! `pactffi_mock_server_mismatches`. Responses are compared by verifying a pact against a provider that returns the +//! received response, and reading `pactffi_verifier_json`. + +use std::env; +use std::fs; +use std::path::PathBuf; +use std::sync::Arc; + +use anyhow::{anyhow, bail}; +use cucumber::gherkin::Step; +use cucumber::{given, then, when, World}; +use regex::Regex; +use serde_json::Value; + +use pact_ffi_compat::ffi::{self, InteractionPart_Response, PactSpecification, + PactSpecification_V3, PactSpecification_V4}; +use pact_ffi_compat::model::{self, Interaction, Part}; +use pact_ffi_compat::server::{Request as ServerRequest, Response as ServerResponse, Server}; +use pact_ffi_compat::trace; + +#[derive(Debug, Clone, Default)] +struct Received { + query: String, + part: Part, +} + +#[derive(Debug, Default, World)] +struct MatchingWorld { + /// "v3" or "v4", from the feature's directory. + version: String, + scenario_id: String, + expected: Interaction, + received: Vec, + /// One list of request mismatches per received request. + results: Vec>, + expected_status: u16, + response_rules: Option, + received_status: u16, + response_mismatches: Vec, +} + +impl MatchingWorld { + fn spec(&self) -> PactSpecification { + if self.version == "v4" { PactSpecification_V4 } else { PactSpecification_V3 } + } + + fn consumer(&self) -> String { + format!("{}-compatibility-suite-c", self.version) + } + + fn pact_dir(&self) -> PathBuf { + env::current_dir().unwrap().join("target/compatibility-suite").join(&self.version).join(&self.scenario_id) + } +} + +fn traced(step: &Step) { + trace::step(&step.keyword, &step.value); +} + +fn table(step: &Step) -> Vec> { + step.table.as_ref().map(|t| t.rows.clone()).unwrap_or_default() +} + +fn expected_request() -> Interaction { + Interaction { description: "expected request".into(), method: "GET".into(), path: "/".into(), status: 200, + ..Interaction::default() } +} + +/// Fills `part` and `query` from one row of a `| body | content type | query | headers | ... |` table. +fn apply_row(fields: &[String], values: &[String], part: &mut Part, query: &mut String) { + let get = |name: &str| fields.iter().position(|f| f == name).map(|n| values[n].as_str()); + if let Some(headers) = get("headers") { + if !headers.is_empty() { + part.headers = model::parse_headers(headers); + } + } + if let Some(body) = get("body") { + model::setup_body_as(body, part, get("content type").filter(|ct| !ct.is_empty())); + } + if let Some(q) = get("query") { + *query = q.to_string(); + } + if let Some(rules) = get("matching rules") { + part.matching_rules = model::matching_rules(rules); + } +} + +#[given(expr = "an expected request with a(n) {string} header of {string}")] +fn expected_header(world: &mut MatchingWorld, step: &Step, name: String, value: String) { + traced(step); + world.expected.request.set_header(&name, &value); +} + +#[given(expr = "a request is received with a(n) {string} header of {string}")] +fn received_header(world: &mut MatchingWorld, step: &Step, name: String, value: String) { + traced(step); + let mut part = Part::default(); + part.set_header(&name, &value); + world.received.push(Received { query: String::new(), part }); +} + +#[given("an expected request configured with the following:")] +fn expected_configured(world: &mut MatchingWorld, step: &Step) { + traced(step); + let rows = table(step); + let mut i = expected_request(); + apply_row(&rows[0], &rows[1], &mut i.request, &mut i.query); + world.expected = i; +} + +#[given("a request is received with the following:")] +fn received_configured(world: &mut MatchingWorld, step: &Step) { + traced(step); + let rows = table(step); + let mut r = Received::default(); + apply_row(&rows[0], &rows[1], &mut r.part, &mut r.query); + world.received.push(r); +} + +#[given("the following requests are received:")] +fn received_many(world: &mut MatchingWorld, step: &Step) { + traced(step); + let rows = table(step); + let fields: Vec = rows[0].iter().filter(|f| *f != "desc").cloned().collect(); + for row in &rows[1..] { + let values: Vec = rows[0].iter().zip(row).filter(|(f, _)| *f != "desc").map(|(_, v)| v.clone()).collect(); + let mut r = Received::default(); + apply_row(&fields, &values, &mut r.part, &mut r.query); + world.received.push(r); + } +} + +/// Starts a mock server holding only the expected request, sends it `received`, and returns its request mismatches. +async fn compare(world: &MatchingWorld, received: &Received) -> anyhow::Result> { + let pact = ffi::new_pact(&world.consumer(), "p"); + ffi::with_specification(pact, world.spec()); + model::register(pact, &world.expected); + let port = ffi::create_mock_server_for_transport(pact, "::1", 0, "http"); + if port < 0 { + ffi::free_pact_handle(pact); + bail!("pactffi_create_mock_server_for_transport failed with {port}"); + } + let mut url = format!("http://[::1]:{port}/"); + if !received.query.is_empty() { + url.push('?'); + url.push_str(&received.query); + } + let mut req = reqwest::Client::new().get(&url); + for (k, v) in &received.part.headers { + req = req.header(k, v); + } + if let Some(body) = &received.part.body { + req = req.body(body.clone()); + } + let sent = req.send().await; + let mismatches: Vec = ffi::mock_server_mismatches(port).and_then(|s| serde_json::from_str(&s).ok()) + .unwrap_or_default(); + ffi::cleanup_mock_server(port); + ffi::free_pact_handle(pact); + let status = sent?.status(); + trace::note(format!("HTTP GET {url} -> {status}")); + Ok(mismatches.iter() + .flat_map(|m| match m["type"].as_str() { + Some("request-mismatch") => m["mismatches"].as_array().cloned().unwrap_or_default(), + _ => vec![m.clone()], + }) + .collect()) +} + +#[when(regex = r"^the requests? (?:is|are) compared to the expected one$")] +async fn compared(world: &mut MatchingWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let received = world.received.clone(); + for r in &received { + let result = compare(world, r).await?; + world.results.push(result); + } + Ok(()) +} + +#[then("the comparison should be OK")] +fn comparison_ok(world: &mut MatchingWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + if let Some(m) = world.results.iter().find(|m| !m.is_empty()) { + bail!("Expected all requests to match, got mismatches {}", Value::from(m.clone())); + } + Ok(()) +} + +#[then("the comparison should NOT be OK")] +fn comparison_not_ok(world: &mut MatchingWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + if world.results.iter().all(|m| m.is_empty()) { + bail!("All requests matched"); + } + Ok(()) +} + +/// The path field for each mismatch type, as `Mismatch::to_json` writes them. +fn mismatch_path(m: &Value) -> Option<&str> { + let field = match m["type"].as_str()? { + "QueryMismatch" => "parameter", + "HeaderMismatch" | "MetadataMismatch" => "key", + "BodyMismatch" => "path", + _ => return None, + }; + m[field].as_str() +} + +/// cucumber-rs leaves Gherkin's `\"` escapes in a `{string}` parameter. +fn description_matches(description: &str, error: &str) -> bool { + let error = &error.replace("\\\"", "\""); + description.contains(error) || Regex::new(error).map(|re| re.is_match(description)).unwrap_or(false) +} + +#[then(expr = "the mismatches will contain a mismatch with error {string} -> {string}")] +fn mismatch_with_error(world: &mut MatchingWorld, step: &Step, path: String, error: String) -> anyhow::Result<()> { + traced(step); + let all: Vec = world.results.iter().flatten().cloned().collect(); + let found = all.iter().any(|m| { + mismatch_path(m) == Some(path.as_str()) && description_matches(m["mismatch"].as_str().unwrap_or_default(), &error) + }); + if !found { + bail!("Did not find a mismatch at {path} with error {error:?} in {}", Value::from(all)); + } + Ok(()) +} + +#[given("an expected response configured with the following:")] +fn expected_response(world: &mut MatchingWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let rows = table(step); + for (field, value) in rows[0].iter().zip(&rows[1]) { + match field.as_str() { + "status" => world.expected_status = value.parse()?, + "matching rules" => world.response_rules = model::matching_rules(value), + other => bail!("unsupported response field {other}"), + } + } + Ok(()) +} + +#[given(expr = "a status {int} response is received")] +fn status_received(world: &mut MatchingWorld, step: &Step, status: u16) { + traced(step); + world.received_status = status; +} + +/// Verifies a one-interaction pact holding the expected response against a provider that returns the received +/// status. pact_ffi has no response comparison call, so this is the only way to reach it. +#[when("the response is compared to the expected one")] +async fn response_compared(world: &mut MatchingWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let pact = ffi::new_pact(&world.consumer(), "p"); + ffi::with_specification(pact, world.spec()); + let i = ffi::new_interaction(pact, "expected response"); + ffi::with_request(i, "GET", "/"); + ffi::response_status(i, world.expected_status); + if let Some(rules) = &world.response_rules { + ffi::with_matching_rules(i, InteractionPart_Response, rules); + } + let dir = world.pact_dir(); + fs::create_dir_all(&dir)?; + let rc = ffi::pact_handle_write_file(pact, dir.to_str().unwrap(), true); + ffi::free_pact_handle(pact); + if rc != 0 { + bail!("pactffi_pact_handle_write_file failed with {rc}"); + } + let file = dir.join(format!("{}-p.json", world.consumer())); + + let status = world.received_status; + let provider = Server::start(Arc::new(move |_req: &ServerRequest, _port| { + ServerResponse { status, ..ServerResponse::default() } + })).await?; + let v = ffi::verifier_new_for_application("pact-ffi-compat", env!("CARGO_PKG_VERSION")); + ffi::verifier_set_provider_info(v, "p", "http", "127.0.0.1", provider.port, "/"); + ffi::verifier_add_file_source(v, file.to_str().unwrap()); + tokio::task::spawn_blocking(move || ffi::verifier_execute(v)).await?; + let results: Value = ffi::verifier_json(v).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or(Value::Null); + ffi::verifier_shutdown(v); + world.response_mismatches = results["errors"].as_array().into_iter().flatten() + .flat_map(|e| e["mismatch"]["mismatches"].as_array().cloned().unwrap_or_default()) + .collect(); + Ok(()) +} + +#[then("the response comparison should be OK")] +fn response_ok(world: &mut MatchingWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + if !world.response_mismatches.is_empty() { + bail!("Expected the response to match, got {}", Value::from(world.response_mismatches.clone())); + } + Ok(()) +} + +#[then("the response comparison should NOT be OK")] +fn response_not_ok(world: &mut MatchingWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + if world.response_mismatches.is_empty() { + bail!("The response matched"); + } + Ok(()) +} + +#[then(expr = "the response mismatches will contain a {string} mismatch with error {string}")] +fn response_mismatch(world: &mut MatchingWorld, step: &Step, kind: String, error: String) -> anyhow::Result<()> { + traced(step); + let ty = match kind.as_str() { + "status" => "StatusMismatch", + "header" => "HeaderMismatch", + "body" => "BodyMismatch", + other => return Err(anyhow!("unknown mismatch kind {other}")), + }; + let found = world.response_mismatches.iter() + .any(|m| m["type"] == ty && description_matches(m["mismatch"].as_str().unwrap_or_default(), &error)); + if !found { + bail!("Did not find a {kind} mismatch with error {error:?} in {}", Value::from(world.response_mismatches.clone())); + } + Ok(()) +} + +fn trace_path(feature: &str, scenario: &str) -> PathBuf { + let dir = env::var("FFI_TRACE_DIR").unwrap_or_else(|_| "target/ffi-trace".into()); + let safe = |s: &str| s.replace(['/', '\\', ':'], "_"); + PathBuf::from(dir).join(safe(feature)).join(format!("{}.md", safe(scenario))) +} + +/// `features/V3/http_matching.feature` -> "v3". +fn feature_version(feature: &cucumber::gherkin::Feature) -> String { + feature.path.as_ref().and_then(|p| p.parent()?.file_name()?.to_str().map(str::to_lowercase)).unwrap_or_default() +} + +fn feature_file(feature: &cucumber::gherkin::Feature) -> String { + feature.path.as_ref().and_then(|p| p.file_stem()?.to_str().map(str::to_string)).unwrap_or_default() +} + +#[tokio::main] +async fn main() { + let lib = model::ffi_lib(); + ffi::load(&lib).unwrap_or_else(|e| panic!("could not load {lib}: {e}")); + + MatchingWorld::cucumber() + .max_concurrent_scenarios(1) + .fail_on_skipped() + .before(|feature, _rule, scenario, world| Box::pin(async move { + trace::reset(); + world.version = feature_version(feature); + world.scenario_id = scenario.name.clone(); + world.expected = expected_request(); + let _ = fs::remove_dir_all(world.pact_dir()); + })) + .after(|feature, _rule, scenario, _ev, _world| Box::pin(async move { + let path = trace_path(&format!("{} {}", feature_version(feature).to_uppercase(), feature.name), &scenario.name); + if let Err(e) = trace::write(&path, &feature.name, &scenario.name) { + eprintln!("could not write trace {}: {e}", path.display()); + } + })) + .filter_run_and_exit(model::FEATURES, |feature, _rule, scenario| { + let v = feature_version(feature); + let f = feature_file(feature); + ((v == "v3" && (f == "http_matching" || f == "matching_rules")) || (v == "v4" && f == "matching_rules")) + && !scenario.tags.iter().any(|t| t == "wip") + && !KNOWN_FAILURES.contains(&scenario.name.as_str()) + }) + .await; +} + +// The mock server reads a 0-byte body as no body (pact_mock_server `extract_body`), so the notEmpty rule +// never sees the empty request body. +const KNOWN_FAILURES: &[&str] = &["Supports a not empty matcher with binary data (negative case)"]; diff --git a/compatibility-suite-ffi/tests/message.rs b/compatibility-suite-ffi/tests/message.rs new file mode 100644 index 000000000..e0fc7c6f2 --- /dev/null +++ b/compatibility-suite-ffi/tests/message.rs @@ -0,0 +1,706 @@ +//! V3 and V4 message consumer features (async and sync), plus V4's mixed-interaction pact, driven only through +//! pact_ffi. Mirrors `v3_steps/message.rs`, `v4_steps/message_consumer.rs`, +//! `v4_steps/sync_message_consumer.rs` and `v4_steps/mod.rs` in the pact-reference compatibility suite. +//! +//! A client's message consumer test is: define the message, generate its contents (what the consumer under test +//! receives), hand them to the consumer code, and write the pact only if that succeeded. The runner has no +//! consumer code, so "successfully processed" generates and writes, and "NOT successfully processed" writes +//! nothing. + +use std::collections::HashMap; +use std::env; +use std::fs; +use std::path::PathBuf; + +use anyhow::{anyhow, bail}; +use cucumber::gherkin::Step; +use cucumber::{given, then, when, World}; +use regex::Regex; +use serde_json::Value; + +use pact_ffi_compat::ffi::{self, Contents, InteractionHandle, InteractionPart, InteractionPart_Request, + InteractionPart_Response, PactHandle, PactSpecification, PactSpecification_V3, PactSpecification_V4}; +use pact_ffi_compat::model::{self, Part, FIXTURES}; +use pact_ffi_compat::trace; + +#[derive(Debug, Default, World)] +struct MessageWorld { + /// "v3" or "v4", from the feature's directory. + version: String, + scenario_id: String, + pact: Option, + interaction: Option, + sync: bool, + /// The error the consumer test failed with. + failed: Option, + received: Vec, + received_sync: Vec<(Contents, Vec)>, + pact_json: Value, + /// Bodies and metadata as configured, to check that generators replaced them. + request_body: Option, + response_body: Option, + request_metadata: HashMap, + response_metadata: HashMap, +} + +impl MessageWorld { + fn spec(&self) -> PactSpecification { + if self.version == "v4" { PactSpecification_V4 } else { PactSpecification_V3 } + } + + fn consumer(&self) -> String { + format!("{}-compatibility-suite-c", self.version) + } + + fn pact_file(&self) -> PathBuf { + self.pact_dir().join(format!("{}-p.json", self.consumer())) + } + + fn pact_dir(&self) -> PathBuf { + env::current_dir().unwrap().join("target/compatibility-suite").join(&self.version).join(&self.scenario_id) + } + + fn pact(&mut self) -> PactHandle { + if let Some(pact) = self.pact { + return pact; + } + let pact = ffi::new_pact(&self.consumer(), "p"); + ffi::with_specification(pact, self.spec()); + self.pact = Some(pact); + pact + } + + fn defined(&self) -> anyhow::Result { + self.interaction.ok_or_else(|| anyhow!("no message is being defined")) + } + + fn shutdown(&mut self) { + if let Some(pact) = self.pact.take() { + ffi::free_pact_handle(pact); + } + } + + fn write_pact(&mut self) -> anyhow::Result<()> { + let pact = self.pact.ok_or_else(|| anyhow!("no pact is being defined"))?; + let dir = self.pact_dir(); + fs::create_dir_all(&dir)?; + let rc = ffi::pact_handle_write_file(pact, &dir.to_string_lossy(), true); + if rc != 0 { + bail!("pactffi_pact_handle_write_file failed with {rc}"); + } + self.pact_json = serde_json::from_str(&fs::read_to_string(self.pact_file())?)?; + Ok(()) + } + + /// The received async message, or the received sync message's request. + fn received(&self, which: &str) -> anyhow::Result<&Contents> { + let found = match which { + "" if !self.sync => self.received.first(), + "" | "response" => self.received_sync.first().and_then(|(_, r)| r.first()), + "request" => self.received_sync.first().map(|(r, _)| r), + _ => None, + }; + found.ok_or_else(|| anyhow!("no {which} message was received")) + } + + /// The first message in the pact file: V3 `messages[0]`, V4 `interactions[0]`. + fn first_message(&self) -> &Value { + match self.pact_json.get("messages") { + Some(m) => &m[0], + None => &self.pact_json["interactions"][0], + } + } +} + +fn traced(step: &Step) { + trace::step(&step.keyword, &step.value); +} + +fn table(step: &Step) -> Vec> { + step.table.as_ref().map(|t| t.rows.clone()).unwrap_or_default() +} + +fn part_of(which: &str) -> InteractionPart { + if which == "response" { InteractionPart_Response } else { InteractionPart_Request } +} + +fn json_to_string(v: &Value) -> String { + match v { + Value::String(s) => s.clone(), + other => other.to_string(), + } +} + +/// Metadata values come back from the FFI as `json_to_string` text: strings bare, everything else as JSON. +fn metadata_value(c: &Contents, key: &str) -> anyhow::Result { + let (_, v) = c.metadata.iter().find(|(k, _)| k == key) + .ok_or_else(|| anyhow!("no metadata {key} in {:?}", c.metadata))?; + Ok(serde_json::from_str(v).unwrap_or_else(|_| Value::String(v.clone()))) +} + +/// `JSON: {...}` is a JSON value (the feature escapes its quotes); anything else is a string. +fn expected_value(s: &str) -> anyhow::Result { + match s.strip_prefix("JSON:") { + Some(json) => Ok(serde_json::from_str(&json.trim().replace("\\\"", "\""))?), + None => Ok(Value::String(s.to_string())), + } +} + +/// Body path `$.one` -> the value at `/one`. +fn body_value<'a>(body: &'a Value, path: &str) -> anyhow::Result<&'a Value> { + let pointer = path.strip_prefix('$').unwrap_or(path).replace('.', "/"); + body.pointer(&pointer).ok_or_else(|| anyhow!("{path} is not in the body {body}")) +} + +fn assert_value_type(kind: &str, v: &Value) -> anyhow::Result<()> { + let s = json_to_string(v); + let pattern = match kind { + "integer" => r"^-?\d+$", + "decimal number" => r"^-?\d+\.\d+$", + "boolean" => r"^(true|false)$", + other => bail!("unknown value type {other}"), + }; + if !Regex::new(pattern)?.is_match(&s) { + bail!("expected a(n) {kind}, got {v}"); + } + Ok(()) +} + +/// Sets a message body the way a client would: text through `pactffi_with_body`, binary through +/// `pactffi_with_binary_body`. Returns the body as a JSON value when it is one. +fn add_body(i: InteractionHandle, p: InteractionPart, cell: &str) -> anyhow::Result> { + let mut part = Part::default(); + model::setup_body(cell, &mut part); + let body = part.body.clone().unwrap_or_default(); + let ct = part.header("content-type").unwrap_or("text/plain").to_string(); + let ok = if model::is_binary(&ct, &body) { + ffi::with_binary_body(i, p, &ct, &body) + } else { + ffi::with_body(i, p, &ct, std::str::from_utf8(&body)?) + }; + if !ok { + bail!("pactffi_with_body failed"); + } + Ok(serde_json::from_slice(&body).ok()) +} + +/// The fixture's contents as the pact file holds them: a JSON value for JSON, otherwise text. +fn expected_document(cell: &str) -> anyhow::Result<(Value, String)> { + let cell = if cell.contains(':') { cell.to_string() } else { format!("file: {cell}") }; + let mut part = Part::default(); + model::setup_body(&cell, &mut part); + let ct = part.header("content-type").unwrap_or("text/plain").to_string(); + let body = part.body.unwrap_or_default(); + let value = serde_json::from_slice(&body).unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&body).into())); + Ok((value, ct)) +} + +/// Compares a document, read either from generated contents (bytes) or a pact file (a JSON value or text). +fn compare_document(actual: &Value, cell: &str) -> anyhow::Result<()> { + let (expected, _) = expected_document(cell)?; + let actual = match (actual, &expected) { + (Value::String(s), e) if !e.is_string() => serde_json::from_str(s).unwrap_or(actual.clone()), + _ => actual.clone(), + }; + if actual != expected { + bail!("Expected document {expected} but was {actual}"); + } + Ok(()) +} + +fn body_as_value(c: &Contents) -> Value { + let bytes = c.body.clone().unwrap_or_default(); + serde_json::from_slice(&bytes).unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into())) +} + +// ---- Defining the interaction ---- + +#[given(regex = r"^a message (?:integration|interaction) is being defined for a consumer test$")] +fn message_defined(world: &mut MessageWorld, step: &Step) { + traced(step); + let pact = world.pact(); + world.interaction = Some(ffi::new_message_interaction(pact, "a message")); + world.sync = false; +} + +#[given("a synchronous message interaction is being defined for a consumer test")] +fn sync_message_defined(world: &mut MessageWorld, step: &Step) { + traced(step); + let pact = world.pact(); + world.interaction = Some(ffi::new_sync_message_interaction(pact, "a synchronous message")); + world.sync = true; +} + +/// v4.feature puts an HTTP interaction and a message in one pact. +#[given("an HTTP interaction is being defined for a consumer test")] +fn http_defined(world: &mut MessageWorld, step: &Step) { + traced(step); + let pact = world.pact(); + let i = ffi::new_interaction(pact, "an HTTP interaction"); + ffi::with_request(i, "GET", "/"); +} + +#[given("a message is defined")] +fn a_message_is_defined(world: &mut MessageWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + world.defined().map(|_| ()) +} + +#[given(regex = r#"^the message (request |)payload contains the "([^"]+)" JSON document$"#)] +fn payload_json(world: &mut MessageWorld, step: &Step, _request: String, name: String) -> anyhow::Result<()> { + traced(step); + world.request_body = add_body(world.defined()?, InteractionPart_Request, &format!("file: {name}.json"))?; + Ok(()) +} + +#[given(regex = r#"^the message response payload contains the "([^"]+)" document$"#)] +fn response_payload(world: &mut MessageWorld, step: &Step, cell: String) -> anyhow::Result<()> { + traced(step); + world.response_body = add_body(world.defined()?, InteractionPart_Response, &cell)?; + Ok(()) +} + +fn add_metadata(world: &mut MessageWorld, which: &str, key: &str, value: Value) -> anyhow::Result<()> { + if !ffi::with_metadata(world.defined()?, key, &value.to_string(), part_of(which)) { + bail!("pactffi_with_metadata failed for {key}"); + } + let originals = if which == "response" { &mut world.response_metadata } else { &mut world.request_metadata }; + originals.insert(key.to_string(), value); + Ok(()) +} + +/// `| key | value |`, where a `JSON:` value is a JSON value and anything else a string. +#[given(regex = r"^the message (request |)contains the following metadata:$")] +fn metadata_table(world: &mut MessageWorld, step: &Step, _request: String) -> anyhow::Result<()> { + traced(step); + for row in table(step).iter().skip(1) { + add_metadata(world, "request", &row[0], expected_value(&row[1])?)?; + } + Ok(()) +} + +/// `| body | generators | metadata |`, any of them. Generators are inline `JSON:` or a fixture file. +#[given(regex = r"^the message (request |response |)is configured with the following:$")] +fn configured(world: &mut MessageWorld, step: &Step, which: String) -> anyhow::Result<()> { + traced(step); + let which = which.trim().to_string(); + let i = world.defined()?; + let p = part_of(&which); + let rows = table(step); + let cells: HashMap<&str, &str> = rows[0].iter().map(String::as_str).zip(rows[1].iter().map(String::as_str)).collect(); + match cells.get("body") { + Some(body) => { + let value = add_body(i, p, body)?; + if which == "response" { world.response_body = value } else { world.request_body = value } + } + // Sync response metadata and generators only apply to responses that exist, and only a body adds one. + None if world.sync && which == "response" => { + if !ffi::with_body(i, p, "text/plain", "") { + bail!("pactffi_with_body failed"); + } + } + None => {} + } + if let Some(metadata) = cells.get("metadata") { + let metadata: Value = serde_json::from_str(metadata)?; + for (k, v) in metadata.as_object().ok_or_else(|| anyhow!("metadata is not an object"))? { + add_metadata(world, &which, k, v.clone())?; + } + } + if let Some(generators) = cells.get("generators") { + let json = match generators.strip_prefix("JSON:") { + Some(json) => json.trim().to_string(), + None => fs::read_to_string(format!("{FIXTURES}/{generators}"))?, + }; + if !ffi::with_generators(i, p, &json) { + bail!("pactffi_with_generators failed"); + } + } + Ok(()) +} + +#[given(regex = r#"^a provider state "([^"]+)" for the (?:synchronous )?message is specified$"#)] +fn provider_state(world: &mut MessageWorld, step: &Step, state: String) -> anyhow::Result<()> { + traced(step); + if !ffi::given(world.defined()?, &state) { + bail!("pactffi_given failed"); + } + Ok(()) +} + +/// The table's first row names the parameters; the second holds their values as JSON. +#[given(regex = r#"^a provider state "([^"]+)" for the (?:synchronous )?message is specified with the following data:$"#)] +fn provider_state_with_data(world: &mut MessageWorld, step: &Step, state: String) -> anyhow::Result<()> { + traced(step); + let rows = table(step); + let params: serde_json::Map = rows[0].iter().zip(&rows[1]) + .map(|(k, v)| Ok((k.clone(), serde_json::from_str(v)?))) + .collect::>()?; + let rc = ffi::given_with_params(world.defined()?, &state, &Value::Object(params).to_string()); + if rc != 0 { + bail!("pactffi_given_with_params failed with {rc}"); + } + Ok(()) +} + +#[given(regex = r#"^a key of "([^"]+)" is specified for the (?:synchronous )?message interaction$"#)] +fn key_specified(world: &mut MessageWorld, step: &Step, key: String) -> anyhow::Result<()> { + traced(step); + if !ffi::set_key(world.defined()?, &key) { + bail!("pactffi_set_key failed"); + } + Ok(()) +} + +#[given(regex = r"^the (?:synchronous )?message interaction is marked as pending$")] +fn marked_pending(world: &mut MessageWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + if !ffi::set_pending(world.defined()?, true) { + bail!("pactffi_set_pending failed"); + } + Ok(()) +} + +#[given(regex = r#"^a comment "([^"]+)" is added to the (?:synchronous )?message interaction$"#)] +fn comment_added(world: &mut MessageWorld, step: &Step, comment: String) -> anyhow::Result<()> { + traced(step); + if !ffi::add_text_comment(world.defined()?, &comment) { + bail!("pactffi_add_text_comment failed"); + } + Ok(()) +} + +// ---- Running the consumer test ---- + +#[when("the message is successfully processed")] +fn processed(world: &mut MessageWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let pact = world.pact.ok_or_else(|| anyhow!("no pact is being defined"))?; + if world.sync { + world.received_sync = ffi::sync_messages(pact); + } else { + world.received = ffi::async_messages(pact); + } + world.write_pact() +} + +#[when(expr = "the message is NOT successfully processed with a {string} exception")] +fn not_processed(world: &mut MessageWorld, step: &Step, error: String) -> anyhow::Result<()> { + traced(step); + let pact = world.pact.ok_or_else(|| anyhow!("no pact is being defined"))?; + world.received = ffi::async_messages(pact); + world.failed = Some(error); + Ok(()) +} + +#[when("the Pact file for the test is generated")] +fn pact_generated(world: &mut MessageWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + world.write_pact() +} + +#[then("the consumer test will have passed")] +fn passed(world: &mut MessageWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + match &world.failed { + Some(e) => bail!("the consumer test failed with {e}"), + None => Ok(()), + } +} + +#[then("the consumer test will have failed")] +fn failed(world: &mut MessageWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + world.failed.as_ref().map(|_| ()).ok_or_else(|| anyhow!("the consumer test passed")) +} + +#[then(expr = "the consumer test error will be {string}")] +fn failed_with(world: &mut MessageWorld, step: &Step, error: String) -> anyhow::Result<()> { + traced(step); + if world.failed.as_deref() != Some(error.as_str()) { + bail!("Expected error {error:?} but was {:?}", world.failed); + } + Ok(()) +} + +// ---- What the consumer received ---- + +#[then(regex = r#"^the received message payload will contain the "([^"]+)" (?:JSON )?document$"#)] +fn received_payload(world: &mut MessageWorld, step: &Step, cell: String) -> anyhow::Result<()> { + traced(step); + let cell = if cell.contains(':') { cell } else { format!("{cell}.json") }; + compare_document(&body_as_value(world.received("")?), &cell) +} + +#[then(expr = "the received message content type will be {string}")] +fn received_content_type(world: &mut MessageWorld, step: &Step, expected: String) -> anyhow::Result<()> { + traced(step); + let actual = metadata_value(world.received("")?, "contentType")?; + if actual != expected.as_str() { + bail!("Expected content type {expected} but was {actual}"); + } + Ok(()) +} + +#[then(regex = r#"^the received message (request |response |)metadata will contain "([^"]+)" == "(.*)"$"#)] +fn received_metadata(world: &mut MessageWorld, step: &Step, which: String, key: String, value: String) + -> anyhow::Result<()> { + traced(step); + let actual = metadata_value(world.received(which.trim())?, &key)?; + let expected = expected_value(&value)?; + if actual != expected { + bail!("Expected metadata {key} = {expected} but was {actual}"); + } + Ok(()) +} + +#[then(regex = r#"^the received message (request |response |)metadata will contain "([^"]+)" replaced with an? "([^"]+)"$"#)] +fn received_metadata_replaced(world: &mut MessageWorld, step: &Step, which: String, key: String, kind: String) + -> anyhow::Result<()> { + traced(step); + let which = which.trim(); + let actual = metadata_value(world.received(which)?, &key)?; + let originals = if which == "response" { &world.response_metadata } else { &world.request_metadata }; + if originals.get(&key) == Some(&actual) { + bail!("metadata {key} was not replaced: {actual}"); + } + assert_value_type(&kind, &actual) +} + +#[then(regex = r#"^the message (request |response |)contents for "([^"]+)" will have been replaced with an? "([^"]+)"$"#)] +fn contents_replaced(world: &mut MessageWorld, step: &Step, which: String, path: String, kind: String) + -> anyhow::Result<()> { + traced(step); + let which = which.trim(); + let body = body_as_value(world.received(which)?); + let original = if which == "response" { &world.response_body } else { &world.request_body }; + let value = body_value(&body, &path)?; + if original.as_ref().and_then(|o| body_value(o, &path).ok()) == Some(value) { + bail!("{path} was not replaced: {value}"); + } + assert_value_type(&kind, value) +} + +// ---- The pact file ---- + +#[then(regex = r"^a Pact file for the message interaction will have been written$")] +fn pact_written(world: &mut MessageWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + if !world.pact_file().exists() { + bail!("{} was not written", world.pact_file().display()); + } + Ok(()) +} + +#[then(regex = r"^a Pact file for the message interaction will NOT have been written$")] +fn pact_not_written(world: &mut MessageWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + if world.pact_file().exists() { + bail!("{} was written", world.pact_file().display()); + } + Ok(()) +} + +#[then(regex = r"^the pact file will contain (\d+) (message )?interactions?$")] +fn interaction_count(world: &mut MessageWorld, step: &Step, n: usize, message: String) -> anyhow::Result<()> { + traced(step); + let key = if message.is_empty() || world.version == "v4" { "interactions" } else { "messages" }; + let actual = world.pact_json[key].as_array().map(Vec::len).unwrap_or(0); + if actual != n { + bail!("Expected {n} {key} but found {actual}"); + } + Ok(()) +} + +#[then(expr = "the first message in the pact file will contain the {string} document")] +fn first_message_document(world: &mut MessageWorld, step: &Step, fixture: String) -> anyhow::Result<()> { + traced(step); + compare_document(&world.first_message()["contents"], &fixture) +} + +#[then(expr = "the first message in the pact file content type will be {string}")] +fn first_message_content_type(world: &mut MessageWorld, step: &Step, expected: String) -> anyhow::Result<()> { + traced(step); + let actual = &world.first_message()["metadata"]["contentType"]; + if actual != expected.as_str() { + bail!("Expected content type {expected} but was {actual}"); + } + Ok(()) +} + +#[then(regex = r#"^the first message in the pact file will contain the (request |)message metadata "([^"]+)" == "(.*)"$"#)] +fn first_message_metadata(world: &mut MessageWorld, step: &Step, request: String, key: String, value: String) + -> anyhow::Result<()> { + traced(step); + let message = world.first_message(); + let metadata = if request.is_empty() { &message["metadata"] } else { &message["request"]["metadata"] }; + let expected = expected_value(&value)?; + if metadata[key.as_str()] != expected { + bail!("Expected metadata {key} = {expected} but was {}", metadata[key.as_str()]); + } + Ok(()) +} + +fn provider_states(world: &MessageWorld) -> Vec { + world.first_message()["providerStates"].as_array().cloned().unwrap_or_default() +} + +#[then(regex = r"^the first message in the pact file will contain (\d+) provider states?$")] +fn provider_state_count(world: &mut MessageWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let states = provider_states(world); + if states.len() != n { + bail!("Expected {n} provider states but found {}", Value::from(states)); + } + Ok(()) +} + +#[then(expr = "the first message in the Pact file will contain provider state {string}")] +fn provider_state_present(world: &mut MessageWorld, step: &Step, state: String) -> anyhow::Result<()> { + traced(step); + let states = provider_states(world); + if !states.iter().any(|s| s["name"] == state.as_str()) { + bail!("No provider state '{state}' in {}", Value::from(states)); + } + Ok(()) +} + +#[then(regex = r#"^the provider state "([^"]+)" for the message will contain the following parameters:$"#)] +fn provider_state_params(world: &mut MessageWorld, step: &Step, state: String) -> anyhow::Result<()> { + traced(step); + let expected: Value = serde_json::from_str(&table(step)[1][0])?; + let states = provider_states(world); + let s = states.iter().find(|s| s["name"] == state.as_str()) + .ok_or_else(|| anyhow!("No provider state '{state}' in {}", Value::from(states.clone())))?; + if s["params"] != expected { + bail!("Expected parameters {expected} but were {}", s["params"]); + } + Ok(()) +} + +fn first_interaction(world: &MessageWorld) -> anyhow::Result<&Value> { + world.pact_json["interactions"].get(0).ok_or_else(|| anyhow!("no interactions in the pact file")) +} + +/// A V4 message part's `contents` is `{content, contentType, encoded}`. +fn v4_content(contents: &Value) -> Value { + let content = &contents["content"]; + match contents["encoded"].as_str() { + Some("base64") | Some("BASE64") => content.as_str() + .and_then(|s| base64::Engine::decode(&base64::engine::general_purpose::STANDARD, s).ok()) + .map(|b| Value::String(String::from_utf8_lossy(&b).into())) + .unwrap_or(content.clone()), + _ => content.clone(), + } +} + +#[then(regex = r#"^the first interaction in the pact file will contain the "([^"]+)" document as (the request|a response|the first response message|the second response message)$"#)] +fn interaction_document(world: &mut MessageWorld, step: &Step, cell: String, which: String) -> anyhow::Result<()> { + traced(step); + let i = first_interaction(world)?; + let contents = match which.as_str() { + "the request" => &i["request"]["contents"], + "the second response message" => &i["response"][1]["contents"], + _ => &i["response"][0]["contents"], + }; + compare_document(&v4_content(contents), &cell) +} + +#[then(regex = r#"^the first interaction in the pact file (request|response) content type will be "([^"]+)"$"#)] +fn interaction_content_type(world: &mut MessageWorld, step: &Step, which: String, expected: String) + -> anyhow::Result<()> { + traced(step); + let i = first_interaction(world)?; + let part = if which == "request" { &i["request"] } else { &i["response"][0] }; + let actual = &part["contents"]["contentType"]; + if actual != expected.as_str() { + bail!("Expected {which} content type {expected} but was {actual} in {part}"); + } + Ok(()) +} + +#[then(regex = r"^the first interaction in the pact file will contain (\d+) response messages?$")] +fn response_count(world: &mut MessageWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let actual = first_interaction(world)?["response"].as_array().map(Vec::len).unwrap_or(0); + if actual != n { + bail!("Expected {n} response messages but found {actual}"); + } + Ok(()) +} + +#[then(expr = "the first interaction in the Pact file will have a type of {string}")] +fn interaction_type(world: &mut MessageWorld, step: &Step, expected: String) -> anyhow::Result<()> { + traced(step); + let actual = &first_interaction(world)?["type"]; + if actual != expected.as_str() { + bail!("Expected type '{expected}' but was {actual}"); + } + Ok(()) +} + +#[then(expr = "there will be an interaction in the Pact file with a type of {string}")] +fn any_interaction_type(world: &mut MessageWorld, step: &Step, expected: String) -> anyhow::Result<()> { + traced(step); + let interactions = world.pact_json["interactions"].as_array().cloned().unwrap_or_default(); + if !interactions.iter().any(|i| i["type"] == expected.as_str()) { + bail!("No interaction of type '{expected}' in {}", Value::from(interactions)); + } + Ok(()) +} + +/// The expected value is JSON in single quotes. +#[then(regex = r#"^the first interaction in the Pact file will have "([^"]+)" = '(.*)'$"#)] +fn interaction_attribute(world: &mut MessageWorld, step: &Step, name: String, value: String) -> anyhow::Result<()> { + traced(step); + let expected: Value = serde_json::from_str(&value)?; + let actual = &first_interaction(world)?[name.as_str()]; + if *actual != expected { + bail!("Expected {name} = {expected} but was {actual}"); + } + Ok(()) +} + +fn trace_path(feature: &str, scenario: &str) -> PathBuf { + let dir = env::var("FFI_TRACE_DIR").unwrap_or_else(|_| "target/ffi-trace".into()); + let safe = |s: &str| s.replace(['/', '\\', ':'], "_"); + PathBuf::from(dir).join(safe(feature)).join(format!("{}.md", safe(scenario))) +} + +/// `features/V3/message_consumer.feature` -> "v3". +fn feature_version(feature: &cucumber::gherkin::Feature) -> String { + feature.path.as_ref().and_then(|p| p.parent()?.file_name()?.to_str().map(str::to_lowercase)).unwrap_or_default() +} + +#[tokio::main] +async fn main() { + let lib = model::ffi_lib(); + ffi::load(&lib).unwrap_or_else(|e| panic!("could not load {lib}: {e}")); + + MessageWorld::cucumber() + .max_concurrent_scenarios(1) + .fail_on_skipped() + .before(|feature, _rule, scenario, world| Box::pin(async move { + trace::reset(); + world.version = feature_version(feature); + world.scenario_id = scenario.name.clone(); + let _ = fs::remove_dir_all(world.pact_dir()); + })) + .after(|feature, _rule, scenario, _ev, world| Box::pin(async move { + if let Some(world) = world { + world.shutdown(); + } + let path = trace_path(&format!("{} {}", feature_version(feature).to_uppercase(), feature.name), &scenario.name); + if let Err(e) = trace::write(&path, &feature.name, &scenario.name) { + eprintln!("could not write trace {}: {e}", path.display()); + } + })) + .filter_run_and_exit(model::FEATURES, |feature, _rule, scenario| { + let file = feature.path.as_ref().and_then(|p| p.file_name()?.to_str().map(str::to_string)).unwrap_or_default(); + matches!((feature_version(feature).as_str(), file.as_str()), + ("v3", "message_consumer.feature") + | ("v4", "message_consumer.feature" | "synchronous_message_consumer.feature" | "v4.feature")) + && !scenario.tags.iter().any(|t| t == "wip") + }) + .await; +} diff --git a/compatibility-suite-ffi/tests/provider.rs b/compatibility-suite-ffi/tests/provider.rs new file mode 100644 index 000000000..dfac767c9 --- /dev/null +++ b/compatibility-suite-ffi/tests/provider.rs @@ -0,0 +1,746 @@ +//! V1 to V4 HTTP and message provider features, verified only through the pact_ffi verifier functions. Mirrors +//! `v1_provider.rs`, `v2_provider.rs`, `shared_steps/provider.rs`, the provider halves of `v3_steps/message.rs` +//! and `v4_steps/message_provider.rs`, and the V3/V4 HTTP provider steps in the pact-reference compatibility suite. +//! +//! The pact files are written through the FFI (`pactffi_pact_handle_write_file`), and the provider, the provider +//! state callback and the Pact broker are small local HTTP servers (`server.rs`) that record what they receive. +//! A message provider is the same kind of server, answering the verifier's POST with the message the way the +//! reference suite's message proxy does: the body, its content type, and the metadata as base64 JSON in the +//! `pact-message-metadata` header. + +use std::env; +use std::fs; +use std::path::PathBuf; +use std::sync::Arc; + +use anyhow::{anyhow, bail}; +use cucumber::gherkin::Step; +use cucumber::{given, then, when, World}; +use serde_json::{json, Value}; + +use base64::engine::general_purpose::STANDARD as BASE64; +use base64::Engine; +use pact_ffi_compat::ffi::{self, InteractionHandle, InteractionPart_Request, PactSpecification}; +use pact_ffi_compat::ffi::{PactSpecification_V1, PactSpecification_V2, PactSpecification_V3, PactSpecification_V4}; +use pact_ffi_compat::model::{self, Interaction, Part}; +use pact_ffi_compat::server::{Request, Response, Server}; +use pact_ffi_compat::trace; + +#[derive(Debug, Default, World)] +struct ProviderWorld { + /// "v1" to "v4", from the feature's directory. + version: String, + scenario_id: String, + interactions: Vec, + /// Messages the message provider can generate, by description: the body and the metadata. + messages: Vec<(String, Part, serde_json::Map)>, + provider: Option, + state_callback: Option, + /// Pact files written for the scenario, each a file source. + pact_files: Vec, + /// One stand-in broker per broker-sourced pact, keyed by interaction number. + brokers: Vec<(usize, Server)>, + publish: bool, + custom_headers: Vec<(String, String)>, + exit: Option, + results: Value, + output: String, +} + +impl ProviderWorld { + fn spec(&self) -> PactSpecification { + match self.version.as_str() { + "v4" => PactSpecification_V4, + "v3" => PactSpecification_V3, + "v2" => PactSpecification_V2, + _ => PactSpecification_V1, + } + } + + fn pact_dir(&self) -> PathBuf { + env::current_dir().unwrap().join("target/compatibility-suite/provider").join(&self.version).join(&self.scenario_id) + } + + fn interaction(&self, n: usize) -> anyhow::Result { + self.interactions.get(n.wrapping_sub(1)).cloned().ok_or_else(|| anyhow!("no interaction {n}")) + } + + fn state_calls(&self) -> Vec { + self.state_callback.as_ref().map(|s| s.requests()).unwrap_or_default().iter() + .filter_map(|r| serde_json::from_slice(&r.body).ok()) + .collect() + } + + fn state_called(&self, action: &str, state: Option<&str>) -> bool { + self.state_called_with(action, state, &[]) + } + + /// The callback body is `{"state", "params", "action"}`; each expected parameter must be in `params`. + fn state_called_with(&self, action: &str, state: Option<&str>, params: &[(String, Value)]) -> bool { + self.state_calls().iter().any(|c| c["action"] == action && state.map_or(true, |s| c["state"] == s) + && params.iter().all(|(k, v)| &c["params"][k] == v)) + } + + fn published(&self, n: usize) -> Vec { + self.brokers.iter().filter(|(i, _)| *i == n) + .flat_map(|(_, b)| b.requests()) + .filter(|r| r.method == "POST" && r.path_only().ends_with("/verification-results")) + .filter_map(|r| serde_json::from_slice(&r.body).ok()) + .collect() + } +} + +fn traced(step: &Step) { + trace::step(&step.keyword, &step.value); +} + +fn table(step: &Step) -> Vec> { + step.table.as_ref().map(|t| t.rows.clone()).unwrap_or_default() +} + +/// Serves each interaction's response to a request with the same method and path; anything else is a 500. +async fn start_provider(world: &mut ProviderWorld, interactions: Vec) -> anyhow::Result<()> { + let server = Server::start(Arc::new(move |req: &Request, _port| { + interactions.iter() + .find(|i| i.method.eq_ignore_ascii_case(&req.method) && i.path == req.path_only()) + .map(|i| Response { + status: i.status, + headers: i.response.headers.clone(), + body: i.response.body.clone().unwrap_or_default(), + }) + .unwrap_or(Response { status: 500, headers: vec![], body: b"no matching interaction".to_vec() }) + })).await?; + trace::note(format!("provider listening on {}", server.url())); + world.provider = Some(server); + Ok(()) +} + +/// Builds a one-interaction pact through the FFI and writes it, as a consumer test would have. `setup` adds +/// whatever else the scenario needs (provider states, pending, comments) to the interaction. +fn write_pact(world: &ProviderWorld, n: usize, setup: impl FnOnce(InteractionHandle) -> anyhow::Result<()>) -> anyhow::Result { + let interaction = world.interaction(n)?; + let consumer = format!("c_{n}"); + let pact = ffi::new_pact(&consumer, "p"); + ffi::with_specification(pact, world.spec()); + let i = model::register(pact, &interaction); + setup(i)?; + write_file(world, pact, &consumer) +} + +/// Builds a one-message pact through the FFI: the message's description is its name, which is what the message +/// provider looks it up by. The consumer is `c_{name}`, so each message gets its own pact file. +fn write_message_pact(world: &ProviderWorld, name: &str, setup: impl FnOnce(InteractionHandle) -> anyhow::Result<()>) -> anyhow::Result { + let consumer = format!("c_{name}"); + let pact = ffi::new_pact(&consumer, "p"); + ffi::with_specification(pact, world.spec()); + let i = ffi::new_message_interaction(pact, name); + setup(i)?; + write_file(world, pact, &consumer) +} + +fn write_file(world: &ProviderWorld, pact: ffi::PactHandle, consumer: &str) -> anyhow::Result { + let dir = world.pact_dir(); + let rc = ffi::pact_handle_write_file(pact, dir.to_str().unwrap(), false); + ffi::free_pact_handle(pact); + if rc != 0 { + bail!("pactffi_pact_handle_write_file failed with {rc}"); + } + Ok(dir.join(format!("{consumer}-p.json"))) +} + +#[given("the following HTTP interactions have been defined:")] +fn interactions_defined(world: &mut ProviderWorld, step: &Step) { + traced(step); + world.interactions = model::setup_common_interactions(&table(step)); +} + +#[given(regex = r"^a provider is started that returns the response from interaction (\d+)$")] +async fn provider_for_interaction(world: &mut ProviderWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let i = world.interaction(n)?; + start_provider(world, vec![i]).await +} + +#[given(regex = r"^a provider is started that returns the response from interaction (\d+), with the following changes:$")] +async fn provider_for_changed_interaction(world: &mut ProviderWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let mut i = world.interaction(n)?; + let rows = table(step); + for (col, value) in rows[0].iter().zip(&rows[1]) { + match col.as_str() { + "response" => i.status = value.parse()?, + "response headers" => i.response.headers.extend(model::parse_headers(value)), + "response body" => model::setup_body(value, &mut i.response), + other => bail!("unsupported change column {other}"), + } + } + start_provider(world, vec![i]).await +} + +#[given(regex = r#"^a provider is started that returns the responses from interactions "(.*)"$"#)] +async fn provider_for_interactions(world: &mut ProviderWorld, step: &Step, ids: String) -> anyhow::Result<()> { + traced(step); + let interactions = ids.split(',').map(|id| world.interaction(id.trim().parse()?)).collect::>()?; + start_provider(world, interactions).await +} + +#[given(regex = r"^a Pact file for interaction (\d+) is to be verified$")] +fn pact_file(world: &mut ProviderWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let file = write_pact(world, n, |_| Ok(()))?; + world.pact_files.push(file); + Ok(()) +} + +#[given(regex = r#"^a Pact file for interaction (\d+) is to be verified with a provider state "(.*)" defined$"#)] +fn pact_file_with_state(world: &mut ProviderWorld, step: &Step, n: usize, state: String) -> anyhow::Result<()> { + traced(step); + let file = write_pact(world, n, |i| { ffi::given(i, &state); Ok(()) })?; + world.pact_files.push(file); + Ok(()) +} + +/// One provider state per row; a `Parameters` column holds the state's parameters as a JSON object. +#[given(regex = r"^a Pact file for interaction (\d+) is to be verified with the following provider states defined:$")] +fn pact_file_with_states(world: &mut ProviderWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let rows = table(step); + let file = write_pact(world, n, |i| { + let params_col = rows[0].iter().position(|c| c == "Parameters"); + for row in &rows[1..] { + match params_col.map(|c| row[c].trim()).filter(|p| !p.is_empty()) { + Some(params) => { + let rc = ffi::given_with_params(i, &row[0], params); + if rc != 0 { + bail!("pactffi_given_with_params failed with {rc}"); + } + } + None => { ffi::given(i, &row[0]); } + } + } + Ok(()) + })?; + world.pact_files.push(file); + Ok(()) +} + +#[given(regex = r"^a Pact file for interaction (\d+) is to be verified, but is marked pending$")] +fn pact_file_pending(world: &mut ProviderWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let file = write_pact(world, n, |i| { ffi::set_pending(i, true); Ok(()) })?; + world.pact_files.push(file); + Ok(()) +} + +/// `text` rows are added as text comments, a `testname` row as the `testname` comment. +fn add_comments(i: InteractionHandle, rows: &[Vec]) -> anyhow::Result<()> { + for row in &rows[1..] { + match row[1].as_str() { + "text" => { ffi::add_text_comment(i, &row[0]); } + "testname" => { ffi::set_comment(i, "testname", &Value::String(row[0].clone()).to_string()); } + other => bail!("unknown comment type {other}"), + } + } + Ok(()) +} + +#[given(regex = r"^a Pact file for interaction (\d+) is to be verified with the following comments:$")] +fn pact_file_with_comments(world: &mut ProviderWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let rows = table(step); + let file = write_pact(world, n, |i| add_comments(i, &rows))?; + world.pact_files.push(file); + Ok(()) +} + +/// Cucumber's `{string}` unescapes `\"`; these steps match with a regex, so do the same. +fn unescape(s: &str) -> String { + s.replace("\\\"", "\"") +} + +/// `JSON: ...` is a JSON value, anything else a string. +fn metadata_value(value: &str) -> anyhow::Result { + Ok(match value.trim().strip_prefix("JSON:") { + Some(json) => serde_json::from_str(json.trim())?, + None => Value::String(value.to_string()), + }) +} + +fn message_part(cell: &str) -> Part { + let mut part = Part::default(); + model::setup_body(cell, &mut part); + part +} + +fn add_message(world: &mut ProviderWorld, name: String, body: &str, metadata: serde_json::Map) { + world.messages.push((name, message_part(&unescape(body)), metadata)); +} + +#[given(regex = r#"^a provider is started that can generate the "(.*)" message with "(.*)"$"#)] +fn message_provider(world: &mut ProviderWorld, step: &Step, name: String, body: String) { + traced(step); + add_message(world, name, &body, Default::default()); +} + +#[given(regex = r#"^a provider is started that can generate the "(.*)" message with "(.*)" and the following metadata:$"#)] +fn message_provider_with_metadata(world: &mut ProviderWorld, step: &Step, name: String, body: String) -> anyhow::Result<()> { + traced(step); + let metadata = table(step)[1..].iter() + .map(|row| Ok((row[0].clone(), metadata_value(&row[1])?))) + .collect::>()?; + add_message(world, name, &body, metadata); + Ok(()) +} + +/// Serves every message the scenario defined. The verifier POSTs `{"description": ...}` for each message. +async fn start_message_provider(world: &mut ProviderWorld) -> anyhow::Result<()> { + let messages = world.messages.clone(); + let server = Server::start(Arc::new(move |req: &Request, _port| { + let description = serde_json::from_slice::(&req.body).ok() + .and_then(|v| v["description"].as_str().map(str::to_string)).unwrap_or_default(); + match messages.iter().find(|(name, _, _)| *name == description) { + Some((_, part, metadata)) => { + let ct = part.header("content-type").unwrap_or("text/plain").to_string(); + let mut metadata = metadata.clone(); + metadata.entry("contentType").or_insert(Value::String(ct.clone())); + Response { + status: 200, + headers: vec![ + ("Content-Type".into(), ct), + ("pact-message-metadata".into(), BASE64.encode(Value::Object(metadata).to_string())), + ], + body: part.body.clone().unwrap_or_default(), + } + } + None => Response::json(404, &json!({"error": format!("no message '{description}'")})), + } + })).await?; + trace::note(format!("message provider listening on {}", server.url())); + world.provider = Some(server); + Ok(()) +} + +/// The message's body from the fixture cell, through `pactffi_with_body` or `pactffi_with_binary_body`. +fn message_body(i: InteractionHandle, cell: &str, matching_rules: Option) { + let mut part = message_part(&unescape(cell)); + part.matching_rules = matching_rules; + model::register_part(i, InteractionPart_Request, &part); +} + +fn push_message_pact(world: &mut ProviderWorld, name: &str, setup: impl FnOnce(InteractionHandle) -> anyhow::Result<()>) -> anyhow::Result<()> { + let file = write_message_pact(world, name, setup)?; + world.pact_files.push(file); + Ok(()) +} + +#[given(regex = r#"^a Pact file for "([^"]*)":"(.*)" is to be verified$"#)] +fn message_pact(world: &mut ProviderWorld, step: &Step, name: String, body: String) -> anyhow::Result<()> { + traced(step); + push_message_pact(world, &name, |i| { message_body(i, &body, None); Ok(()) }) +} + +#[given(regex = r#"^a Pact file for "([^"]*)":"(.*)" is to be verified with provider state "(.*)"$"#)] +fn message_pact_with_state(world: &mut ProviderWorld, step: &Step, name: String, body: String, state: String) -> anyhow::Result<()> { + traced(step); + push_message_pact(world, &name, |i| { ffi::given(i, &state); message_body(i, &body, None); Ok(()) }) +} + +#[given(regex = r#"^a Pact file for "([^"]*)":"(.*)" is to be verified, but is marked pending$"#)] +fn message_pact_pending(world: &mut ProviderWorld, step: &Step, name: String, body: String) -> anyhow::Result<()> { + traced(step); + push_message_pact(world, &name, |i| { message_body(i, &body, None); ffi::set_pending(i, true); Ok(()) }) +} + +#[given(regex = r#"^a Pact file for "([^"]*)":"(.*)" is to be verified with the following comments:$"#)] +fn message_pact_with_comments(world: &mut ProviderWorld, step: &Step, name: String, body: String) -> anyhow::Result<()> { + traced(step); + let rows = table(step); + push_message_pact(world, &name, |i| { message_body(i, &body, None); add_comments(i, &rows) }) +} + +/// `pactffi_with_metadata` parses the value as JSON and falls back to a string, so a string is passed as is. +fn add_metadata(i: InteractionHandle, key: &str, value: &str) -> anyhow::Result<()> { + let value = match value.trim().strip_prefix("JSON:") { + Some(json) => json.trim().to_string(), + None => value.to_string(), + }; + if !ffi::with_metadata(i, key, &value, InteractionPart_Request) { + bail!("pactffi_with_metadata failed for {key}"); + } + Ok(()) +} + +#[given(regex = r#"^a Pact file for "([^"]*)":"(.*)" is to be verified with the following metadata:$"#)] +fn message_pact_with_metadata(world: &mut ProviderWorld, step: &Step, name: String, body: String) -> anyhow::Result<()> { + traced(step); + let rows = table(step); + push_message_pact(world, &name, |i| { + message_body(i, &body, None); + rows[1..].iter().try_for_each(|row| add_metadata(i, &row[0], &row[1])) + }) +} + +/// Rows of `body`, `matching rules` (a fixture or `JSON:`) and `metadata` (`key=value; ...`). +#[given(regex = r#"^a Pact file for "([^"]*)" is to be verified with the following:$"#)] +fn message_pact_with_following(world: &mut ProviderWorld, step: &Step, name: String) -> anyhow::Result<()> { + traced(step); + let rows = table(step); + let get = |key: &str| rows.iter().find(|r| r[0] == key).map(|r| r[1].clone()); + let rules = get("matching rules").and_then(|cell| model::matching_rules(&cell)); + push_message_pact(world, &name, |i| { + message_body(i, &get("body").unwrap_or_default(), rules); + for entry in get("metadata").unwrap_or_default().split(';').filter(|e| !e.trim().is_empty()) { + let (key, value) = entry.trim().split_once('=').ok_or_else(|| anyhow!("bad metadata {entry}"))?; + add_metadata(i, key, value)?; + } + Ok(()) + }) +} + +/// The broker serves the pacts-for-verification flow for one pact and accepts verification results. +#[given(regex = r"^a Pact file for interaction (\d+) is to be verified from a Pact broker$")] +async fn pact_from_broker(world: &mut ProviderWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + let file = write_pact(world, n, |_| Ok(()))?; + let pact: Value = serde_json::from_str(&fs::read_to_string(&file)?)?; + let broker = Server::start(Arc::new(move |req: &Request, port| { + let base = format!("http://127.0.0.1:{port}"); + let pact_url = format!("{base}/pacts/provider/p/consumer/c_{n}"); + match (req.method.as_str(), req.path_only()) { + ("GET", "/") => Response::json(200, &json!({"_links": { + "pb:provider-pacts-for-verification": { + "href": format!("{base}/pacts/provider/{{provider}}/for-verification"), "templated": true + } + }})), + // The verifier navigates here first, then POSTs the selectors to the resource's self link. + ("GET", "/pacts/provider/p/for-verification") => Response::json(200, &json!({"_links": { + "self": {"href": format!("{base}/pacts/provider/p/for-verification")} + }})), + ("POST", "/pacts/provider/p/for-verification") => Response::json(200, &json!({ + "_embedded": {"pacts": [{ + "_links": {"self": {"href": pact_url, "name": format!("Pact between c_{n} and p")}}, + "shortDescription": "latest" + }]}, + "_links": {"self": {"href": format!("{base}/pacts/provider/p/for-verification")}} + })), + ("GET", path) if path == format!("/pacts/provider/p/consumer/c_{n}") => { + let mut pact = pact.clone(); + pact["_links"] = json!({ + "self": {"href": pact_url}, + "pb:publish-verification-results": {"href": format!("{pact_url}/verification-results")} + }); + Response::json(200, &pact) + } + ("POST", path) if path.ends_with("/verification-results") => Response::json(201, &json!({})), + _ => Response::json(404, &json!({"error": "not found"})), + } + })).await?; + trace::note(format!("Pact broker for c_{n} listening on {}", broker.url())); + world.brokers.push((n, broker)); + Ok(()) +} + +#[given("publishing of verification results is enabled")] +fn publishing_enabled(world: &mut ProviderWorld, step: &Step) { + traced(step); + world.publish = true; +} + +async fn state_callback(world: &mut ProviderWorld, fail: bool) -> anyhow::Result<()> { + let server = Server::start(Arc::new(move |_req: &Request, _port| { + if fail { Response::json(500, &json!({"error": "state change failed"})) } else { Response::json(200, &json!({})) } + })).await?; + trace::note(format!("provider state callback listening on {}", server.url())); + world.state_callback = Some(server); + Ok(()) +} + +#[given("a provider state callback is configured")] +async fn state_callback_configured(world: &mut ProviderWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + state_callback(world, false).await +} + +#[given("a provider state callback is configured, but will return a failure")] +async fn failing_state_callback_configured(world: &mut ProviderWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + state_callback(world, true).await +} + +/// The FFI has no request filter callback, only custom headers, so other kinds of change can't be expressed. +#[given("a request filter is configured to make the following changes:")] +fn request_filter(world: &mut ProviderWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let rows = table(step); + for (col, value) in rows[0].iter().zip(&rows[1]) { + match col.as_str() { + "headers" => world.custom_headers.extend(model::parse_headers(value)), + other => bail!("pact_ffi has no request filter for {other}; only pactffi_verifier_add_custom_header exists"), + } + } + Ok(()) +} + +#[when("the verification is run")] +async fn verification_run(world: &mut ProviderWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + if !world.messages.is_empty() { + start_message_provider(world).await?; + } + let provider = world.provider.as_ref().ok_or_else(|| anyhow!("no provider started"))?; + let v = ffi::verifier_new_for_application("pact-ffi-compat", env!("CARGO_PKG_VERSION")); + ffi::verifier_set_provider_info(v, "p", "http", "127.0.0.1", provider.port, "/"); + if let Some(cb) = &world.state_callback { + ffi::verifier_set_provider_state(v, &cb.url(), true, true); + } + if world.publish { + ffi::verifier_set_publish_options(v, "1.2.3"); + } + for (k, val) in &world.custom_headers { + ffi::verifier_add_custom_header(v, k, val); + } + for file in &world.pact_files { + ffi::verifier_add_file_source(v, file.to_str().unwrap()); + } + for (_, broker) in &world.brokers { + ffi::verifier_broker_source_with_selectors(v, &broker.url(), false, None); + } + // The verifier blocks on its own runtime; the servers keep running on this one. + let exit = tokio::task::spawn_blocking(move || ffi::verifier_execute(v)).await?; + world.exit = Some(exit); + world.output = ffi::verifier_output(v, true).unwrap_or_default(); + world.results = ffi::verifier_json(v).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or(Value::Null); + ffi::verifier_shutdown(v); + Ok(()) +} + +#[then("the verification will be successful")] +fn successful(world: &mut ProviderWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + if world.exit != Some(0) || world.results["result"] != true { + bail!("verification failed (exit {:?}):\n{}", world.exit, world.output); + } + Ok(()) +} + +#[then("the verification will NOT be successful")] +fn not_successful(world: &mut ProviderWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + if world.exit == Some(0) || world.results["result"] != false { + bail!("verification passed (exit {:?})", world.exit); + } + Ok(()) +} + +/// Maps the suite's error wording onto the verifier's JSON report: mismatch types for response and message +/// mismatches, the error message for a failed state change. `entries` are `interactionResults` or +/// `pendingErrors`, both of which carry a `mismatch`. +fn has_error(entries: &Value, error: &str) -> anyhow::Result { + let mismatch_types: Vec = entries.as_array().cloned().unwrap_or_default().iter() + .flat_map(|r| r["mismatch"]["mismatches"].as_array().cloned().unwrap_or_default()) + .filter_map(|m| m["type"].as_str().map(str::to_string)) + .collect(); + let has = |types: &[&str]| mismatch_types.iter().any(|t| types.contains(&t.as_str())); + Ok(match error { + "Response status did not match" => has(&["StatusMismatch"]), + "Headers had differences" => has(&["HeaderMismatch"]), + "Body had differences" => has(&["BodyMismatch", "BodyTypeMismatch"]), + "Body type had differences" => has(&["BodyTypeMismatch"]), + "Metadata had differences" => has(&["MetadataMismatch"]), + "State change request failed" => entries.to_string().contains("state change handlers has failed"), + other => bail!("unknown error {other}"), + }) +} + +#[then(regex = r#"^the verification results will contain a "(.*)" error$"#)] +fn results_contain_error(world: &mut ProviderWorld, step: &Step, error: String) -> anyhow::Result<()> { + traced(step); + if !has_error(&world.results["interactionResults"], &error)? { + bail!("no \"{error}\" error in the verification results: {}", world.results); + } + Ok(()) +} + +#[then(regex = r#"^there will be a pending "(.*)" error$"#)] +fn pending_error(world: &mut ProviderWorld, step: &Step, error: String) -> anyhow::Result<()> { + traced(step); + if !has_error(&world.results["pendingErrors"], &error)? { + bail!("no pending \"{error}\" error in the verification results: {}", world.results); + } + Ok(()) +} + +#[then(regex = r#"^the comment "(.*)" will have been printed to the console$"#)] +fn comment_printed(world: &mut ProviderWorld, step: &Step, comment: String) -> anyhow::Result<()> { + traced(step); + if !world.output.contains(&comment) { + bail!("comment '{comment}' not in the verifier output:\n{}", world.output); + } + Ok(()) +} + +#[then(regex = r#"^the "(.*)" will displayed as the original test name$"#)] +fn test_name_printed(world: &mut ProviderWorld, step: &Step, name: String) -> anyhow::Result<()> { + traced(step); + if !world.output.contains(&format!("Test Name: {name}")) { + bail!("test name '{name}' not in the verifier output:\n{}", world.output); + } + Ok(()) +} + +/// The table's first row names the parameters, the second holds their JSON values. +fn expected_params(step: &Step) -> anyhow::Result> { + let rows = table(step); + rows[0].iter().zip(&rows[1]).map(|(k, v)| Ok((k.clone(), serde_json::from_str(v)?))).collect() +} + +#[then(regex = r#"^the provider state callback will receive a setup call with "(.*)" and the following parameters:$"#)] +fn state_setup_with_params(world: &mut ProviderWorld, step: &Step, state: String) -> anyhow::Result<()> { + traced(step); + let params = expected_params(step)?; + if !world.state_called_with("setup", Some(&state), ¶ms) { + bail!("no setup call for state '{state}' with {params:?}: {:?}", world.state_calls()); + } + Ok(()) +} + +#[then(regex = r#"^the provider state callback will receive a teardown call "(.*)" and the following parameters:$"#)] +fn state_teardown_with_params(world: &mut ProviderWorld, step: &Step, state: String) -> anyhow::Result<()> { + traced(step); + let params = expected_params(step)?; + if !world.state_called_with("teardown", Some(&state), ¶ms) { + bail!("no teardown call for state '{state}' with {params:?}: {:?}", world.state_calls()); + } + Ok(()) +} + +#[then("a verification result will NOT be published back")] +fn not_published(world: &mut ProviderWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let published: Vec = world.brokers.iter().flat_map(|(n, _)| world.published(*n)).collect(); + if !published.is_empty() { + bail!("verification results were published: {published:?}"); + } + Ok(()) +} + +fn published_with(world: &ProviderWorld, n: usize, success: bool) -> anyhow::Result<()> { + let published = world.published(n); + if !published.iter().any(|r| r["success"] == success) { + bail!("no verification result with success = {success} published for interaction {n}: {published:?}"); + } + Ok(()) +} + +#[then(regex = r"^a successful verification result will be published back for interaction \{(\d+)\}$")] +fn published_success(world: &mut ProviderWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + published_with(world, n, true) +} + +#[then(regex = r"^a failed verification result will be published back for the interaction \{(\d+)\}$")] +fn published_failure(world: &mut ProviderWorld, step: &Step, n: usize) -> anyhow::Result<()> { + traced(step); + published_with(world, n, false) +} + +#[then("the provider state callback will be called before the verification is run")] +fn state_setup_called(world: &mut ProviderWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + if !world.state_called("setup", None) { + bail!("provider state callback was not called for setup: {:?}", world.state_calls()); + } + Ok(()) +} + +#[then(regex = r#"^the provider state callback will receive a setup call with "(.*)" as the provider state parameter$"#)] +fn state_setup_with(world: &mut ProviderWorld, step: &Step, state: String) -> anyhow::Result<()> { + traced(step); + if !world.state_called("setup", Some(&state)) { + bail!("no setup call for state '{state}': {:?}", world.state_calls()); + } + Ok(()) +} + +#[then("the provider state callback will be called after the verification is run")] +fn state_teardown_called(world: &mut ProviderWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + if !world.state_called("teardown", None) { + bail!("provider state callback was not called for teardown: {:?}", world.state_calls()); + } + Ok(()) +} + +#[then(regex = r#"^the provider state callback will receive a teardown call "(.*)" as the provider state parameter$"#)] +fn state_teardown_with(world: &mut ProviderWorld, step: &Step, state: String) -> anyhow::Result<()> { + traced(step); + if !world.state_called("teardown", Some(&state)) { + bail!("no teardown call for state '{state}': {:?}", world.state_calls()); + } + Ok(()) +} + +#[then("the provider state callback will NOT receive a teardown call")] +fn state_no_teardown(world: &mut ProviderWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + if world.state_called("teardown", None) { + bail!("provider state callback received a teardown call: {:?}", world.state_calls()); + } + Ok(()) +} + +/// The reference suite does not check this either: the warning only goes to the log. +#[then(regex = r#"^a warning will be displayed that there was no provider state callback configured for provider state "(.*)"$"#)] +fn no_state_callback_warning(_world: &mut ProviderWorld, step: &Step, _state: String) { + traced(step); +} + +#[then(regex = r#"^the request to the provider will contain the header "(.*)"$"#)] +fn provider_request_header(world: &mut ProviderWorld, step: &Step, header: String) -> anyhow::Result<()> { + traced(step); + let (name, value) = header.split_once(':').map(|(k, v)| (k.trim(), v.trim())).ok_or_else(|| anyhow!("bad header"))?; + let requests = world.provider.as_ref().map(|p| p.requests()).unwrap_or_default(); + if requests.is_empty() || !requests.iter().all(|r| r.header(name) == Some(value)) { + bail!("not every provider request had {name}: {value}: {requests:?}"); + } + Ok(()) +} + +fn trace_path(feature: &str, scenario: &str) -> PathBuf { + let dir = env::var("FFI_TRACE_DIR").unwrap_or_else(|_| "target/ffi-trace".into()); + let safe = |s: &str| s.replace(['/', '\\', ':'], "_"); + PathBuf::from(dir).join(safe(feature)).join(format!("{}.md", safe(scenario))) +} + +/// `features/V2/http_provider.feature` -> "v2". +fn feature_version(feature: &cucumber::gherkin::Feature) -> String { + feature.path.as_ref().and_then(|p| p.parent()?.file_name()?.to_str().map(str::to_lowercase)).unwrap_or_default() +} + +#[tokio::main] +async fn main() { + let lib = model::ffi_lib(); + ffi::load(&lib).unwrap_or_else(|e| panic!("could not load {lib}: {e}")); + + ProviderWorld::cucumber() + .max_concurrent_scenarios(1) + .fail_on_skipped() + .before(|feature, _rule, scenario, world| Box::pin(async move { + trace::reset(); + world.version = feature_version(feature); + world.scenario_id = scenario.name.clone(); + let _ = fs::remove_dir_all(world.pact_dir()); + })) + .after(|feature, _rule, scenario, _ev, _world| Box::pin(async move { + let path = trace_path(&format!("{} {}", feature_version(feature).to_uppercase(), feature.name), &scenario.name); + if let Err(e) = trace::write(&path, &feature.name, &scenario.name) { + eprintln!("could not write trace {}: {e}", path.display()); + } + })) + .filter_run_and_exit(model::FEATURES, |feature, _rule, scenario| { + let file = feature.path.as_ref().and_then(|p| p.file_name()?.to_str().map(str::to_string)).unwrap_or_default(); + matches!(feature_version(feature).as_str(), "v1" | "v2" | "v3" | "v4") + && file.ends_with("provider.feature") && !scenario.tags.iter().any(|t| t == "wip") + }) + .await; +}