diff --git a/compatibility-suite/Cargo.toml b/compatibility-suite/Cargo.toml index 5f7f6f79b..4798f3b8c 100644 --- a/compatibility-suite/Cargo.toml +++ b/compatibility-suite/Cargo.toml @@ -15,7 +15,7 @@ maplit = "1.0.2" pact_consumer = { path = "../rust/pact_consumer" } pact_models = { version = "1.3.16" } pact_matching = { version = "2.0.11" } -pact_mock_server = { version = "2.2.6" } +pact_mock_server = { version = "2.2.7" } pact_verifier = { path = "../rust/pact_verifier" } regex = "1.10.2" reqwest = { version = "0.13.4", default-features = false, features = ["json"] } diff --git a/compatibility-suite/pact-compatibility-suite/.github/renovate.json b/compatibility-suite/pact-compatibility-suite/.github/renovate.json index def7a3722..c664bf19f 100644 --- a/compatibility-suite/pact-compatibility-suite/.github/renovate.json +++ b/compatibility-suite/pact-compatibility-suite/.github/renovate.json @@ -1,7 +1,10 @@ { "$schema": "https://docs.renovatebot.com/renovate-schema.json", - "extends": ["config:best-practices"], + "extends": [ + "config:best-practices" + ], "prHourlyLimit": 0, "prConcurrentLimit": 0, + "rebaseWhen": "conflicted", "automerge": true -} \ No newline at end of file +} diff --git a/compatibility-suite/pact-compatibility-suite/.github/workflows/smartbear-issue-label-added.yml b/compatibility-suite/pact-compatibility-suite/.github/workflows/smartbear-issue-label-added.yml deleted file mode 100644 index 8b68fed74..000000000 --- a/compatibility-suite/pact-compatibility-suite/.github/workflows/smartbear-issue-label-added.yml +++ /dev/null @@ -1,11 +0,0 @@ -name: SmartBear Supported Issue Label Added - -on: - issues: - types: - - labeled - -jobs: - call-workflow: - uses: pact-foundation/.github/.github/workflows/smartbear-issue-label-added.yml@master - secrets: inherit diff --git a/compatibility-suite/pact-compatibility-suite/.github/workflows/triage.yml b/compatibility-suite/pact-compatibility-suite/.github/workflows/triage.yml deleted file mode 100644 index eb5ec3054..000000000 --- a/compatibility-suite/pact-compatibility-suite/.github/workflows/triage.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: Triage Issue - -on: - issues: - types: - - opened - - labeled - pull_request: - types: - - labeled - -jobs: - call-workflow: - uses: pact-foundation/.github/.github/workflows/triage.yml@master - secrets: inherit diff --git a/compatibility-suite/pact-compatibility-suite/features/V4/http_body_content_type.feature b/compatibility-suite/pact-compatibility-suite/features/V4/http_body_content_type.feature new file mode 100644 index 000000000..d70e9d92f --- /dev/null +++ b/compatibility-suite/pact-compatibility-suite/features/V4/http_body_content_type.feature @@ -0,0 +1,62 @@ +Feature: V4 body content type without a Content-Type header + A V4 body records its own content type, so an interaction can have a typed body without a Content-Type header. + The body content type decides how the body is compared, even when the received request has no Content-Type header + and its body would be sniffed as something else. The Content-Type header is only an expectation when it is in the + interaction's headers. + + Scenario: Typed body, request sent with no Content-Type header + Given an expected request configured with the following: + | body | content type | + | file: sample.pdf | application/octet-stream | + And the "content-type" header is removed from the expected request + And a request is received with the following: + | body | + | file: sample.pdf | + And the "content-type" header is removed from the received request + When the request is compared to the expected one + Then the comparison should be OK + + Scenario: Typed body, request sent with a different body and no Content-Type header + Given an expected request configured with the following: + | body | content type | + | file: sample.pdf | application/octet-stream | + And the "content-type" header is removed from the expected request + And a request is received with the following: + | body | + | file: rat.jpg | + And the "content-type" header is removed from the received request + When the request is compared to the expected one + Then the comparison should NOT be OK + + Scenario: Typed body, request sent with a matching Content-Type header + Given an expected request configured with the following: + | body | content type | + | file: sample.pdf | application/octet-stream | + And the "content-type" header is removed from the expected request + And a request is received with the following: + | body | content type | + | file: sample.pdf | application/octet-stream | + When the request is compared to the expected one + Then the comparison should be OK + + Scenario: Typed body, request sent with a Content-Type header that declares a different type + Given an expected request configured with the following: + | body | content type | + | file: sample.pdf | application/octet-stream | + And the "content-type" header is removed from the expected request + And a request is received with the following: + | body | content type | + | file: sample.pdf | application/json | + When the request is compared to the expected one + Then the comparison should NOT be OK + + Scenario: The Content-Type header is still required when it is in the interaction + Given an expected request configured with the following: + | body | content type | + | file: sample.pdf | application/octet-stream | + And a request is received with the following: + | body | + | file: sample.pdf | + And the "content-type" header is removed from the received request + 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/http_indexed_generators.feature b/compatibility-suite/pact-compatibility-suite/features/V4/http_indexed_generators.feature new file mode 100644 index 000000000..355f003c6 --- /dev/null +++ b/compatibility-suite/pact-compatibility-suite/features/V4/http_indexed_generators.feature @@ -0,0 +1,92 @@ +Feature: Generators for each value of a header or query parameter + A generator key in the header or query category can carry a value index, written as a path: $.name[1] or + $['name'][1]. An indexed generator applies only to that value, and runs after the generator for the name. A key + without the index applies to every value, and adds the header or query parameter with a single generated value if + it is not there. Header names are matched without regard to case. A key without the leading $ is a plain name, so + ids[0] is the parameter named "ids[0]". The headers column is a JSON object of a name to a list of values, and the + expected values are a JSON list. + + Background: + Given the generator test mode is set as "Provider" + + Scenario: A query generator for the name applies to every value + Given a request configured with the following generators: + | query | generators | + | a=1&a=2 | JSON: { "query": { "a": { "type": "ProviderState", "expression": "${id}" } } } | + When the request is prepared for use with a "providerState" context: + | { "id": "X" } | + Then the request query parameter "a" will be ["X", "X"] + + Scenario: An indexed query generator only applies to its value + Given a request configured with the following generators: + | query | generators | + | a=1&a=2&a=3 | JSON: { "query": { "$.a[1]": { "type": "ProviderState", "expression": "${id}" } } } | + When the request is prepared for use with a "providerState" context: + | { "id": "X" } | + Then the request query parameter "a" will be ["1", "X", "3"] + + Scenario: An indexed query generator runs after the generator for the name + Given a request configured with the following generators: + | query | generators | + | a=1&a=2 | JSON: { "query": { "$.a[0]": { "type": "ProviderState", "expression": "${first}" }, "a": { "type": "ProviderState", "expression": "${all}" } } } | + When the request is prepared for use with a "providerState" context: + | { "first": "F", "all": "A" } | + Then the request query parameter "a" will be ["F", "A"] + + Scenario: An indexed query generator for a value that is not there is ignored + Given a request configured with the following generators: + | query | generators | + | a=1 | JSON: { "query": { "$.a[3]": { "type": "ProviderState", "expression": "${id}" } } } | + When the request is prepared for use with a "providerState" context: + | { "id": "X" } | + Then the request query parameter "a" will be ["1"] + + Scenario: A query generator key without the leading $ is a plain parameter name + Given a request configured with the following generators: + | query | generators | + | ids=1&ids[0]=2 | JSON: { "query": { "ids[0]": { "type": "ProviderState", "expression": "${id}" } } } | + When the request is prepared for use with a "providerState" context: + | { "id": "X" } | + Then the request query parameter "ids" will be ["1"] + And the request query parameter "ids[0]" will be ["X"] + + Scenario: A query generator for a parameter that is not there generates a single value + Given a request configured with the following generators: + | query | generators | + | a=1 | JSON: { "query": { "id": { "type": "ProviderState", "expression": "${id}" } } } | + When the request is prepared for use with a "providerState" context: + | { "id": "X" } | + Then the request query parameter "a" will be ["1"] + And the request query parameter "id" will be ["X"] + + Scenario: A header generator for the name applies to every value + Given a request configured with the following generators: + | headers | generators | + | { "X-Request": ["a", "b"] } | JSON: { "header": { "X-Request": { "type": "ProviderState", "expression": "${id}" } } } | + When the request is prepared for use with a "providerState" context: + | { "id": "X" } | + Then the request header "X-Request" will be ["X", "X"] + + Scenario: An indexed header generator only applies to its value + Given a request configured with the following generators: + | headers | generators | + | { "X-Request": ["a", "b", "c"] } | JSON: { "header": { "$['X-Request'][1]": { "type": "ProviderState", "expression": "${id}" } } } | + When the request is prepared for use with a "providerState" context: + | { "id": "X" } | + Then the request header "X-Request" will be ["a", "X", "c"] + + Scenario: Header generators match the header name without regard to case + Given a request configured with the following generators: + | headers | generators | + | { "X-Request": ["a", "b"] } | JSON: { "header": { "x-request": { "type": "ProviderState", "expression": "${all}" }, "$['X-REQUEST'][1]": { "type": "ProviderState", "expression": "${second}" } } } | + When the request is prepared for use with a "providerState" context: + | { "all": "A", "second": "S" } | + Then the request header "X-Request" will be ["A", "S"] + + Scenario: A header generator for a header that is not there generates a single value + Given a request configured with the following generators: + | generators | + | JSON: { "header": { "X-Id": { "type": "ProviderState", "expression": "${id}" } } } | + When the request is prepared for use with a "providerState" context: + | { "id": "X" } | + Then the request header "X-Id" will be ["X"] diff --git a/compatibility-suite/pact-compatibility-suite/features/V4/http_indexed_rules.feature b/compatibility-suite/pact-compatibility-suite/features/V4/http_indexed_rules.feature new file mode 100644 index 000000000..90ff68c6a --- /dev/null +++ b/compatibility-suite/pact-compatibility-suite/features/V4/http_indexed_rules.feature @@ -0,0 +1,115 @@ +Feature: Matching rules for each value of a header or query parameter + Headers and query parameters are a list of values for each name. A matching rule key in the header or query + category can carry a value index, written as a path: $.name[1] or $['name'][1]. An indexed rule applies only to + that value, and overrides the rule for the name for that value. A key without the index applies to every value. + The headers column is a JSON object of a name to a list of values, so values can contain commas. + + Scenario: An indexed query rule only applies to its value (positive case) + Given an expected request configured with the following: + | query | matching rules | + | a=x&a=100 | JSON: { "query": { "$.a[1]": { "matchers": [{ "match": "regex", "regex": "^[0-9]+$" }] } } } | + And a request is received with the following: + | query | + | a=x&a=42 | + When the request is compared to the expected one + Then the comparison should be OK + + Scenario: An indexed query rule only applies to its value (negative case) + Given an expected request configured with the following: + | query | matching rules | + | a=x&a=100 | JSON: { "query": { "$.a[1]": { "matchers": [{ "match": "regex", "regex": "^[0-9]+$" }] } } } | + And a request is received with the following: + | query | + | a=x&a=abc | + When the request is compared to the expected one + Then the comparison should NOT be OK + + Scenario: Values without an indexed query rule are compared for equality + Given an expected request configured with the following: + | query | matching rules | + | a=x&a=100 | JSON: { "query": { "$.a[1]": { "matchers": [{ "match": "regex", "regex": "^[0-9]+$" }] } } } | + And a request is received with the following: + | query | + | a=y&a=42 | + When the request is compared to the expected one + Then the comparison should NOT be OK + + Scenario: An indexed query rule overrides the rule for the name for that value (positive case) + Given an expected request configured with the following: + | query | matching rules | + | a=x&a=100 | JSON: { "query": { "a": { "matchers": [{ "match": "regex", "regex": "^[a-z]+$" }] }, "$.a[1]": { "matchers": [{ "match": "regex", "regex": "^[0-9]+$" }] } } } | + And a request is received with the following: + | query | + | a=y&a=42 | + When the request is compared to the expected one + Then the comparison should be OK + + Scenario: An indexed query rule overrides the rule for the name for that value (negative case) + Given an expected request configured with the following: + | query | matching rules | + | a=x&a=100 | JSON: { "query": { "a": { "matchers": [{ "match": "regex", "regex": "^[a-z]+$" }] }, "$.a[1]": { "matchers": [{ "match": "regex", "regex": "^[0-9]+$" }] } } } | + And a request is received with the following: + | query | + | a=y&a=z | + When the request is compared to the expected one + Then the comparison should NOT be OK + + Scenario: A query parameter name with brackets is a plain name + Given an expected request configured with the following: + | query | matching rules | + | ids[0]=100 | JSON: { "query": { "ids[0]": { "matchers": [{ "match": "regex", "regex": "^[0-9]+$" }] } } } | + And a request is received with the following: + | query | + | ids[0]=42 | + When the request is compared to the expected one + Then the comparison should be OK + + Scenario: An indexed header rule only applies to its value (positive case) + Given an expected request configured with the following: + | headers | matching rules | + | { "X-Request": ["a", "100"] } | JSON: { "header": { "$['X-Request'][1]": { "matchers": [{ "match": "regex", "regex": "^[0-9]+$" }] } } } | + And a request is received with the following: + | headers | + | { "X-Request": ["a", "42"] } | + When the request is compared to the expected one + Then the comparison should be OK + + Scenario: An indexed header rule only applies to its value (negative case) + Given an expected request configured with the following: + | headers | matching rules | + | { "X-Request": ["a", "100"] } | JSON: { "header": { "$['X-Request'][1]": { "matchers": [{ "match": "regex", "regex": "^[0-9]+$" }] } } } | + And a request is received with the following: + | headers | + | { "X-Request": ["a", "abc"] } | + When the request is compared to the expected one + Then the comparison should NOT be OK + + Scenario: An indexed header rule overrides the rule for the name for that value + Given an expected request configured with the following: + | headers | matching rules | + | { "X-Request": ["a", "100"] } | JSON: { "header": { "X-Request": { "matchers": [{ "match": "regex", "regex": "^[a-z]+$" }] }, "$['X-Request'][1]": { "matchers": [{ "match": "regex", "regex": "^[0-9]+$" }] } } } | + And a request is received with the following: + | headers | + | { "X-Request": ["b", "42"] } | + When the request is compared to the expected one + Then the comparison should be OK + + Scenario: Header names in indexed rule keys are not case sensitive + Given an expected request configured with the following: + | headers | matching rules | + | { "X-Request": ["a", "100"] } | JSON: { "header": { "$['x-request'][1]": { "matchers": [{ "match": "regex", "regex": "^[0-9]+$" }] } } } | + And a request is received with the following: + | headers | + | { "x-request": ["a", "42"] } | + When the request is compared to the expected one + Then the comparison should be OK + + Scenario: Header values can contain commas + Given an expected request configured with the following: + | headers | matching rules | + | { "X-Request": ["a", "Tue, 01 Jan 2030 10:00:00 GMT"] } | JSON: { "header": { "$['X-Request'][1]": { "matchers": [{ "match": "regex", "regex": "^[A-Z][a-z]{2}, .* GMT$" }] } } } | + And a request is received with the following: + | headers | + | { "X-Request": ["a", "Wed, 02 Jan 2030 11:00:00 GMT"] } | + When the request is compared to the expected one + Then the comparison should be OK diff --git a/compatibility-suite/tests/v4_steps/generators.rs b/compatibility-suite/tests/v4_steps/generators.rs index 105a7193b..34bb96fbd 100644 --- a/compatibility-suite/tests/v4_steps/generators.rs +++ b/compatibility-suite/tests/v4_steps/generators.rs @@ -9,6 +9,7 @@ use maplit::hashmap; use pact_models::generators::{Generators, GeneratorTestMode}; use pact_models::json_utils::json_to_string; use pact_models::path_exp::DocPath; +use pact_models::query_strings::parse_query_string; use pact_models::v4::http_parts::HttpRequest; use serde_json::Value; @@ -30,6 +31,13 @@ fn a_request_configured_with_the_following_generators(world: &mut V4World, step: if let Some(field) = headers.get(index) { match field.as_str() { "body" => setup_body(value, &mut request, None), + "query" => request.query = parse_query_string(value), + "headers" => { + // A JSON object of a name to a list of values, so that values can contain commas + let headers: HashMap> = serde_json::from_str(value) + .expect("headers must be a JSON object of a name to a list of values"); + request.headers = Some(headers); + } "generators" => { let json: Value = if value.starts_with("JSON:") { serde_json::from_str(value.strip_prefix("JSON:").unwrap_or(value).trim()).unwrap() @@ -153,3 +161,37 @@ fn the_body_value_for_will_have_been_replaced_with_a_value( assert_value_type(value_type, element) } + +#[then(expr = "the request query parameter {string} will be {}")] +fn the_request_query_parameter_will_be( + world: &mut V4World, + name: String, + values: String +) -> anyhow::Result<()> { + let expected: Vec = serde_json::from_str(values.as_str())?; + let actual = world.generated_request.query.as_ref() + .and_then(|query| query.get(&name)) + .map(|values| values.iter().map(|v| v.clone().unwrap_or_default()).collect::>()); + if actual.as_ref() == Some(&expected) { + Ok(()) + } else { + Err(anyhow!("Expected query parameter {} to be {:?} but was {:?}", name, expected, actual)) + } +} + +#[then(expr = "the request header {string} will be {}")] +fn the_request_header_will_be( + world: &mut V4World, + name: String, + values: String +) -> anyhow::Result<()> { + let expected: Vec = serde_json::from_str(values.as_str())?; + let actual = world.generated_request.headers.as_ref() + .and_then(|headers| headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name.as_str()))) + .map(|(_, values)| values.clone()); + if actual.as_ref() == Some(&expected) { + Ok(()) + } else { + Err(anyhow!("Expected header {} to be {:?} but was {:?}", name, expected, actual)) + } +} diff --git a/compatibility-suite/tests/v4_steps/http_matching.rs b/compatibility-suite/tests/v4_steps/http_matching.rs index feeed8569..44bbae620 100644 --- a/compatibility-suite/tests/v4_steps/http_matching.rs +++ b/compatibility-suite/tests/v4_steps/http_matching.rs @@ -1,3 +1,4 @@ +use std::collections::HashMap; use std::fs::File; use std::io::BufReader; @@ -5,9 +6,11 @@ use anyhow::anyhow; use cucumber::gherkin::Step; use cucumber::{given, then, when}; use maplit::hashmap; +use pact_models::bodies::OptionalBody; use pact_models::interaction::Interaction; use pact_models::matchingrules::matchers_from_json; use pact_models::pact::Pact; +use pact_models::query_strings::parse_query_string; use pact_models::v4::http_parts::{HttpRequest, HttpResponse}; use pact_models::v4::synch_http::SynchronousHttp; use serde_json::{json, Value}; @@ -106,6 +109,18 @@ fn the_response_mismatches_will_contain_a_mismatch_with_error( } } +fn setup_query_and_headers(request: &mut HttpRequest, data: &HashMap<&str, &String>) { + if let Some(query) = data.get("query") { + request.query = parse_query_string(query); + } + if let Some(headers) = data.get("headers") { + // A JSON object of a name to a list of values, so that values can contain commas + let headers: HashMap> = serde_json::from_str(headers) + .expect("headers must be a JSON object of a name to a list of values"); + request.headers.get_or_insert_with(HashMap::new).extend(headers); + } +} + #[given(expr = "an expected request configured with the following:")] fn an_expected_request_configured_with_the_following(world: &mut V4World, step: &Step) { if let Some(table) = step.table.as_ref() { @@ -120,6 +135,7 @@ fn an_expected_request_configured_with_the_following(world: &mut V4World, step: if let Some(body) = data.get("body") { setup_body(body, &mut world.expected_request, data.get("content type").map(|ct| ct.as_str())); } + setup_query_and_headers(&mut world.expected_request, &data); if let Some(value) = data.get("matching rules") { let json: Value = if value.starts_with("JSON:") { @@ -153,10 +169,32 @@ fn a_request_is_received_with_the_following(world: &mut V4World, step: &Step) { if let Some(body) = data.get("body") { setup_body(body, &mut request, data.get("content type").map(|ct| ct.as_str())); } + setup_query_and_headers(&mut request, &data); } world.received_requests.push(request); } +#[given(expr = "the {string} header is removed from the expected request")] +fn the_header_is_removed_from_the_expected_request(world: &mut V4World, name: String) { + remove_header(&mut world.expected_request, &name); +} + +#[given(expr = "the {string} header is removed from the received request")] +fn the_header_is_removed_from_the_received_request(world: &mut V4World, name: String) { + let request = world.received_requests.last_mut().unwrap(); + remove_header(request, &name); + // A real request without a Content-Type header has a body with no known content type + if let OptionalBody::Present(body, _, _) = &request.body { + request.body = OptionalBody::Present(body.clone(), None, None); + } +} + +fn remove_header(request: &mut HttpRequest, name: &str) { + if let Some(headers) = request.headers.as_mut() { + headers.retain(|key, _| !key.eq_ignore_ascii_case(name)); + } +} + #[when("the request is compared to the expected one")] async fn the_request_is_compared_to_the_expected_one(world: &mut V4World) { world.request_results.push( diff --git a/rust/Cargo.lock b/rust/Cargo.lock index a86bcedc0..b41b87cb1 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -2915,7 +2915,7 @@ dependencies = [ [[package]] name = "pact_ffi" -version = "0.5.12" +version = "0.5.13" dependencies = [ "ansi_term", "anyhow", @@ -2965,7 +2965,7 @@ dependencies = [ [[package]] name = "pact_matching" -version = "2.1.0" +version = "2.2.0" dependencies = [ "ansi_term", "anyhow", @@ -3019,8 +3019,8 @@ dependencies = [ [[package]] name = "pact_mock_server" -version = "2.2.6" -source = "git+https://github.com/pact-foundation/pact-core-mock-server.git#427966c8a756585a171ddda4a2cdc8f02e88e333" +version = "2.2.7" +source = "git+https://github.com/pact-foundation/pact-core-mock-server.git#cb03341e8bb6c12163ae361a0b2e268e45b60d14" dependencies = [ "anyhow", "bytes", @@ -3049,7 +3049,7 @@ dependencies = [ [[package]] name = "pact_models" -version = "1.3.17" +version = "1.3.18" dependencies = [ "anyhow", "ariadne", @@ -3097,7 +3097,7 @@ dependencies = [ [[package]] name = "pact_verifier" -version = "1.5.0" +version = "1.6.0" dependencies = [ "ansi_term", "anyhow", @@ -3145,7 +3145,7 @@ dependencies = [ [[package]] name = "pact_verifier_cli" -version = "1.4.0" +version = "1.5.1" dependencies = [ "ansi_term", "anyhow", @@ -3600,9 +3600,9 @@ dependencies = [ [[package]] name = "qualname" -version = "0.0.1" +version = "0.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7ca141ff6dd6af1bf241aa43eac7491d69c9be5059574708495e61948ab4bac" +checksum = "5b7e17688d7e871b907a1d869d01a72e13da2f235e47edd88e003610f26ec7a8" [[package]] name = "quick-xml" @@ -5864,9 +5864,9 @@ dependencies = [ [[package]] name = "xrust" -version = "2.2.0" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fb2c761645855d610598e85a199f9e86f805cf6d0d526b26cfedf38582b299f" +checksum = "11e0eacb58c190372d2d26a8716969b53e72ef30e8769748c8cb989cb874a3cd" dependencies = [ "chrono", "english-numbers", diff --git a/rust/pact_consumer/Cargo.toml b/rust/pact_consumer/Cargo.toml index 3d8853bde..a3cd3db75 100644 --- a/rust/pact_consumer/Cargo.toml +++ b/rust/pact_consumer/Cargo.toml @@ -28,8 +28,8 @@ async-trait = "0.1.91" bytes = "1.12.1" itertools = "0.15.0" maplit = "1.0.2" -pact_matching = { version = "2.1.0", path = "../pact_matching", default-features = false } -pact_mock_server = { version = "2.2.6", default-features = false } +pact_matching = { version = "2.2.0", path = "../pact_matching", default-features = false } +pact_mock_server = { version = "2.2.7", default-features = false } pact_models = { version = "1.3.16", default-features = false } pact-plugin-driver = { version = "1.2.3", optional = true, default-features = false } uuid = { version = "1.24.0", features = ["v4"], optional = true } diff --git a/rust/pact_ffi/CHANGELOG.md b/rust/pact_ffi/CHANGELOG.md index 5a450ef56..aff49c160 100644 --- a/rust/pact_ffi/CHANGELOG.md +++ b/rust/pact_ffi/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## [0.5.13](https://github.com/pact-foundation/pact-reference/compare/pact_ffi-v0.5.12...pact_ffi-v0.5.13) - _2026-11-13_ + +### ๐Ÿš€ Features + +- Allow the provider state change retries to be set with PACT_PROVIDER_STATE_CHANGE_RETRIES + +### ๐Ÿ› Bug Fixes + +- Apply the matchers nested under an eachValue matcher + +- _(ffi)_ Keep the plugin transport when writing via pactffi_pact_handle_write_file + +- _(ffi)_ Don't abort the host process when stderr is full + +### ๐Ÿ—๏ธ Build and CI + +- Use caret requirements between pact crates + +- Require pact_mock_server 2.2.6 + ## [0.5.12](https://github.com/pact-foundation/pact-reference/compare/pact_ffi-v0.5.11...pact_ffi-v0.5.12) - _2026-10-19_ ### ๐Ÿ› Bug Fixes diff --git a/rust/pact_ffi/Cargo.toml b/rust/pact_ffi/Cargo.toml index cd4e9a8b3..236227fc7 100644 --- a/rust/pact_ffi/Cargo.toml +++ b/rust/pact_ffi/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pact_ffi" -version = "0.5.12" +version = "0.5.13" authors = ["Ronald Holshausen ", "Matt Fellows ", "Andrew Lilley Brinker ", "Caleb Stepanian "] edition = "2021" description = "Pact interface for foreign languages." @@ -29,11 +29,11 @@ multipart-2021 = { version = "0.19.0", default-features = false, features = ["cl onig = { version = "6.5.3", default-features = false } # FFI Inmemory sink uses the global static `LOG_BUFFER` in the pact_matching crate. This is required to be the same # version as the mock server crate -pact_matching = { version = "2.1.0", path = "../pact_matching" } -pact_mock_server = "2.2.6" +pact_matching = { version = "2.2.0", path = "../pact_matching" } +pact_mock_server = "2.2.7" pact_models = { version = "1.3.16" } pact-plugin-driver = { version = "1.2.3" } -pact_verifier = { version = "1.5.0", path = "../pact_verifier" } +pact_verifier = { version = "1.6.0", path = "../pact_verifier" } panic-message = "0.3.0" rand = "0.9.5" rand_regex = "0.18.1" diff --git a/rust/pact_ffi/src/mock_server/handles.rs b/rust/pact_ffi/src/mock_server/handles.rs index 466725ecd..bba4bc1c4 100644 --- a/rust/pact_ffi/src/mock_server/handles.rs +++ b/rust/pact_ffi/src/mock_server/handles.rs @@ -124,7 +124,7 @@ use maplit::*; use pact_models::{Consumer, PactSpecification, Provider}; use pact_models::bodies::OptionalBody; use pact_models::content_types::{detect_content_type_from_string, ContentType, TEXT}; -use pact_models::generators::{generators_from_json, Generator, Generators}; +use pact_models::generators::{generators_from_json, Generator, GeneratorCategory, Generators}; use pact_models::headers::parse_header; use pact_models::http_parts::HttpPart; use pact_models::interaction::Interaction; @@ -1639,6 +1639,82 @@ ffi_fn! { } } +ffi_fn! { + /// Removes a header from the Interaction, along with any matching rules and generators + /// configured for it. The header name is matched case-insensitively. Returns false if the + /// interaction or Pact can't be modified (i.e. the mock server for it has already started), the + /// interaction is not an HTTP interaction, or the header is not set. + /// + /// This can be used to remove the `Content-Type` header that the body functions + /// (`pactffi_with_body`, `pactffi_with_binary_body`, etc.) add by default, when the request or + /// response must not have one. The content type of the body is kept with the body, so it is + /// still compared using that content type. Before V4, a Pact file can only record the content + /// type of a body with the `Content-Type` header, so removing it from a part with a body that is + /// not text is not allowed for those specification versions, and this function will return + /// false. + /// + /// * `part` - The part of the interaction to remove the header from (Request or Response). + /// * `name` - the header name. + /// + /// # Safety + /// The name parameter must be a valid pointer to a NULL terminated string. + fn pactffi_remove_header( + interaction: InteractionHandle, + part: InteractionPart, + name: *const c_char + ) -> bool { + if let Some(name) = convert_cstr("name", name) { + let spec_version = interaction.with_pact(&|_, inner| inner.specification_version) + .unwrap_or_default(); + interaction.with_interaction(&|_, mock_server_started, inner| { + if let Some(reqres) = inner.as_v4_http_mut() { + let http_part: &mut dyn HttpPart = match part { + InteractionPart::Request => &mut reqres.request, + InteractionPart::Response => &mut reqres.response + }; + remove_header(http_part, name, spec_version) && !mock_server_started + } else { + error!("Interaction is not an HTTP interaction, is {}", inner.type_of()); + false + } + }).unwrap_or(false) + } else { + warn!("Ignoring header with empty or null name"); + false + } + } { + false + } +} + +fn remove_header(part: &mut dyn HttpPart, name: &str, spec_version: PactSpecification) -> bool { + if spec_version < PactSpecification::V4 && name.eq_ignore_ascii_case("content-type") { + let body = part.body(); + if body.is_present() && !body.content_type().map(|ct| ct.is_text()).unwrap_or(false) { + warn!("Not removing the Content-Type header: a {} Pact file can not record the content type \ + of a body that is not text without it", spec_version); + return false; + } + } + + let removed = match part.headers_mut().keys().find(|k| k.eq_ignore_ascii_case(name)).cloned() { + Some(key) => part.headers_mut().remove(&key).is_some(), + None => false + }; + + let matches_name = |path: &DocPath| path.first_field() + .map(|field| field.eq_ignore_ascii_case(name)) + .unwrap_or(false); + if let Some(category) = part.matching_rules_mut().rules.get_mut(&Category::HEADER) { + category.rules.retain(|path, _| !matches_name(path)); + } + if let Some(generators) = part.generators_mut().categories.get_mut(&GeneratorCategory::HEADER) { + generators.retain(|path, _| !matches_name(path)); + } + + removed +} + /// Configures the response for the Interaction. Returns false if the interaction or Pact can't be /// modified (i.e. the mock server for it has already started) /// @@ -3903,6 +3979,63 @@ mod tests { expect!(interaction.request.matching_rules.rules.get(&Category::HEADER).cloned().unwrap_or_default().is_empty()).to(be_true()); } + #[test] + fn pactffi_remove_header_test() { + let pact_handle = PactHandle::new("TestHC1", "TestHP"); + let description = CString::new("remove_header").unwrap(); + let handle = pactffi_new_interaction(pact_handle, description.as_ptr()); + + let name = CString::new("x-id").unwrap(); + let value = CString::new("{\"pact:matcher:type\":\"regex\",\"regex\":\"\\\\d+\",\"value\":\"100\"}").unwrap(); + pactffi_with_header_v2(handle, InteractionPart::Request, name.as_ptr(), 0, value.as_ptr()); + let other = CString::new("x-other").unwrap(); + pactffi_with_header_v2(handle, InteractionPart::Request, other.as_ptr(), 0, value.as_ptr()); + + let upper_name = CString::new("X-ID").unwrap(); + let result = pactffi_remove_header(handle, InteractionPart::Request, upper_name.as_ptr()); + let result2 = pactffi_remove_header(handle, InteractionPart::Request, upper_name.as_ptr()); + + let interaction = handle.with_interaction(&|_, _, inner| { + inner.as_v4_http().unwrap() + }).unwrap(); + + pactffi_free_pact_handle(pact_handle); + + expect!(result).to(be_true()); + expect!(result2).to(be_false()); + expect!(interaction.request.headers.clone()).to(be_some().value(hashmap!{ + "x-other".to_string() => vec!["100".to_string()] + })); + let rules = interaction.request.matching_rules.rules.get(&Category::HEADER).cloned().unwrap_or_default(); + expect!(rules.rules.keys().map(|k| k.to_string()).collect::>()).to(be_equal_to(vec!["$['x-other']".to_string()])); + } + + #[rstest] + #[case(PactSpecification::V4, true)] + #[case(PactSpecification::V3, false)] + fn pactffi_remove_header_binary_body_content_type(#[case] spec: PactSpecification, #[case] expected_result: bool) { + let pact_handle = PactHandle::new("TestHC1", "TestHP"); + pactffi_with_specification(pact_handle, spec); + let description = CString::new("remove_header_binary").unwrap(); + let handle = pactffi_new_interaction(pact_handle, description.as_ptr()); + + let body = [0x00_u8, 0x01, 0xFF, 0xFE]; + pactffi_with_binary_body(handle, InteractionPart::Request, std::ptr::null(), body.as_ptr(), body.len()); + + let name = CString::new("content-type").unwrap(); + let result = pactffi_remove_header(handle, InteractionPart::Request, name.as_ptr()); + + let interaction = handle.with_interaction(&|_, _, inner| { + inner.as_v4_http().unwrap() + }).unwrap(); + + pactffi_free_pact_handle(pact_handle); + + expect!(result).to(be_equal_to(expected_result)); + expect!(interaction.request.has_header("Content-Type")).to(be_equal_to(!expected_result)); + expect!(interaction.request.body.content_type().unwrap().to_string()).to(be_equal_to("application/octet-stream")); + } + #[test] fn pactffi_set_header_different_case() { let pact_handle = PactHandle::new("TestHC1", "TestHP"); diff --git a/rust/pact_ffi/tests/tests.rs b/rust/pact_ffi/tests/tests.rs index bb797fa31..ae9307532 100644 --- a/rust/pact_ffi/tests/tests.rs +++ b/rust/pact_ffi/tests/tests.rs @@ -2690,3 +2690,43 @@ fn pact_handle_write_file_keeps_the_plugin_transport() { expect!(read_transport(&mock_server_dir)).to(be_equal_to(json!("matt"))); expect!(read_transport(&handle_dir)).to(be_equal_to(json!("matt"))); } + +// Each value of a repeated header or query parameter can have its own matcher. These must all +// survive being written to a pact file and read back. +#[test] +fn matchers_for_each_header_and_query_value_survive_writing_the_pact_file() { + let pact_handle = PactHandle::new("IndexedMatchersC", "IndexedMatchersP"); + pactffi_with_specification(pact_handle, PactSpecification::V4); + let description = CString::new("repeated values with matchers").unwrap(); + let i_handle = pactffi_new_interaction(pact_handle, description.as_ptr()); + let method = CString::new("GET").unwrap(); + let path = CString::new("/request").unwrap(); + pactffi_with_request(i_handle, method.as_ptr(), path.as_ptr()); + let name = CString::new("X-Request").unwrap(); + let first = CString::new(r#"{"value":"first-1","pact:matcher:type":"regex","regex":"^first-\\d+$"}"#).unwrap(); + let second = CString::new(r#"{"value":"second-1","pact:matcher:type":"regex","regex":"^second-\\d+$"}"#).unwrap(); + pactffi_with_header_v2(i_handle, InteractionPart::Request, name.as_ptr(), 0, first.as_ptr()); + pactffi_with_header_v2(i_handle, InteractionPart::Request, name.as_ptr(), 1, second.as_ptr()); + pactffi_with_query_parameter_v2(i_handle, name.as_ptr(), 0, first.as_ptr()); + pactffi_with_query_parameter_v2(i_handle, name.as_ptr(), 1, second.as_ptr()); + pactffi_response_status(i_handle, 200); + + let tmp = TempDir::new().unwrap(); + let tmp_dir = CString::new(tmp.path().to_string_lossy().as_bytes().to_vec()).unwrap(); + let result = pactffi_pact_handle_write_file(pact_handle, tmp_dir.as_ptr(), true); + let file_name = pact_default_file_name(&pact_handle); + pactffi_free_pact_handle(pact_handle); + expect!(result).to(be_equal_to(0)); + + let pact = pact_models::pact::read_pact(&tmp.path().join(file_name.unwrap())).unwrap(); + let request = pact.interactions()[0].as_request_response().unwrap().request; + for category in ["header", "query"] { + let rules = request.matching_rules.rules_for_category(category).unwrap(); + // Adding a matcher for a later value moves the first value's matcher to index 0 + let base = DocPath::root().join("X-Request"); + expect!(rules.rules.get(&base.join("0")).map(|r| r.rules.clone())) + .to(be_some().value(vec![MatchingRule::Regex("^first-\\d+$".to_string())])); + expect!(rules.rules.get(&base.join("1")).map(|r| r.rules.clone())) + .to(be_some().value(vec![MatchingRule::Regex("^second-\\d+$".to_string())])); + } +} diff --git a/rust/pact_matching/CHANGELOG.md b/rust/pact_matching/CHANGELOG.md index 7c4db3784..aadbdb201 100644 --- a/rust/pact_matching/CHANGELOG.md +++ b/rust/pact_matching/CHANGELOG.md @@ -1,5 +1,47 @@ # Changelog +## [2.2.0](https://github.com/pact-foundation/pact-reference/compare/pact_matching-v2.1.0...pact_matching-v2.2.0) - _2026-11-12_ + +### ๐Ÿš€ Features + +- _(matching)_ Respect Link and Via grammars when splitting headers + +### ๐Ÿ› Bug Fixes + +- Apply the matchers nested under an eachValue matcher + +- Apply an eachValue rule once when the values already have it + +- _(pact_matching)_ Merge the eachValue rules into any existing rules for the values + +- _(v2 engine)_ Apply the rules defined below an eachValue matcher to its values + +- _(matching)_ Match combined headers against repeated expectations + +- _(matching)_ Normalize repeated custom headers across engines + +- _(matching)_ Classify headers once for both engines + +- _(matching)_ Compare repeated custom headers by their joined value + +- _(matching)_ Apply scalar header matchers to the joined value + +- _(matching)_ Split repeated headers into list elements for list matchers + +- _(matching)_ Normalise repeated headers using the header's own grammar + +- _(matching)_ Use the header grammar when comparing single header values + +- _(matching)_ Name the failing value when a repeated header fails a scalar rule + +### ๐Ÿ“š Documentation + +- _(matching)_ Describe repeated header matching + +### ๐Ÿงช Testing + +- _(matching)_ Keep separate-line header list cases beside combined ones + ## [2.1.0](https://github.com/pact-foundation/pact-reference/compare/pact_matching-v2.0.11...pact_matching-v2.1.0) - _2026-10-21_ ### ๐Ÿš€ Features diff --git a/rust/pact_matching/Cargo.toml b/rust/pact_matching/Cargo.toml index d6342f83d..64825f162 100644 --- a/rust/pact_matching/Cargo.toml +++ b/rust/pact_matching/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pact_matching" -version = "2.1.0" +version = "2.2.0" authors = ["Ronald Holshausen "] edition = "2024" description = "Pact-Rust support library that implements request and response matching logic" diff --git a/rust/pact_matching/src/generator_tests.rs b/rust/pact_matching/src/generator_tests.rs index 411cc8816..247f45463 100644 --- a/rust/pact_matching/src/generator_tests.rs +++ b/rust/pact_matching/src/generator_tests.rs @@ -114,6 +114,108 @@ async fn applies_provider_state_generator_for_query_parameters_with_square_brack expect!(q_val).to(be_equal_to(&vec![Some("5678".to_string()), Some("5678".to_string())])); } +#[tokio::test] +async fn header_generator_for_the_name_applies_to_each_value_and_ignores_case() { + let request = HttpRequest { headers: Some(hashmap!{ + s!("X-Request") => vec![s!("a"), s!("b")] + }), generators: generators! { + "HEADER" => { + "x-request" => Generator::ProviderStateGenerator("exp".to_string(), None) + } + }, .. HttpRequest::default() + }; + let context = hashmap! { "exp" => json!("Z") }; + let headers = generate_request(&request, &GeneratorTestMode::Provider, &context).await.headers.unwrap(); + expect!(headers.get("X-Request").unwrap()).to(be_equal_to(&vec![s!("Z"), s!("Z")])); +} + +#[tokio::test] +async fn header_generator_for_a_value_index_applies_only_to_that_value() { + let response = HttpResponse { headers: Some(hashmap!{ + s!("X-Request") => vec![s!("a"), s!("b"), s!("c")] + }), generators: generators! { + "HEADER" => { + "$['X-Request'][1]" => Generator::ProviderStateGenerator("exp".to_string(), None), + "$['x-request'][5]" => Generator::ProviderStateGenerator("exp".to_string(), None) + } + }, .. HttpResponse::default() + }; + let context = hashmap! { "exp" => json!("Z") }; + let headers = generate_response(&response, &GeneratorTestMode::Provider, &context).await.headers.unwrap(); + expect!(headers.get("X-Request").unwrap()).to(be_equal_to(&vec![s!("a"), s!("Z"), s!("c")])); +} + +#[tokio::test] +async fn header_generator_for_a_value_index_runs_after_the_one_for_the_name() { + let request = HttpRequest { headers: Some(hashmap!{ + s!("X-Request") => vec![s!("a"), s!("b")] + }), generators: generators! { + "HEADER" => { + "$['X-Request'][0]" => Generator::ProviderStateGenerator("first".to_string(), None), + "X-Request" => Generator::ProviderStateGenerator("all".to_string(), None) + } + }, .. HttpRequest::default() + }; + let context = hashmap! { "first" => json!("B"), "all" => json!("A") }; + let headers = generate_request(&request, &GeneratorTestMode::Provider, &context).await.headers.unwrap(); + expect!(headers.get("X-Request").unwrap()).to(be_equal_to(&vec![s!("B"), s!("A")])); +} + +#[tokio::test] +async fn header_generator_for_a_missing_header_generates_a_single_value() { + let request = HttpRequest { generators: generators! { + "HEADER" => { + "X-Id" => Generator::ProviderStateGenerator("exp".to_string(), None), + "$['X-Other'][1]" => Generator::ProviderStateGenerator("exp".to_string(), None) + } + }, .. HttpRequest::default() + }; + let context = hashmap! { "exp" => json!("Z") }; + let headers = generate_request(&request, &GeneratorTestMode::Provider, &context).await.headers.unwrap(); + expect!(headers).to(be_equal_to(hashmap!{ s!("X-Id") => vec![s!("Z")] })); +} + +#[tokio::test] +async fn query_generator_for_a_missing_parameter_generates_a_single_value() { + let request = HttpRequest { query: Some(hashmap!{ + "a".to_string() => vec![ Some("1".to_string()) ] + }), generators: generators! { + "QUERY" => { + "id" => Generator::ProviderStateGenerator("exp".to_string(), None), + "$.other[1]" => Generator::ProviderStateGenerator("exp".to_string(), None) + } + }, .. HttpRequest::default() + }; + let context = hashmap! { "exp" => json!("Z") }; + let query = generate_request(&request, &GeneratorTestMode::Provider, &context).await.query.unwrap(); + expect!(query).to(be_equal_to(hashmap!{ + s!("a") => vec![Some(s!("1"))], + s!("id") => vec![Some(s!("Z"))] + })); +} + +#[tokio::test] +async fn query_generator_for_a_value_index_applies_only_to_that_value() { + // A key without the leading `$` is a plain parameter name, as when it is loaded from a pact file + let mut plain_name = DocPath::root(); + plain_name.push_field("ids[0]"); + let mut request = HttpRequest { query: Some(hashmap!{ + "ids".to_string() => vec![ Some("1".to_string()), Some("2".to_string()) ], + "ids[0]".to_string() => vec![ Some("x".to_string()) ] + }), generators: generators! { + "QUERY" => { + "$.ids[1]" => Generator::ProviderStateGenerator("exp".to_string(), None) + } + }, .. HttpRequest::default() + }; + request.generators.add_generator_with_subcategory(&GeneratorCategory::QUERY, plain_name, + Generator::ProviderStateGenerator("exp".to_string(), None)); + let context = hashmap! { "exp" => json!("Z") }; + let query = generate_request(&request, &GeneratorTestMode::Provider, &context).await.query.unwrap(); + expect!(query.get("ids").unwrap()).to(be_equal_to(&vec![Some(s!("1")), Some(s!("Z"))])); + expect!(query.get("ids[0]").unwrap()).to(be_equal_to(&vec![Some(s!("Z"))])); +} + #[tokio::test] async fn applies_body_generator_to_the_copy_of_the_request() { let request = HttpRequest { body: OptionalBody::Present("{\"a\": 100, \"b\": \"B\"}".into(), None, None), diff --git a/rust/pact_matching/src/headers.rs b/rust/pact_matching/src/headers.rs index 85b9db5a5..ddc2ebc20 100644 --- a/rust/pact_matching/src/headers.rs +++ b/rust/pact_matching/src/headers.rs @@ -87,14 +87,9 @@ pub(crate) fn match_header_value( let expected = expected.trim(); let actual = actual.trim(); - let matcher_result = if context.matcher_is_defined(&path) { - let result = match_values(&path, &context.select_best_matcher(&path), expected, actual); - if single_value { - result - } else { - result.map_err(|err| err.iter().map(|e| format!("{} for value at index {}", e, index)).collect()) - } - } else if context.matcher_is_defined(&indexed_path) { + // A rule for the name also matches the indexed path, and the most specific rule is selected, so + // a rule for this value index overrides the rule for the name + let matcher_result = if context.matcher_is_defined(&indexed_path) { let result = match_values(&indexed_path, &context.select_best_matcher(&indexed_path), expected, actual); if single_value { result @@ -1049,4 +1044,27 @@ mod tests { } ])); } + + #[rstest::rstest] + #[case(["b", "42"], true)] + #[case(["b", "z"], false)] + #[case(["1", "42"], false)] + fn an_indexed_rule_overrides_the_rule_for_the_header_for_that_value(#[case] actual: [&str; 2], #[case] matched: bool) { + let rules = pact_models::matchingrules::matchers_from_json(&serde_json::json!({ + "matchingRules": { "header": { + "X-Request": { "matchers": [{ "match": "regex", "regex": "^[a-z]+$" }] }, + "$['X-Request'][1]": { "matchers": [{ "match": "regex", "regex": "^[0-9]+$" }] } + } } + }), &None).unwrap(); + let context = HeaderMatchingContext::new(&CoreMatchingContext::new( + DiffConfig::AllowUnexpectedKeys, + &rules.rules_for_category("header").unwrap_or_default(), + &hashmap!{} + )); + let expected = hashmap! { "X-Request".to_string() => vec!["a".to_string(), "100".to_string()] }; + let actual = hashmap! { "X-Request".to_string() => actual.iter().map(|v| v.to_string()).collect() }; + let result = match_headers(Some(expected), Some(actual), &context); + let mismatches: Vec<_> = result.values().flatten().collect(); + expect!(mismatches.is_empty()).to(be_equal_to(matched)); + } } diff --git a/rust/pact_matching/src/lib.rs b/rust/pact_matching/src/lib.rs index f4b32b531..1d64987d5 100644 --- a/rust/pact_matching/src/lib.rs +++ b/rust/pact_matching/src/lib.rs @@ -374,14 +374,14 @@ use serde_json::{json, Value}; use pact_models::bodies::OptionalBody; use pact_models::content_types::ContentType; -use pact_models::generators::{apply_generators, GenerateValue, GeneratorCategory, GeneratorTestMode, VariantMatcher}; +use pact_models::generators::{apply_generators, GenerateValue, Generator, GeneratorCategory, GeneratorTestMode, VariantMatcher}; use pact_models::http_parts::HttpPart; use pact_models::interaction::Interaction; use pact_models::json_utils::json_to_string; use pact_models::matchingrules::{Category, MatchingRule, MatchingRuleCategory, RuleList}; use pact_models::pact::Pact; use pact_models::PactSpecification; -use pact_models::path_exp::DocPath; +use pact_models::path_exp::{DocPath, PathToken}; use pact_models::v4::http_parts::{HttpRequest, HttpResponse}; use pact_models::v4::message_parts::MessageContents; use pact_models::v4::sync_message::SynchronousMessage; @@ -1778,9 +1778,12 @@ pub async fn match_body( let actual_content_type = actual.content_type().unwrap_or_default(); debug!("expected content type = '{}', actual content type = '{}'", expected_content_type, actual_content_type); + // Without a Content-Type header the actual type was only sniffed from the body (the mock server + // stores that guess on the body), so it can't contradict the expected type (pact-go#263). + let actual_declares_type = actual.has_header("Content-Type"); let content_type_matcher = header_context.select_best_matcher(&DocPath::root().join("content-type")); debug!("content type header matcher = '{:?}'", content_type_matcher); - if expected_content_type.is_unknown() || actual_content_type.is_unknown() || + if expected_content_type.is_unknown() || actual_content_type.is_unknown() || !actual_declares_type || expected_content_type.is_equivalent_to(&actual_content_type) || expected_content_type.is_equivalent_to(&actual_content_type.base_type()) || (!content_type_matcher.is_empty() && @@ -2442,6 +2445,56 @@ pub async fn match_sync_message_response<'a>( mismatches } +/// Applies a generator to the values of a header or query parameter. A key for the name (`$.name`) applies to every +/// value, and generates a single value if there are none. A key with a value index (`$.name[1]`) applies only to that +/// value, and is ignored if there is no value at that index. Generators are applied in order of path length, so the +/// generators for an index run after the one for the name. +fn apply_value_generator( + values: &mut HashMap>, + key: &DocPath, + generator: &Generator, + context: &HashMap<&str, Value>, + ignore_case: bool, + to_string: fn(&V) -> String, + from_string: fn(String) -> V +) { + let (name, index) = match key.tokens().as_slice() { + [PathToken::Root, PathToken::Field(name)] => (name.as_str(), None), + [PathToken::Root, PathToken::Field(name), PathToken::Index(index)] => (name.as_str(), Some(*index)), + _ => match key.first_field() { + Some(name) => (name, None), + None => return + } + }; + let existing = values.keys() + .find(|k| if ignore_case { k.eq_ignore_ascii_case(name) } else { k.as_str() == name }) + .cloned(); + let generate = |value: String| generator.generate_value(&value, context, &DefaultVariantMatcher.boxed()).ok(); + match (existing, index) { + (Some(existing), None) => { + let current = values.get_mut(&existing).unwrap(); + for value in current.iter_mut() { + if let Some(v) = generate(to_string(value)) { + *value = from_string(v); + } + } + } + (Some(existing), Some(index)) => { + if let Some(value) = values.get_mut(&existing).unwrap().get_mut(index) { + if let Some(v) = generate(to_string(value)) { + *value = from_string(v); + } + } + } + (None, None) => { + if let Some(v) = generate(String::default()) { + values.insert(name.to_string(), vec![from_string(v)]); + } + } + (None, Some(_)) => {} + } +} + /// Generates the request by applying any defined generators // TODO: Need to pass in any plugin data #[instrument(level = "trace")] @@ -2462,54 +2515,25 @@ pub async fn generate_request(request: &HttpRequest, mode: &GeneratorTestMode, c let generators = request.build_generators(&GeneratorCategory::HEADER); if !generators.is_empty() { debug!("Applying header generators..."); + let headers = request.headers.get_or_insert_with(HashMap::new); apply_generators(mode, &generators, &mut |key, generator| { - if let Some(header) = key.first_field() { - if let Some(ref mut headers) = request.headers { - if headers.contains_key(header) { - if let Ok(v) = generator.generate_value(&headers.get(header).unwrap().clone(), context, &DefaultVariantMatcher.boxed()) { - headers.insert(header.to_string(), v); - } - } else { - if let Ok(v) = generator.generate_value(&"".to_string(), context, &DefaultVariantMatcher.boxed()) { - headers.insert(header.to_string(), vec![ v.to_string() ]); - } - } - } else { - if let Ok(v) = generator.generate_value(&"".to_string(), context, &DefaultVariantMatcher.boxed()) { - request.headers = Some(hashmap!{ - header.to_string() => vec![ v.to_string() ] - }) - } - } - } + apply_value_generator(headers, key, generator, context, true, |v| v.clone(), |v| v); }); + if headers.is_empty() { + request.headers = None; + } } let generators = request.build_generators(&GeneratorCategory::QUERY); if !generators.is_empty() { debug!("Applying query generators..."); + let query = request.query.get_or_insert_with(HashMap::new); apply_generators(mode, &generators, &mut |key, generator| { - if let Some(param) = key.first_field() { - if let Some(ref mut parameters) = request.query { - if let Some(parameter) = parameters.get_mut(param) { - let mut generated = parameter.clone(); - for (index, val) in parameter.iter().enumerate() { - let value = val.clone().unwrap_or_default(); - if let Ok(v) = generator.generate_value(&value, context, &DefaultVariantMatcher.boxed()) { - generated[index] = Some(v); - } - } - *parameter = generated; - } else if let Ok(v) = generator.generate_value(&"".to_string(), context, &DefaultVariantMatcher.boxed()) { - parameters.insert(param.to_string(), vec![ Some(v.to_string()) ]); - } - } else if let Ok(v) = generator.generate_value(&"".to_string(), context, &DefaultVariantMatcher.boxed()) { - request.query = Some(hashmap!{ - param.to_string() => vec![ Some(v.to_string()) ] - }) - } - } + apply_value_generator(query, key, generator, context, false, |v| v.clone().unwrap_or_default(), Some); }); + if query.is_empty() { + request.query = None; + } } let generators = request.build_generators(&GeneratorCategory::BODY); @@ -2543,27 +2567,13 @@ pub async fn generate_response(response: &HttpResponse, mode: &GeneratorTestMode let generators = response.build_generators(&GeneratorCategory::HEADER); if !generators.is_empty() { debug!("Applying header generators..."); + let headers = response.headers.get_or_insert_with(HashMap::new); apply_generators(mode, &generators, &mut |key, generator| { - if let Some(header) = key.first_field() { - if let Some(ref mut headers) = response.headers { - if headers.contains_key(header) { - if let Ok(v) = generator.generate_value(&headers.get(header).unwrap().clone(), context, &DefaultVariantMatcher.boxed()) { - headers.insert(header.to_string(), v); - } - } else { - if let Ok(v) = generator.generate_value(&"".to_string(), context, &DefaultVariantMatcher.boxed()) { - headers.insert(header.to_string(), vec![ v.to_string() ]); - } - } - } else { - if let Ok(v) = generator.generate_value(&"".to_string(), context, &DefaultVariantMatcher.boxed()) { - response.headers = Some(hashmap!{ - header.to_string() => vec![ v.to_string() ] - }) - } - } - } + apply_value_generator(headers, key, generator, context, true, |v| v.clone(), |v| v); }); + if headers.is_empty() { + response.headers = None; + } } let generators = response.build_generators(&GeneratorCategory::BODY); if !generators.is_empty() && response.body.is_present() { diff --git a/rust/pact_matching/src/query.rs b/rust/pact_matching/src/query.rs index fd9aa8ebe..d4c0bcefa 100644 --- a/rust/pact_matching/src/query.rs +++ b/rust/pact_matching/src/query.rs @@ -212,4 +212,31 @@ mod tests { expect!(result).to(be_err()); } } + + #[rstest] + #[case(["y", "42"], true)] + #[case(["y", "z"], false)] + #[case(["1", "42"], false)] + fn an_indexed_rule_overrides_the_rule_for_the_name_for_that_value(#[case] actual: [&str; 2], #[case] matched: bool) { + let rules = pact_models::matchingrules::matchers_from_json(&serde_json::json!({ + "matchingRules": { "query": { + "a": { "matchers": [{ "match": "regex", "regex": "^[a-z]+$" }] }, + "$.a[1]": { "matchers": [{ "match": "regex", "regex": "^[0-9]+$" }] } + } } + }), &None).unwrap(); + let context = CoreMatchingContext::new( + DiffConfig::AllowUnexpectedKeys, + &rules.rules_for_category("query").unwrap_or_default(), + &hashmap!{} + ); + let expected = ["x".to_string(), "100".to_string()]; + let actual = actual.map(|v| v.to_string()); + + let result = super::match_query_values("a", &expected, &actual, &context); + if matched { + expect!(result).to(be_ok()); + } else { + expect!(result).to(be_err()); + } + } } diff --git a/rust/pact_matching/src/tests.rs b/rust/pact_matching/src/tests.rs index 967083bd8..f97481eba 100644 --- a/rust/pact_matching/src/tests.rs +++ b/rust/pact_matching/src/tests.rs @@ -502,6 +502,33 @@ async fn body_does_not_match_if_different_content_types() { })); } +#[tokio::test] +async fn body_uses_expected_content_type_if_actual_has_none() { + let octet_stream = ContentType::parse("application/octet-stream").unwrap(); + let expected = Request { + method: "POST".to_string(), + body: OptionalBody::Present(Bytes::from_static(b"\x00\x01\x02"), Some(octet_stream), None), + ..Request::default() + }; + let actual = Request { + method: "POST".to_string(), + body: OptionalBody::Present(Bytes::from_static(b"\x00\x01\x02"), Some(TEXT.clone()), None), + ..Request::default() + }; + let result = match_body(&expected, &actual, &CoreMatchingContext::default(), + &CoreMatchingContext::default()).await; + expect!(result.mismatches().iter()).to(be_empty()); + + let different = Request { + body: OptionalBody::Present(Bytes::from_static(b"\x00\x01\x09"), None, None), + ..actual.clone() + }; + let result = match_body(&expected, &different, &CoreMatchingContext::default(), + &CoreMatchingContext::default()).await; + expect!(result.mismatches().iter()).to_not(be_empty()); + expect!(matches!(result.mismatches()[0], Mismatch::BodyTypeMismatch { .. })).to(be_false()); +} + #[tokio::test] async fn body_matching_uses_any_matcher_for_content_type_header() { let expected = Request { diff --git a/rust/pact_models/CHANGELOG.md b/rust/pact_models/CHANGELOG.md index 992dbce2c..65aa12216 100644 --- a/rust/pact_models/CHANGELOG.md +++ b/rust/pact_models/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [1.3.18](https://github.com/pact-foundation/pact-reference/compare/pact_models-v1.3.17...pact_models-v1.3.18) - _2026-11-13_ + +### ๐Ÿ“š Documentation + +- _(pact_models)_ Curate the release changelog + ## [1.3.17](https://github.com/pact-foundation/pact-reference/compare/pact_models-v1.3.16...pact_models-v1.3.17) - _2026-10-21_ ### ๐Ÿ› Bug Fixes diff --git a/rust/pact_models/Cargo.toml b/rust/pact_models/Cargo.toml index 61389d810..edda37c2c 100644 --- a/rust/pact_models/Cargo.toml +++ b/rust/pact_models/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pact_models" -version = "1.3.17" +version = "1.3.18" authors = ["Ronald Holshausen "] edition = "2024" description = "Pact-Rust support library that provides the core models for dealing with Pact files" diff --git a/rust/pact_models/src/generators/mod.rs b/rust/pact_models/src/generators/mod.rs index c7df37ed8..0b29797da 100644 --- a/rust/pact_models/src/generators/mod.rs +++ b/rust/pact_models/src/generators/mod.rs @@ -26,7 +26,7 @@ use crate::bodies::OptionalBody; use crate::expression_parser::{contains_expressions, DataType, DataValue, MapValueResolver, parse_expression}; #[cfg(feature = "datetime")] use crate::generators::datetime_expressions::{execute_date_expression, execute_datetime_expression, execute_time_expression}; use crate::json_utils::{get_field_as_string, json_to_string, JsonToNum, resolve_path}; -use crate::matchingrules::{Category, MatchingRuleCategory}; +use crate::matchingrules::{Category, MatchingRuleCategory, indexed_field_path, v3_field_key}; use crate::PactSpecification; use crate::path_exp::DocPath; use crate::plugins::plugin_support; @@ -667,7 +667,9 @@ impl Generators { match sub_v { &Value::Object(ref map) => { if *category == GeneratorCategory::QUERY || *category == GeneratorCategory::HEADER { - self.parse_generator_from_map(category, map, Some(DocPath::root().push_field(sub_k).clone())); + let path = indexed_field_path(sub_k) + .unwrap_or_else(|| DocPath::root().push_field(sub_k).clone()); + self.parse_generator_from_map(category, map, Some(path)); } else { self.parse_generator_from_map(category, map, Some(DocPath::new(sub_k)?)); } @@ -726,9 +728,7 @@ impl Generators { for (key, val) in category { let json = val.to_json(); if let Some(json) = json { - let name = key.first_field().map(|v| v.to_string()) - .unwrap_or_else(|| key.to_string()); - generators.insert(name, json); + generators.insert(v3_field_key(key, category.keys()), json); } } map.insert(cat.clone(), Value::Object(generators)); @@ -2437,6 +2437,26 @@ mod tests { expect!(json.to_string()).to_not(be_equal_to("{}")); } + #[test] + fn generators_for_each_header_and_query_value_round_trip_through_json() { + let path = DocPath::root().join("X-Request"); + let mut generators = Generators::default(); + for category in [GeneratorCategory::HEADER, GeneratorCategory::QUERY] { + generators.add_generator_with_subcategory(&category, path.clone(), Generator::RandomInt(1, 10)); + generators.add_generator_with_subcategory(&category, path.join("1"), Generator::RandomInt(20, 30)); + } + + let json = generators_to_json(&generators, &PactSpecification::V4); + let expected = json!({ + "X-Request": { "type": "RandomInt", "min": 1, "max": 10 }, + "$['X-Request'][1]": { "type": "RandomInt", "min": 20, "max": 30 } + }); + assert_eq!(json, json!({ "header": expected, "query": expected })); + + let loaded = generators_from_json(&json!({ "generators": json })).unwrap(); + assert_eq!(loaded, generators); + } + #[test] fn hash_test_for_generators() { let g1 = Generators::default(); diff --git a/rust/pact_models/src/matchingrules/mod.rs b/rust/pact_models/src/matchingrules/mod.rs index 2c7b7b68d..ed7f17c63 100644 --- a/rust/pact_models/src/matchingrules/mod.rs +++ b/rust/pact_models/src/matchingrules/mod.rs @@ -1123,9 +1123,7 @@ impl MatchingRuleCategory { Value::Object(self.rules.iter().fold(serde_json::Map::new(), |mut map, (category, rulelist)| { match self.name { Category::HEADER | Category::QUERY => { - let name = category.first_field().map(|v| v.to_string()) - .unwrap_or_else(|| category.to_string()); - map.insert(name, rulelist.to_v3_json()); + map.insert(v3_field_key(category, self.rules.keys()), rulelist.to_v3_json()); } _ => { map.insert(String::from(category), rulelist.to_v3_json()); @@ -1193,10 +1191,21 @@ impl MatchingRuleCategory { pub fn select_best_matcher(&self, path: &[&str]) -> RuleList { match self.name { Category::BODY | Category::METADATA => self.max_by_path(path), + Category::HEADER | Category::QUERY => self.most_specific_for_path(path), _ => self.resolve_matchers_for_path(path).as_rule_list() } } + /// Selects the rules with the longest key that matches the path, so a rule for a value index + /// (`$.a[1]`) is used for that value over the rule for the name (`a`). + fn most_specific_for_path(&self, path: &[&str]) -> RuleList { + self.rules.iter() + .filter(|(k, _)| k.matches_path(path)) + .max_by_key(|(k, _)| k.len()) + .map(|(_, v)| v.clone()) + .unwrap_or_default() + } + /// Returns this category as a matching rule list. Returns a None if there are no rules pub fn as_rule_list(&self) -> RuleList { self.rules.values().next().cloned().unwrap_or_default() @@ -1255,8 +1264,11 @@ impl MatchingRuleCategory { self.add_rule_list(DocPath::empty(), rules)?; } else if self.name == Category::QUERY || self.name == Category::HEADER { for (k, v) in m { - let mut path = DocPath::root(); - path.push_field(k); + let path = indexed_field_path(k).unwrap_or_else(|| { + let mut path = DocPath::root(); + path.push_field(k); + path + }); self.add_rule_list(path, v)?; } } else { @@ -1627,6 +1639,36 @@ impl Display for MatchingRules { } } +/// Key used for a header or query parameter rule or generator in V3+ format. Entries for a single +/// value (`$.name[1]`) keep their full path, as the bare name would collide with the entries for +/// the other values. An entry for the first value is written as the bare name when it is the only +/// entry for that name, which is how it has always been written. +pub(crate) fn v3_field_key<'a>(path: &DocPath, keys: impl Iterator) -> String { + match path.tokens().as_slice() { + [PathToken::Root, PathToken::Field(name)] => name.clone(), + [PathToken::Root, PathToken::Field(name), PathToken::Index(index)] => { + let mut keys = keys; + let shares_name = keys.any(|other| other != path && other.first_field() == Some(name.as_str())); + if *index == 0 && !shares_name { + name.clone() + } else { + path.to_string() + } + } + _ => path.first_field().map(|v| v.to_string()).unwrap_or_else(|| path.to_string()) + } +} + +/// Parses a V3+ header or query parameter key written for a single value (`$.name[1]` or +/// `$['name'][1]`). Any other key is a plain header or parameter name. +pub(crate) fn indexed_field_path(key: &str) -> Option { + if !key.starts_with('$') { + return None; + } + DocPath::new(key).ok().filter(|path| matches!(path.tokens().as_slice(), + [PathToken::Root, PathToken::Field(_), PathToken::Index(_)])) +} + /// Parses the matching rules from the Value structure pub fn matchers_from_json(value: &Value, deprecated_name: &Option ) -> anyhow::Result { @@ -2487,6 +2529,21 @@ mod tests { }))); } + #[test] + fn select_best_matcher_selects_the_rule_for_a_value_index_over_the_rule_for_the_name() { + let rules = matchers_from_json(&json!({ + "matchingRules": { "query": { + "a": { "matchers": [{ "match": "type" }] }, + "$.a[1]": { "matchers": [{ "match": "regex", "regex": "\\d+" }] } + } } + }), &None).unwrap(); + let category = rules.rules_for_category("query").unwrap(); + expect!(category.select_best_matcher(&["$", "a", "1"]).rules).to( + be_equal_to(vec![MatchingRule::Regex("\\d+".to_string())])); + expect!(category.select_best_matcher(&["$", "a", "0"]).rules).to( + be_equal_to(vec![MatchingRule::Type])); + } + #[test] fn matcher_is_defined_returns_false_when_there_are_no_matchers() { let matchers = matchingrules!{}; @@ -3018,4 +3075,87 @@ mod tests { })); expect!(rule.can_cascade()).to(be_false()); } + + fn indexed_field_rules(category: &str) -> MatchingRuleCategory { + let mut rules = MatchingRuleCategory::empty(category); + let path = DocPath::root().join("X-Request"); + rules.add_rule(path.clone(), MatchingRule::Regex("^first-\\d+$".to_string()), RuleLogic::And); + rules.add_rule(path.join("1"), MatchingRule::Regex("^second-\\d+$".to_string()), RuleLogic::And); + rules + } + + #[test] + fn to_v3_json_keeps_rules_for_each_header_and_query_value() { + let mut matching_rules = MatchingRules::default(); + matching_rules.add_rules("header", indexed_field_rules("header")); + matching_rules.add_rules("query", indexed_field_rules("query")); + + let expected = json!({ + "X-Request": { + "combine": "AND", + "matchers": [ { "match": "regex", "regex": "^first-\\d+$" } ] + }, + "$['X-Request'][1]": { + "combine": "AND", + "matchers": [ { "match": "regex", "regex": "^second-\\d+$" } ] + } + }); + for spec in [PactSpecification::V3, PactSpecification::V4] { + let json = matchers_to_json(&matching_rules, &spec); + assert_eq!(json, json!({ "header": expected, "query": expected })); + } + } + + #[test] + fn rules_for_each_header_and_query_value_round_trip_through_json() { + let mut matching_rules = MatchingRules::default(); + matching_rules.add_rules("header", indexed_field_rules("header")); + matching_rules.add_rules("query", indexed_field_rules("query")); + + let json = json!({ "matchingRules": matchers_to_json(&matching_rules, &PactSpecification::V4) }); + let loaded = matchers_from_json(&json, &None).unwrap(); + + assert_eq!(loaded, matching_rules); + } + + #[test] + fn to_v3_json_writes_a_lone_first_value_rule_as_the_bare_name() { + let mut rules = MatchingRuleCategory::empty("query"); + rules.add_rule(DocPath::root().join("a").join("0"), MatchingRule::Type, RuleLogic::And); + + expect!(rules.to_v3_json()).to(be_equal_to(json!({ + "a": { "combine": "AND", "matchers": [ { "match": "type" } ] } + }))); + } + + #[test] + fn to_v3_json_keeps_the_first_value_index_when_other_values_have_rules() { + let mut rules = MatchingRuleCategory::empty("query"); + let path = DocPath::root().join("a"); + rules.add_rule(path.join("0"), MatchingRule::Type, RuleLogic::And); + rules.add_rule(path.join("1"), MatchingRule::Integer, RuleLogic::And); + + expect!(rules.to_v3_json()).to(be_equal_to(json!({ + "$.a[0]": { "combine": "AND", "matchers": [ { "match": "type" } ] }, + "$.a[1]": { "combine": "AND", "matchers": [ { "match": "integer" } ] } + }))); + } + + #[test] + fn add_v3_rules_from_json_treats_bracketed_names_as_plain_names() { + let mut rules = MatchingRuleCategory::empty("query"); + rules.add_v3_rules_from_json(&json!({ + "ids[0]": { "matchers": [ { "match": "type" } ] }, + "$filter": { "matchers": [ { "match": "type" } ] }, + "$.a[2]": { "matchers": [ { "match": "type" } ] } + })).unwrap(); + + let mut paths = rules.rules.keys().map(|p| p.tokens().clone()).collect::>(); + paths.sort_by_key(|tokens| format!("{:?}", tokens)); + expect!(paths).to(be_equal_to(vec![ + vec![PathToken::Root, PathToken::Field("$filter".to_string())], + vec![PathToken::Root, PathToken::Field("a".to_string()), PathToken::Index(2)], + vec![PathToken::Root, PathToken::Field("ids[0]".to_string())] + ])); + } } diff --git a/rust/pact_verifier/CHANGELOG.md b/rust/pact_verifier/CHANGELOG.md index 400b583e5..1fbf7233e 100644 --- a/rust/pact_verifier/CHANGELOG.md +++ b/rust/pact_verifier/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## [1.6.0](https://github.com/pact-foundation/pact-reference/compare/pact_verifier-v1.5.0...pact_verifier-v1.6.0) - _2026-11-13_ + +### ๐Ÿš€ Features + +- Allow the provider state change retries to be set with PACT_PROVIDER_STATE_CHANGE_RETRIES + +### ๐Ÿ› Bug Fixes + +- _(pact_verifier)_ Apply generators to form-urlencoded request bodies + +### ๐Ÿ“ฆ Other + +- Merge pull request #592 from ChangkeunJ/fix/verifier-form-urlencoded-generators + ## [1.5.0](https://github.com/pact-foundation/pact-reference/compare/pact_verifier-v1.4.7...pact_verifier-v1.5.0) - _2026-10-21_ ### ๐Ÿš€ Features diff --git a/rust/pact_verifier/Cargo.toml b/rust/pact_verifier/Cargo.toml index c3285890d..1c4887542 100644 --- a/rust/pact_verifier/Cargo.toml +++ b/rust/pact_verifier/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pact_verifier" -version = "1.5.0" +version = "1.6.0" authors = ["Ronald Holshausen "] edition = "2024" description = "Pact-Rust support library that implements provider verification functions" @@ -15,11 +15,12 @@ exclude = [ ] [features] -default = ["datetime", "xml", "plugins", "multipart"] +default = ["datetime", "xml", "plugins", "multipart", "form_urlencoded"] datetime = ["pact_models/datetime", "pact-plugin-driver?/datetime", "pact_matching/datetime"] # Support for date/time matchers and expressions xml = ["pact_models/xml", "pact-plugin-driver?/xml", "pact_matching/xml"] # support for matching XML documents plugins = ["dep:pact-plugin-driver", "dep:uuid", "pact_matching/plugins", "pact-plugin-driver/default"] multipart = ["pact_matching/multipart"] # suport for MIME multipart bodies +form_urlencoded = ["pact_models/form_urlencoded", "pact_matching/form_urlencoded"] # support for generating form urlencoded bodies [dependencies] ansi_term = "0.12.1" @@ -35,7 +36,7 @@ itertools = "0.15.0" lazy_static = "1.5.0" maplit = "1.0.2" mime = "0.3.17" -pact_matching = { version = "2.1.0", path = "../pact_matching", default-features = false } +pact_matching = { version = "2.2.0", path = "../pact_matching", default-features = false } pact_models = { version = "1.3.16", default-features = false } pact-plugin-driver = { version = "1.2.3", optional = true, default-features = false } uuid = { version = "1.24.0", features = ["v4"], optional = true } diff --git a/rust/pact_verifier/src/tests.rs b/rust/pact_verifier/src/tests.rs index f520190df..7ea408a06 100644 --- a/rust/pact_verifier/src/tests.rs +++ b/rust/pact_verifier/src/tests.rs @@ -16,12 +16,14 @@ use rstest::rstest; use serde_json::{json, Value}; use pact_consumer::prelude::*; use pact_models::Consumer; +use pact_models::generators::GeneratorTestMode; use pact_models::interaction::Interaction; use pact_models::pact::Pact; use pact_models::prelude::v4::SynchronousHttp; use pact_models::provider_states::*; use pact_models::sync_interaction::RequestResponseInteraction; use pact_models::sync_pact::RequestResponsePact; +use pact_models::v4::http_parts::HttpRequest; use crate::{ FilterById, @@ -1256,3 +1258,38 @@ fn process_comments_with_no_references_produces_no_references_section() { super::process_comments(&interaction, &mut output); assert_snapshot!(output.join("\n")); } + +#[test_log::test(tokio::test)] +async fn generate_request_applies_body_generators_to_a_form_urlencoded_request() { + let request = HttpRequest::from_json(&json!({ + "method": "POST", + "path": "/orders", + "headers": { "Content-Type": "application/x-www-form-urlencoded" }, + "body": { + "content": "customer=1&qty=2¬e=gift+wrap", + "contentType": "application/x-www-form-urlencoded", + "encoded": false + }, + "generators": { + "body": { + "$.customer": { "type": "ProviderState", "expression": "${customer}", "dataType": "STRING" }, + "$.qty": { "type": "RandomInt", "min": 100, "max": 999 } + } + } + })).unwrap(); + let context = hashmap!{ "customer" => json!(1234) }; + + let generated = pact_matching::generate_request(&request, &GeneratorTestMode::Provider, &context).await; + + let body = String::from_utf8(generated.body.value().unwrap().to_vec()).unwrap(); + let params: Vec<(&str, &str)> = body.split('&') + .map(|param| param.split_once('=').unwrap()) + .collect(); + expect!(params.len()).to(be_equal_to(3)); + expect!(params[0]).to(be_equal_to(("customer", "1234"))); + expect!(params[1].0).to(be_equal_to("qty")); + let qty: i32 = params[1].1.parse().unwrap(); + expect!(qty).to(be_greater_or_equal_to(100)); + expect!(qty).to(be_less_or_equal_to(999)); + expect!(params[2]).to(be_equal_to(("note", "gift+wrap"))); +} diff --git a/rust/pact_verifier_cli/CHANGELOG.md b/rust/pact_verifier_cli/CHANGELOG.md index 7a8e3cedc..3849802fc 100644 --- a/rust/pact_verifier_cli/CHANGELOG.md +++ b/rust/pact_verifier_cli/CHANGELOG.md @@ -1,5 +1,33 @@ # Changelog +## [1.5.1](https://github.com/pact-foundation/pact-reference/compare/pact_verifier_cli-v1.5.0...pact_verifier_cli-v1.5.1) - _2026-11-23_ + +### ๐Ÿ› Bug Fixes + +- _(pact_verifier_cli)_ Build against xrust 2.4 + +### ๐Ÿงช Testing + +- _(pact_verifier_cli)_ Snapshot the HTML report + +### ๐Ÿ› ๏ธ Miscellaneous Tasks + +- _(pact_verifier_cli)_ Extract release tarball into a workdir in Docker fetch stage ([#608](https://github.com/pact-foundation/pact-reference/pull/608)) + +## [1.5.0](https://github.com/pact-foundation/pact-reference/compare/pact_verifier_cli-v1.4.0...pact_verifier_cli-v1.5.0) - _2026-11-13_ + +### ๐Ÿš€ Features + +- Allow the provider state change retries to be set with PACT_PROVIDER_STATE_CHANGE_RETRIES + +### ๐Ÿ› Bug Fixes + +- _(pact_verifier)_ Apply generators to form-urlencoded request bodies + +### ๐Ÿ“ฆ Other + +- Merge pull request #592 from ChangkeunJ/fix/verifier-form-urlencoded-generators + ## [1.4.0](https://github.com/pact-foundation/pact-reference/compare/pact_verifier_cli-v1.3.5...pact_verifier_cli-v1.4.0) - _2026-10-21_ ### ๐Ÿš€ Features diff --git a/rust/pact_verifier_cli/Cargo.toml b/rust/pact_verifier_cli/Cargo.toml index 9c95ed3c2..71309efa6 100644 --- a/rust/pact_verifier_cli/Cargo.toml +++ b/rust/pact_verifier_cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pact_verifier_cli" -version = "1.4.0" +version = "1.5.1" authors = ["Ronald Holshausen "] edition = "2024" description = "Standalone pact verifier for provider pact verification" @@ -14,11 +14,12 @@ exclude = [ ] [features] -default = ["datetime", "xml", "plugins", "multipart", "junit"] +default = ["datetime", "xml", "plugins", "multipart", "form_urlencoded", "junit"] datetime = ["pact_models/datetime", "pact_verifier/datetime"] # Support for date/time matchers and expressions xml = ["pact_models/xml", "pact_verifier/xml"] # support for matching XML documents plugins = ["pact_verifier/plugins"] multipart = ["pact_verifier/multipart"] # support for MIME multipart bodies +form_urlencoded = ["pact_models/form_urlencoded", "pact_verifier/form_urlencoded"] # support for form urlencoded bodies junit = ["dep:junit-report", "dep:strip-ansi-escapes"] # support for Junit format reports [dependencies] @@ -29,11 +30,11 @@ junit-report = { version = "0.8.3", optional = true } lazy_static = "1.5.0" log = "0.4.27" maplit = "1.0.2" -pact_matching = { version = "2.1.0", path = "../pact_matching", default-features = false } +pact_matching = { version = "2.2.0", path = "../pact_matching", default-features = false } pact_models = { version = "1.3.16", default-features = false } -pact_verifier = { version = "1.5.0", path = "../pact_verifier", default-features = false } +pact_verifier = { version = "1.6.0", path = "../pact_verifier", default-features = false } quick-xml = { version = "0.39.2", features = ["serde", "serialize"] } -xrust = "2.0.3" +xrust = "2.4.1" regex = "1.11.1" rustls = { version = "0.23.43", default-features = false, features = ["ring", "logging", "tls12", "std"] } serde = "1.0.228" diff --git a/rust/pact_verifier_cli/Dockerfile b/rust/pact_verifier_cli/Dockerfile index 3625ab5f2..dfed67ab2 100644 --- a/rust/pact_verifier_cli/Dockerfile +++ b/rust/pact_verifier_cli/Dockerfile @@ -4,6 +4,7 @@ FROM --platform=$BUILDPLATFORM alpine:3.22 AS fetch ARG VERSION ARG TARGETARCH RUN apk add --no-cache ca-certificates curl xz +WORKDIR /dist RUN case "$TARGETARCH" in \ amd64) target=x86_64-unknown-linux-musl ;; \ arm64) target=aarch64-unknown-linux-musl ;; \ diff --git a/rust/pact_verifier_cli/src/reports/mod.rs b/rust/pact_verifier_cli/src/reports/mod.rs index e1b446ba8..629bb586b 100644 --- a/rust/pact_verifier_cli/src/reports/mod.rs +++ b/rust/pact_verifier_cli/src/reports/mod.rs @@ -21,12 +21,20 @@ mod xml; const XSLT: &str = include_str!("verification-report.xsl"); +fn missing_namespace() -> ParseError { + ParseError::MissingNameSpace { + prefix: None, + nsuri: None, + message: Some("namespace prefixes must be declared in the document".to_string()) + } +} + fn node_from_str(s: &str) -> Result { - parse(RNode::new_document(), s, Some(|_: &_| Err(ParseError::MissingNameSpace))) + parse(RNode::new_document(), s, Some(|_: &_| Err(missing_namespace()))) } fn apply_xslt(xml_str: &str, xslt: Option<&String>) -> anyhow::Result { - let doc = parse(RNode::new_document(), xml_str, Some(|_: &_| Err(ParseError::MissingNameSpace)))?; + let doc = parse(RNode::new_document(), xml_str, Some(|_: &_| Err(missing_namespace())))?; let mut s = String::new(); let xslt_doc = if let Some(xslt) = xslt { @@ -36,15 +44,15 @@ fn apply_xslt(xml_str: &str, xslt: Option<&String>) -> anyhow::Result { } else { XSLT }; - let xslt_doc = parse(RNode::new_document(), xslt_doc, Some(|_: &_| Err(ParseError::MissingNameSpace)))?; + let xslt_doc = parse(RNode::new_document(), xslt_doc, Some(|_: &_| Err(missing_namespace())))?; let mut static_context = StaticContextBuilder::new() .message(|_| Ok(())) - .fetcher(|_| Err(Error::new(ErrorKind::NotImplemented, "not implemented"))) + .external(|_| Err(Error::new(ErrorKind::NotImplemented, "not implemented"))) .parser(|_| Err::(Error::new(ErrorKind::NotImplemented, "not implemented"))) .build(); - let mut ctxt = from_document(xslt_doc, None, node_from_str, |_| Ok(String::new()))?; + let mut ctxt = from_document(xslt_doc, None, node_from_str, |_| Ok(Vec::new()))?; ctxt.context(vec![Item::Node(doc)], 0); ctxt.result_document(RNode::new_document()); let seq = ctxt.evaluate(&mut static_context)?; @@ -148,3 +156,59 @@ pub(crate) fn write_html_report( Ok(()) } + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::time::Duration; + + use insta::assert_snapshot; + use pact_matching::Mismatch; + use pact_verifier::verification_result::{ + VerificationExecutionResult, VerificationInteractionResult, VerificationMismatchResult, + }; + + use super::*; + + #[test] + fn html_report_with_default_xslt() { + let mut notice = HashMap::new(); + notice.insert("text".to_string(), "This pact is being verified because it is the latest version".to_string()); + let result = VerificationExecutionResult { + result: false, + notices: vec![notice], + errors: vec![ + ( + "GET /foo returns 200".to_string(), + VerificationMismatchResult::Mismatches { + mismatches: vec![ + Mismatch::StatusMismatch { + expected: 200, + actual: 404, + mismatch: "expected 200 but was 404".to_string(), + }, + ], + interaction_id: Some("interaction-123".to_string()), + }, + ), + ], + interaction_results: vec![ + VerificationInteractionResult { + interaction_id: None, + interaction_key: None, + consumer: "My Consumer".to_string(), + provider: "My Provider".to_string(), + provider_states: vec![], + description: "request 1".to_string(), + interaction_description: "POST /bar returns 201".to_string(), + result: Ok(()), + pending: false, + duration: Duration::from_millis(15), + }, + ], + ..VerificationExecutionResult::default() + }; + let xml = xml::to_xml_string(&result, "My Provider").unwrap(); + assert_snapshot!(apply_xslt(&xml, None).unwrap()); + } +} diff --git a/rust/pact_verifier_cli/src/reports/snapshots/pact_verifier_cli__reports__tests__html_report_with_default_xslt.snap b/rust/pact_verifier_cli/src/reports/snapshots/pact_verifier_cli__reports__tests__html_report_with_default_xslt.snap new file mode 100644 index 000000000..c644858b2 --- /dev/null +++ b/rust/pact_verifier_cli/src/reports/snapshots/pact_verifier_cli__reports__tests__html_report_with_default_xslt.snap @@ -0,0 +1,426 @@ +--- +source: pact_verifier_cli/src/reports/mod.rs +expression: "apply_xslt(&xml, None).unwrap()" +--- + +Pact Verification Report โ€” My Provider
Pact ยท Verification Report

My Provider

Provider Contract Verification

โœ—
Failed

Summary

1
Total
1
Passed
1
Failed
0
Pending

Notices

โ„นThis pact is being verified because it is the latest version

Failures

FailureGET /foo returns 200
TypeLocationDescriptionExpectedActual
Statusexpected 200 but was 404200404

Interaction Results

InteractionStatusDuration
POST /bar returns 201โœ“ Passed15 ms