diff --git a/compatibility-suite-ffi/Cargo.toml b/compatibility-suite-ffi/Cargo.toml index 390006d1d..918353759 100644 --- a/compatibility-suite-ffi/Cargo.toml +++ b/compatibility-suite-ffi/Cargo.toml @@ -46,3 +46,7 @@ harness = false [[test]] name = "plugins" harness = false + +[[test]] +name = "integration_json" +harness = false diff --git a/compatibility-suite-ffi/README.md b/compatibility-suite-ffi/README.md index c7434ebb9..636dd7e64 100644 --- a/compatibility-suite-ffi/README.md +++ b/compatibility-suite-ffi/README.md @@ -38,6 +38,7 @@ cargo test --no-fail-fast | `generators` | V3 `generators` and `http_generators`, V4 `generators` | | `message` | V3 `message_consumer`, V4 `message_consumer`, `synchronous_message_consumer`, `v4` | | `plugins` | V4 `plugins/*`: lifecycle, HTTP, message, synchronous message and transports (needs the matt, csv, avro and protobuf plugins installed) | +| `integration_json` | FFI-only `features/ffi/*`: matching rules defined with integration JSON through `pactffi_with_body` (e.g. `pact:matcher:combine`), which the shared suite can't express as it defines rules in the Pact file format | 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 diff --git a/compatibility-suite-ffi/features/ffi/integration_json.feature b/compatibility-suite-ffi/features/ffi/integration_json.feature new file mode 100644 index 000000000..f66cb35c2 --- /dev/null +++ b/compatibility-suite-ffi/features/ffi/integration_json.feature @@ -0,0 +1,144 @@ +@consumer +Feature: Matching rules combined with OR in integration JSON + FFI consumers (Pact JS, Go, PHP, Python, Ruby, ...) define matching rules by embedding integration JSON in the + bodies they pass to pactffi_with_body. A "pact:matcher:type" array combined with "pact:matcher:combine": "OR" + is written to the Pact file as a single rule list combined with OR, which the V3 and V4 specifications support. + See pact-foundation/pact-reference#249. + + Scenario Outline: Matching rules combined with OR are written to the Pact file + Given a HTTP interaction with a POST request with the following JSON body: + """ + { + "id": { + "pact:matcher:type": [ + { "pact:matcher:type": "regex", "regex": "^\\d+$" }, + { "pact:matcher:type": "regex", "regex": "^[a-z]+$" } + ], + "pact:matcher:combine": "", + "value": "123" + } + } + """ + When the Pact file for the test is generated + Then the request body in the Pact file will be '{"id": "123"}' + And the request body matching rules in the Pact file will be: + """ + { + "$.id": { + "combine": "OR", + "matchers": [ + { "match": "regex", "regex": "^\\d+$" }, + { "match": "regex", "regex": "^[a-z]+$" } + ] + } + } + """ + + Examples: + | spec | combine | + | V3 | OR | + | V4 | OR | + | V3 | or | + + Scenario Outline: The mock server accepts a value matching any of the matching rules combined with OR + Given a HTTP interaction with a POST request with the following JSON body: + """ + { + "id": { + "pact:matcher:type": [ + { "pact:matcher:type": "regex", "regex": "^\\d+$" }, + { "pact:matcher:type": "regex", "regex": "^[a-z]+$" } + ], + "pact:matcher:combine": "OR", + "value": "123" + } + } + """ + When the mock server is started with the interaction + And a POST request is made to the mock server with the JSON body '' + Then the mock server status will be + + Examples: + | spec | body | status | + | V3 | {"id": "123"} | OK | + | V3 | {"id": "abc"} | OK | + | V3 | {"id": "A1"} | NOT OK | + | V4 | {"id": "123"} | OK | + | V4 | {"id": "abc"} | OK | + | V4 | {"id": "A1"} | NOT OK | + + Scenario Outline: The mock server accepts null or an object matching its nested matching rules + Given a HTTP interaction with a POST request with the following JSON body: + """ + { + "address": { + "pact:matcher:type": [ + { "pact:matcher:type": "type" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "OR", + "value": { + "number": { "pact:matcher:type": "integer", "value": 100 }, + "street": { "pact:matcher:type": "type", "value": "Main Street" } + } + } + } + """ + When the mock server is started with the interaction + And a POST request is made to the mock server with the JSON body '' + Then the mock server status will be + + Examples: + | spec | body | status | + | V3 | {"address": {"number": 42, "street": "High Street"}} | OK | + | V3 | {"address": null} | OK | + | V3 | {"address": {"number": "42", "street": "High St"}} | NOT OK | + | V4 | {"address": {"number": 42, "street": "High Street"}} | OK | + | V4 | {"address": null} | OK | + | V4 | {"address": {"number": "42", "street": "High St"}} | NOT OK | + + Scenario: Matching rules combined with OR replace a matcher wrapped as their example value + A path has a single list of rules, so the OR rules replace the wrapped matcher's rule (as Pact-JVM's `or` does) + and only the wrapped matcher's example value is kept. + Given a V4 HTTP interaction with a POST request with the following JSON body: + """ + { + "id": { + "pact:matcher:type": [ + { "pact:matcher:type": "integer" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "OR", + "value": { "pact:matcher:type": "regex", "regex": "^\\d+$", "value": "100" } + } + } + """ + When the Pact file for the test is generated + Then the request body in the Pact file will be '{"id": "100"}' + And the request body matching rules in the Pact file will be: + """ + { + "$.id": { + "combine": "OR", + "matchers": [ { "match": "integer" }, { "match": "null" } ] + } + } + """ + + Scenario: An invalid combine value is rejected + Given a V4 HTTP interaction with a POST request with the following JSON body: + """ + { + "id": { + "pact:matcher:type": [ + { "pact:matcher:type": "integer" }, + { "pact:matcher:type": "null" } + ], + "pact:matcher:combine": "XOR", + "value": 1 + } + } + """ + When the Pact file for the test is generated + Then the request body in the Pact file will be '{"id": null}' + And the request body in the Pact file will have no matching rules diff --git a/compatibility-suite-ffi/tests/integration_json.rs b/compatibility-suite-ffi/tests/integration_json.rs new file mode 100644 index 000000000..892d0fe80 --- /dev/null +++ b/compatibility-suite-ffi/tests/integration_json.rs @@ -0,0 +1,198 @@ +//! FFI-only scenarios: matching rules defined with integration JSON (the format FFI consumers pass to +//! `pactffi_with_body`), which the shared compatibility suite cannot express since it defines matching rules in the +//! Pact file format. + +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 serde_json::Value; + +use pact_ffi_compat::ffi::{self, InteractionHandle, InteractionPart_Request, PactHandle, PactSpecification, + PactSpecification_V3, PactSpecification_V4}; +use pact_ffi_compat::{model, trace}; + +const FEATURES: &str = "features/ffi"; + +#[derive(Debug, Default, World)] +struct IntegrationJsonWorld { + scenario_id: String, + spec: String, + pact: Option, + interaction: Option, + port: Option, + pact_json: Value, +} + +impl IntegrationJsonWorld { + fn specification(&self) -> anyhow::Result { + match self.spec.as_str() { + "V3" => Ok(PactSpecification_V3), + "V4" => Ok(PactSpecification_V4), + s => bail!("unsupported specification {s}"), + } + } + + fn pact_dir(&self) -> PathBuf { + env::current_dir().unwrap().join("target/compatibility-suite/ffi").join(&self.scenario_id) + } + + fn pact(&self) -> anyhow::Result { + self.pact.ok_or_else(|| anyhow!("no pact is being defined")) + } + + fn request(&self) -> &Value { + &self.pact_json["interactions"][0]["request"] + } + + /// The V3 Pact file has the body as JSON, the V4 one as `{"content": ...}`. + fn request_body(&self) -> &Value { + let body = &self.request()["body"]; + if self.spec == "V4" { &body["content"] } else { body } + } + + 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 traced(step: &Step) { + trace::step(&step.keyword, &step.value); +} + +fn docstring(step: &Step) -> anyhow::Result<&str> { + step.docstring.as_deref().ok_or_else(|| anyhow!("step has no doc string")) +} + +#[given(regex = r"^a (V3|V4) HTTP interaction with a POST request with the following JSON body:$")] +fn interaction_with_body(world: &mut IntegrationJsonWorld, step: &Step, spec: String) -> anyhow::Result<()> { + traced(step); + world.spec = spec; + let pact = ffi::new_pact(&format!("{}-integration-json-c", world.spec.to_lowercase()), "p"); + ffi::with_specification(pact, world.specification()?); + let i = ffi::new_interaction(pact, "a request with integration JSON"); + ffi::with_request(i, "POST", "/path"); + if !ffi::with_body(i, InteractionPart_Request, "application/json", docstring(step)?) { + bail!("pactffi_with_body failed"); + } + ffi::response_status(i, 200); + world.pact = Some(pact); + world.interaction = Some(i); + Ok(()) +} + +#[when("the Pact file for the test is generated")] +fn pact_generated(world: &mut IntegrationJsonWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let dir = world.pact_dir(); + fs::create_dir_all(&dir)?; + let rc = ffi::pact_handle_write_file(world.pact()?, &dir.to_string_lossy(), true); + if rc != 0 { + bail!("pactffi_pact_handle_write_file failed with {rc}"); + } + let file = fs::read_dir(&dir)?.next().ok_or_else(|| anyhow!("no pact file written"))??.path(); + world.pact_json = serde_json::from_str(&fs::read_to_string(file)?)?; + Ok(()) +} + +#[when("the mock server is started with the interaction")] +fn mock_server_started(world: &mut IntegrationJsonWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let port = ffi::create_mock_server_for_transport(world.pact()?, "::1", 0, "http"); + if port < 0 { + bail!("pactffi_create_mock_server_for_transport failed with {port}"); + } + world.port = Some(port); + Ok(()) +} + +#[when(regex = r"^a POST request is made to the mock server with the JSON body '(.*)'$")] +async fn request_made(world: &mut IntegrationJsonWorld, step: &Step, body: String) -> anyhow::Result<()> { + traced(step); + let port = world.port.ok_or_else(|| anyhow!("mock server not started"))?; + let url = format!("http://[::1]:{port}/path"); + let res = reqwest::Client::new().post(&url).header("content-type", "application/json").body(body).send().await?; + trace::note(format!("HTTP POST {url} -> {}", res.status())); + Ok(()) +} + +#[then(regex = r"^the mock server status will be (OK|NOT OK)$")] +fn mock_server_status(world: &mut IntegrationJsonWorld, step: &Step, status: String) -> anyhow::Result<()> { + traced(step); + let port = world.port.ok_or_else(|| anyhow!("mock server not started"))?; + let matched = ffi::mock_server_matched(port); + let mismatches = ffi::mock_server_mismatches(port).unwrap_or_default(); + match (status.as_str(), matched) { + ("OK", false) => bail!("Expected the mock server to match, but it had mismatches: {mismatches}"), + ("NOT OK", true) => bail!("Expected the mock server to have mismatches, but it matched"), + _ => Ok(()), + } +} + +#[then(regex = r"^the request body in the Pact file will be '(.*)'$")] +fn request_body(world: &mut IntegrationJsonWorld, step: &Step, expected: String) -> anyhow::Result<()> { + traced(step); + let expected: Value = serde_json::from_str(&expected)?; + let actual = world.request_body(); + if *actual != expected { + bail!("Expected the request body to be {expected} but was {actual}"); + } + Ok(()) +} + +#[then("the request body matching rules in the Pact file will be:")] +fn request_body_rules(world: &mut IntegrationJsonWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let expected: Value = serde_json::from_str(docstring(step)?)?; + let actual = &world.request()["matchingRules"]["body"]; + if *actual != expected { + bail!("Expected the request body matching rules to be {expected} but were {actual}"); + } + Ok(()) +} + +#[then("the request body in the Pact file will have no matching rules")] +fn no_request_body_rules(world: &mut IntegrationJsonWorld, step: &Step) -> anyhow::Result<()> { + traced(step); + let rules = &world.request()["matchingRules"]["body"]; + if !(rules.is_null() || rules.as_object().is_some_and(|o| o.is_empty())) { + bail!("Expected no request body matching rules but found {rules}"); + } + Ok(()) +} + +#[tokio::main] +async fn main() { + let lib = model::ffi_lib(); + ffi::load(&lib).unwrap_or_else(|e| panic!("could not load {lib}: {e}")); + + IntegrationJsonWorld::cucumber() + .max_concurrent_scenarios(1) + .fail_on_skipped() + .before(|_feature, _rule, scenario, world| Box::pin(async move { + trace::reset(); + world.scenario_id = scenario.name.replace(['/', '\\', ':'], "_"); + 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 dir = env::var("FFI_TRACE_DIR").unwrap_or_else(|_| "target/ffi-trace".into()); + let path = PathBuf::from(dir).join(format!("FFI {}", feature.name)) + .join(format!("{}.md", scenario.name.replace(['/', '\\', ':'], "_"))); + if let Err(e) = trace::write(&path, &feature.name, &scenario.name) { + eprintln!("could not write trace {}: {e}", path.display()); + } + })) + .filter_run_and_exit(FEATURES, |_feature, _rule, scenario| !scenario.tags.iter().any(|t| t == "wip")) + .await; +} diff --git a/compatibility-suite/pact-compatibility-suite/features/V3/matching_rules.feature b/compatibility-suite/pact-compatibility-suite/features/V3/matching_rules.feature index ec9af8e64..6b3b4caf3 100644 --- a/compatibility-suite/pact-compatibility-suite/features/V3/matching_rules.feature +++ b/compatibility-suite/pact-compatibility-suite/features/V3/matching_rules.feature @@ -269,3 +269,89 @@ Feature: V3 era Matching Rules When the request is compared to the expected one Then the comparison should NOT be OK And the mismatches will contain a mismatch with error "$.four" -> "Expected 100 (Integer) to be the same type as 'a' (String)" + + Scenario: Supports matching rules combined with OR (positive case) + Given an expected request configured with the following: + | body | matching rules | + | file: basic.json | or-regex-matcher-v3.json | + And the following requests are received: + | body | desc | + | JSON: { "one": "100", "two": "b" } | matches the first rule | + | JSON: { "one": "abc", "two": "b" } | matches the second rule | + When the requests are compared to the expected one + Then the comparison should be OK + + Scenario: Supports matching rules combined with OR (negative case) + Given an expected request configured with the following: + | body | matching rules | + | file: basic.json | or-regex-matcher-v3.json | + And a request is received with the following: + | body | + | JSON: { "one": "A1", "two": "b" } | + When the request is compared to the expected one + Then the comparison should NOT be OK + And the mismatches will contain a mismatch with error "$.one" -> "Expected 'A1' to match '^\d+$'" + And the mismatches will contain a mismatch with error "$.one" -> "Expected 'A1' to match '^[a-z]+$'" + + Scenario: Supports an integer or decimal matcher combined with OR (positive case) + Given an expected request configured with the following: + | body | matching rules | + | file: basic.json | or-number-matcher-v3.json | + And the following requests are received: + | body | desc | + | JSON: { "one": 100, "two": "b" } | integer | + | JSON: { "one": 100.25, "two": "b" } | decimal | + When the requests are compared to the expected one + Then the comparison should be OK + + Scenario: Supports an integer or decimal matcher combined with OR (negative case) + Given an expected request configured with the following: + | body | matching rules | + | file: basic.json | or-number-matcher-v3.json | + And a request is received with the following: + | body | + | JSON: { "one": true, "two": "b" } | + When the request is compared to the expected one + Then the comparison should NOT be OK + + Scenario: Supports a type matcher combined with a null matcher with OR (positive case) + Given an expected request configured with the following: + | body | matching rules | + | file: 3-level.json | or-null-matcher-v3.json | + And the following requests are received: + | body | desc | + | JSON: { "one": { "a": { "ids": [1], "status": "OK" } }, "two": [ { "ids": [1], "status": "BAD" } ] } | an object | + | JSON: { "one": null, "two": [ { "ids": [1], "status": "BAD" } ] } | null | + When the requests are compared to the expected one + Then the comparison should be OK + + Scenario: Supports a type matcher combined with a null matcher with OR (negative case) + Given an expected request configured with the following: + | body | matching rules | + | file: 3-level.json | or-null-matcher-v3.json | + And a request is received with the following: + | body | + | JSON: { "one": "a string", "two": [ { "ids": [1], "status": "BAD" } ] } | + When the request is compared to the expected one + Then the comparison should NOT be OK + + Scenario: Supports header and query matching rules combined with OR (positive case) + Given an expected request configured with the following: + | query | headers | matching rules | + | a=1234 | 'X-TEST: 1234' | or-matcher-header-query-v3.json | + And the following requests are received: + | query | headers | desc | + | a=100 | 'X-TEST: 100' | matches the first rule | + | a=ABC | 'X-TEST: ABC' | matches the second rule | + When the requests are compared to the expected one + Then the comparison should be OK + + Scenario: Supports header and query matching rules combined with OR (negative case) + Given an expected request configured with the following: + | query | headers | matching rules | + | a=1234 | 'X-TEST: 1234' | or-matcher-header-query-v3.json | + And a request is received with the following: + | query | headers | + | a=abc | 'X-TEST: abc' | + When the request is compared to the expected one + Then the comparison should NOT be OK diff --git a/compatibility-suite/pact-compatibility-suite/features/V4/matching_rules.feature b/compatibility-suite/pact-compatibility-suite/features/V4/matching_rules.feature index a20ce3e04..1bab7b39e 100644 --- a/compatibility-suite/pact-compatibility-suite/features/V4/matching_rules.feature +++ b/compatibility-suite/pact-compatibility-suite/features/V4/matching_rules.feature @@ -155,3 +155,33 @@ Feature: V4 era Matching Rules When the request is compared to the expected one Then the comparison should NOT be OK And the mismatches will contain a mismatch with error "$.actions" -> "Variant at index 1 ({\"href\":\"http://api.x.io/orders/42/items\",\"method\":\"DELETE\",\"name\":\"delete-item\",\"title\":\"Delete Item\"}) was not found in the actual list" + + Scenario: Supports a not empty matcher combined with a null matcher with OR (positive case) + Given an expected request configured with the following: + | body | matching rules | + | file: basic.json | or-notempty-matcher-v4.json | + And a request is received with the following: + | body | + | JSON: { "one": "a", "two": "b" } | + When the request is compared to the expected one + Then the comparison should be OK + + Scenario: Supports a not empty matcher combined with a null matcher with OR (positive case, null value) + Given an expected request configured with the following: + | body | matching rules | + | file: basic.json | or-notempty-matcher-v4.json | + And a request is received with the following: + | body | + | JSON: { "one": null, "two": "b" } | + When the request is compared to the expected one + Then the comparison should be OK + + Scenario: Supports a not empty matcher combined with a null matcher with OR (negative case) + Given an expected request configured with the following: + | body | matching rules | + | file: basic.json | or-notempty-matcher-v4.json | + And a request is received with the following: + | body | + | JSON: { "one": "", "two": "b" } | + When the request is compared to the expected one + Then the comparison should NOT be OK diff --git a/compatibility-suite/pact-compatibility-suite/fixtures/or-matcher-header-query-v3.json b/compatibility-suite/pact-compatibility-suite/fixtures/or-matcher-header-query-v3.json new file mode 100644 index 000000000..31846873a --- /dev/null +++ b/compatibility-suite/pact-compatibility-suite/fixtures/or-matcher-header-query-v3.json @@ -0,0 +1,32 @@ +{ + "header": { + "X-TEST": { + "combine": "OR", + "matchers": [ + { + "match": "regex", + "regex": "^\\d+$" + }, + { + "match": "regex", + "regex": "^[A-Z]+$" + } + ] + } + }, + "query": { + "a": { + "combine": "OR", + "matchers": [ + { + "match": "regex", + "regex": "^\\d+$" + }, + { + "match": "regex", + "regex": "^[A-Z]+$" + } + ] + } + } +} diff --git a/compatibility-suite/pact-compatibility-suite/fixtures/or-notempty-matcher-v4.json b/compatibility-suite/pact-compatibility-suite/fixtures/or-notempty-matcher-v4.json new file mode 100644 index 000000000..49a8fceb3 --- /dev/null +++ b/compatibility-suite/pact-compatibility-suite/fixtures/or-notempty-matcher-v4.json @@ -0,0 +1,15 @@ +{ + "body": { + "$.one": { + "combine": "OR", + "matchers": [ + { + "match": "notEmpty" + }, + { + "match": "null" + } + ] + } + } +} diff --git a/compatibility-suite/pact-compatibility-suite/fixtures/or-null-matcher-v3.json b/compatibility-suite/pact-compatibility-suite/fixtures/or-null-matcher-v3.json new file mode 100644 index 000000000..54ea9c1f0 --- /dev/null +++ b/compatibility-suite/pact-compatibility-suite/fixtures/or-null-matcher-v3.json @@ -0,0 +1,15 @@ +{ + "body": { + "$.one": { + "combine": "OR", + "matchers": [ + { + "match": "type" + }, + { + "match": "null" + } + ] + } + } +} diff --git a/compatibility-suite/pact-compatibility-suite/fixtures/or-number-matcher-v3.json b/compatibility-suite/pact-compatibility-suite/fixtures/or-number-matcher-v3.json new file mode 100644 index 000000000..66848bb19 --- /dev/null +++ b/compatibility-suite/pact-compatibility-suite/fixtures/or-number-matcher-v3.json @@ -0,0 +1,15 @@ +{ + "body": { + "$.one": { + "combine": "OR", + "matchers": [ + { + "match": "integer" + }, + { + "match": "decimal" + } + ] + } + } +} diff --git a/compatibility-suite/pact-compatibility-suite/fixtures/or-regex-matcher-v3.json b/compatibility-suite/pact-compatibility-suite/fixtures/or-regex-matcher-v3.json new file mode 100644 index 000000000..56ca4663d --- /dev/null +++ b/compatibility-suite/pact-compatibility-suite/fixtures/or-regex-matcher-v3.json @@ -0,0 +1,17 @@ +{ + "body": { + "$.one": { + "combine": "OR", + "matchers": [ + { + "match": "regex", + "regex": "^\\d+$" + }, + { + "match": "regex", + "regex": "^[a-z]+$" + } + ] + } + } +}