Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions rust/pact_verifier/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1131,6 +1131,8 @@ pub async fn verify_provider_async<F: RequestFilterExecutor, S: ProviderStateExe
Some(context) => context.verification_properties.pending,
None => false
};
let consumer_name = pact.consumer().name.clone();
let interaction_count = pact.interactions().len();
let verify_result = verify_pact_internal(
&provider_info,
&filter,
Expand Down Expand Up @@ -1178,6 +1180,22 @@ pub async fn verify_provider_async<F: RequestFilterExecutor, S: ProviderStateExe
break;
}

let publish_options = publish_options.filter(|_| {
if all_interactions_verified(interaction_count, results.as_slice()) {
true
} else {
let message = format!("WARNING: Cannot publish verification for {} as not all interactions have been verified ({} of {} were verified). Re-run the verification without the filter parameters or environment variables to publish the verification.",
consumer_name, results.len(), interaction_count);
warn!("{}", message);
if verification_options.coloured_output {
verification_result.output.push(Yellow.paint(message).to_string());
} else {
verification_result.output.push(message);
}
false
}
});

if let Some(publish) = publish_options {
publish_result(results.as_slice(), &pact_source, &publish, metrics_data.as_ref(), verification_options.broker_request_retries).await;

Expand Down Expand Up @@ -1697,6 +1715,13 @@ pub(crate) fn process_comments(interaction: &dyn V4Interaction, output: &mut Vec
}
}

/// Verification results can only be published for a pact if every interaction in it was
/// verified. Results from a filtered run (or one that verified nothing) would be recorded by
/// the broker as a verification of the whole pact, so they are not published.
fn all_interactions_verified(interaction_count: usize, results: &[VerificationInteractionResult]) -> bool {
interaction_count > 0 && results.len() == interaction_count
}

async fn publish_result(
results: &[VerificationInteractionResult],
source: &PactSource,
Expand Down
33 changes: 33 additions & 0 deletions rust/pact_verifier/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1293,3 +1293,36 @@ async fn generate_request_applies_body_generators_to_a_form_urlencoded_request()
expect!(qty).to(be_less_or_equal_to(999));
expect!(params[2]).to(be_equal_to(("note", "gift+wrap")));
}

fn interaction_result(id: &str) -> VerificationInteractionResult {
VerificationInteractionResult {
interaction_id: Some(id.to_string()),
interaction_key: None,
consumer: "".to_string(),
provider: "".to_string(),
provider_states: vec![],
description: "".to_string(),
interaction_description: "".to_string(),
result: Ok(()),
pending: false,
duration: Default::default(),
}
}

#[test]
fn all_interactions_verified_is_true_when_every_interaction_has_a_result() {
let results = vec![interaction_result("1"), interaction_result("2")];
expect!(super::all_interactions_verified(2, &results)).to(be_true());
}

#[test]
fn all_interactions_verified_is_false_when_only_some_interactions_were_verified() {
let results = vec![interaction_result("1")];
expect!(super::all_interactions_verified(3, &results)).to(be_false());
}

#[test]
fn all_interactions_verified_is_false_when_no_interactions_were_verified() {
expect!(super::all_interactions_verified(1, &[])).to(be_false());
expect!(super::all_interactions_verified(0, &[])).to(be_false());
}
190 changes: 190 additions & 0 deletions rust/pact_verifier/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,196 @@ async fn verify_multiple_pacts() {
expect!(result.unwrap().result).to(be_false());
}

/// Mirrors pact-ruby: verification results are only published for a pact when every
/// interaction in it has been verified. A filtered run must not publish a result for a pact
/// where only some (or none) of the interactions ran, as the broker records it against the
/// whole pact.
#[test_log::test(tokio::test)]
async fn does_not_publish_results_for_pacts_where_interactions_were_filtered_out() {
let provider = PactBuilder::new_v4("filtered_consumer", "filtered_provider")
.interaction("a retrieve Mallory request", "", |mut i| {
i.test_name("does_not_publish_results_for_pacts_where_interactions_were_filtered_out");
i.request.method("GET");
i.request.path("/mallory");
i.request.query_param("name", "ron");
i.request.query_param("status", "good");
i.response.ok().content_type("text/html").body("\"That is some good Mallory.\"");
i
})
.start_mock_server(None, None);

let pact_one = read_file(&fixture_path("pact-one.json")).unwrap();
let pact_two = read_file(&fixture_path("pact-two.json")).unwrap();

// Note: there is no interaction for publishing pact-two results. If the verifier publishes
// them, the mock broker gets an unexpected request and the test fails.
let server = PactBuilderAsync::new("RustPactVerifier", "PactBrokerFilteredVerification")
.interaction("a request to the pact broker root", "", |mut i| async move {
i.request
.path("/")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response
.header("Content-Type", "application/hal+json")
.json_body(json_pattern!({
"_links": {
"pb:provider-pacts-for-verification": {
"href": like!("http://localhost/pacts/provider/{provider}/for-verification"),
"title": like!("Pact versions to be verified for the specified provider"),
"templated": like!(true)
}
}
}));
i
})
.await
.interaction("a request to the pacts for verification endpoint", "", |mut i| async move {
i.request
.get()
.path("/pacts/provider/Alice%20Service/for-verification")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response
.header("Content-Type", "application/hal+json")
.json_body(json_pattern!({
"_links": {
"self": {
"href": like!("http://localhost/pacts/provider/Alice%20Service/for-verification"),
"title": like!("Pacts to be verified")
}
}
}));
i
})
.await
.interaction("a request for the pacts to verify", "", |mut i| async move {
i.request
.post()
.path("/pacts/provider/Alice%20Service/for-verification")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response
.header("Content-Type", "application/hal+json")
.json_body(json_pattern!({
"_embedded": {
"pacts": [
{
"shortDescription": "pact-one",
"_links": { "self": { "name": "pact-one", "href": "/pact-one", "templated": false } },
"verificationProperties": { "pending": false, "notices": [] }
},
{
"shortDescription": "pact-two",
"_links": { "self": { "name": "pact-two", "href": "/pact-two", "templated": false } },
"verificationProperties": { "pending": false, "notices": [] }
}
]
},
"_links": {
"self": {
"href": like!("http://localhost/pacts/provider/Alice%20Service/for-verification"),
"title": like!("Pacts to be verified")
}
}
}));
i
})
.await
.interaction("pact-one", "", |mut i| async move {
i.request
.get()
.path("/pact-one")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response
.header("Content-Type", "application/json")
.body(pact_one);
i
})
.await
.interaction("pact-two", "", |mut i| async move {
i.request
.get()
.path("/pact-two")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response
.header("Content-Type", "application/json")
.body(pact_two);
i
})
.await
.interaction("pact-one results", "", |mut i| async move {
i.request
.post()
.path("/pact-one/results")
.header("content-type", "application/json")
.json_body(json_pattern!({
"providerApplicationVersion": "1.2.3",
"success": true,
"testResults": [
{ "interactionId": "pact-one", "success": true }
],
"verifiedBy": { "implementation": "Pact-Rust", "version": like!("1.0.0") }
}));
i
})
.await
.start_mock_server(None, None);

#[allow(deprecated)]
let provider_info = ProviderInfo {
name: "Alice Service".to_string(),
host: "127.0.0.1".to_string(),
port: provider.url().port(),
transports: vec![ ProviderTransport {
transport: "HTTP".to_string(),
port: provider.url().port(),
path: None,
scheme: Some("http".to_string())
} ],
.. ProviderInfo::default()
};

let pact_source = PactSource::BrokerWithDynamicConfiguration {
provider_name: "Alice Service".to_string(),
broker_url: server.url().to_string(),
enable_pending: false,
include_wip_pacts_since: None,
provider_tags: vec![],
provider_branch: None,
selectors: vec![],
auth: None,
links: vec![]
};

let verification_options: VerificationOptions<NullRequestFilterExecutor> = VerificationOptions::default();
let provider_state_executor = Arc::new(DummyProviderStateExecutor{});
let publish_options = PublishOptions {
provider_version: Some("1.2.3".to_string()),
build_url: None,
provider_tags: vec![],
provider_branch: None,
};

let result = verify_provider_async(
provider_info,
vec![ pact_source ],
FilterInfo::Description("a retrieve Mallory request".to_string()),
vec![],
&verification_options,
Some(&publish_options),
&provider_state_executor,
None
).await.unwrap();

expect!(result.result).to(be_true());
expect!(result.interaction_results.len()).to(be_equal_to(1));
expect!(result.output.iter().any(|line| line.contains(
"Cannot publish verification for Consumer as not all interactions have been verified (0 of 1 were verified)"
))).to(be_true());
}

fn read_file(path: &PathBuf) -> anyhow::Result<String> {
let mut f = File::open(path)?;
let mut buf = String::new();
Expand Down
Loading