Skip to content
Draft
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
4 changes: 4 additions & 0 deletions compatibility-suite-ffi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,7 @@ harness = false
[[test]]
name = "plugins"
harness = false

[[test]]
name = "integration_json"
harness = false
1 change: 1 addition & 0 deletions compatibility-suite-ffi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ cargo test --no-fail-fast
| `generators` | V3 `generators` and `http_generators`, V4 `generators` |
| `message` | V3 `message_consumer`, V4 `message_consumer`, `synchronous_message_consumer`, `v4` |
| `plugins` | V4 `plugins/*`: lifecycle, HTTP, message, synchronous message and transports (needs the matt, csv, avro and protobuf plugins installed) |
| `integration_json` | FFI-only `features/ffi/*`: matching rules defined with integration JSON through `pactffi_with_body` (e.g. `pact:matcher:combine`), which the shared suite can't express as it defines rules in the Pact file format |

Scenarios tagged `wip` are skipped. `tests/matching.rs` also skips one known failure: the mock server reads a
0-byte body as no body, so the V4 "not empty matcher with binary data (negative case)" scenario can't get its
Expand Down
144 changes: 144 additions & 0 deletions compatibility-suite-ffi/features/ffi/integration_json.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
@consumer
Feature: Matching rules combined with OR in integration JSON
FFI consumers (Pact JS, Go, PHP, Python, Ruby, ...) define matching rules by embedding integration JSON in the
bodies they pass to pactffi_with_body. A "pact:matcher:type" array combined with "pact:matcher:combine": "OR"
is written to the Pact file as a single rule list combined with OR, which the V3 and V4 specifications support.
See pact-foundation/pact-reference#249.

Scenario Outline: Matching rules combined with OR are written to the <spec> Pact file
Given a <spec> HTTP interaction with a POST request with the following JSON body:
"""
{
"id": {
"pact:matcher:type": [
{ "pact:matcher:type": "regex", "regex": "^\\d+$" },
{ "pact:matcher:type": "regex", "regex": "^[a-z]+$" }
],
"pact:matcher:combine": "<combine>",
"value": "123"
}
}
"""
When the Pact file for the test is generated
Then the request body in the Pact file will be '{"id": "123"}'
And the request body matching rules in the Pact file will be:
"""
{
"$.id": {
"combine": "OR",
"matchers": [
{ "match": "regex", "regex": "^\\d+$" },
{ "match": "regex", "regex": "^[a-z]+$" }
]
}
}
"""

Examples:
| spec | combine |
| V3 | OR |
| V4 | OR |
| V3 | or |

Scenario Outline: The <spec> mock server accepts a value matching any of the matching rules combined with OR
Given a <spec> HTTP interaction with a POST request with the following JSON body:
"""
{
"id": {
"pact:matcher:type": [
{ "pact:matcher:type": "regex", "regex": "^\\d+$" },
{ "pact:matcher:type": "regex", "regex": "^[a-z]+$" }
],
"pact:matcher:combine": "OR",
"value": "123"
}
}
"""
When the mock server is started with the interaction
And a POST request is made to the mock server with the JSON body '<body>'
Then the mock server status will be <status>

Examples:
| spec | body | status |
| V3 | {"id": "123"} | OK |
| V3 | {"id": "abc"} | OK |
| V3 | {"id": "A1"} | NOT OK |
| V4 | {"id": "123"} | OK |
| V4 | {"id": "abc"} | OK |
| V4 | {"id": "A1"} | NOT OK |

Scenario Outline: The <spec> mock server accepts null or an object matching its nested matching rules
Given a <spec> HTTP interaction with a POST request with the following JSON body:
"""
{
"address": {
"pact:matcher:type": [
{ "pact:matcher:type": "type" },
{ "pact:matcher:type": "null" }
],
"pact:matcher:combine": "OR",
"value": {
"number": { "pact:matcher:type": "integer", "value": 100 },
"street": { "pact:matcher:type": "type", "value": "Main Street" }
}
}
}
"""
When the mock server is started with the interaction
And a POST request is made to the mock server with the JSON body '<body>'
Then the mock server status will be <status>

Examples:
| spec | body | status |
| V3 | {"address": {"number": 42, "street": "High Street"}} | OK |
| V3 | {"address": null} | OK |
| V3 | {"address": {"number": "42", "street": "High St"}} | NOT OK |
| V4 | {"address": {"number": 42, "street": "High Street"}} | OK |
| V4 | {"address": null} | OK |
| V4 | {"address": {"number": "42", "street": "High St"}} | NOT OK |

Scenario: Matching rules combined with OR replace a matcher wrapped as their example value
A path has a single list of rules, so the OR rules replace the wrapped matcher's rule (as Pact-JVM's `or` does)
and only the wrapped matcher's example value is kept.
Given a V4 HTTP interaction with a POST request with the following JSON body:
"""
{
"id": {
"pact:matcher:type": [
{ "pact:matcher:type": "integer" },
{ "pact:matcher:type": "null" }
],
"pact:matcher:combine": "OR",
"value": { "pact:matcher:type": "regex", "regex": "^\\d+$", "value": "100" }
}
}
"""
When the Pact file for the test is generated
Then the request body in the Pact file will be '{"id": "100"}'
And the request body matching rules in the Pact file will be:
"""
{
"$.id": {
"combine": "OR",
"matchers": [ { "match": "integer" }, { "match": "null" } ]
}
}
"""

Scenario: An invalid combine value is rejected
Given a V4 HTTP interaction with a POST request with the following JSON body:
"""
{
"id": {
"pact:matcher:type": [
{ "pact:matcher:type": "integer" },
{ "pact:matcher:type": "null" }
],
"pact:matcher:combine": "XOR",
"value": 1
}
}
"""
When the Pact file for the test is generated
Then the request body in the Pact file will be '{"id": null}'
And the request body in the Pact file will have no matching rules
198 changes: 198 additions & 0 deletions compatibility-suite-ffi/tests/integration_json.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
//! FFI-only scenarios: matching rules defined with integration JSON (the format FFI consumers pass to
//! `pactffi_with_body`), which the shared compatibility suite cannot express since it defines matching rules in the
//! Pact file format.

use std::env;
use std::fs;
use std::path::PathBuf;

use anyhow::{anyhow, bail};
use cucumber::gherkin::Step;
use cucumber::{given, then, when, World};
use serde_json::Value;

use pact_ffi_compat::ffi::{self, InteractionHandle, InteractionPart_Request, PactHandle, PactSpecification,
PactSpecification_V3, PactSpecification_V4};
use pact_ffi_compat::{model, trace};

const FEATURES: &str = "features/ffi";

#[derive(Debug, Default, World)]
struct IntegrationJsonWorld {
scenario_id: String,
spec: String,
pact: Option<PactHandle>,
interaction: Option<InteractionHandle>,
port: Option<i32>,
pact_json: Value,
}

impl IntegrationJsonWorld {
fn specification(&self) -> anyhow::Result<PactSpecification> {
match self.spec.as_str() {
"V3" => Ok(PactSpecification_V3),
"V4" => Ok(PactSpecification_V4),
s => bail!("unsupported specification {s}"),
}
}

fn pact_dir(&self) -> PathBuf {
env::current_dir().unwrap().join("target/compatibility-suite/ffi").join(&self.scenario_id)
}

fn pact(&self) -> anyhow::Result<PactHandle> {
self.pact.ok_or_else(|| anyhow!("no pact is being defined"))
}

fn request(&self) -> &Value {
&self.pact_json["interactions"][0]["request"]
}

/// The V3 Pact file has the body as JSON, the V4 one as `{"content": ...}`.
fn request_body(&self) -> &Value {
let body = &self.request()["body"];
if self.spec == "V4" { &body["content"] } else { body }
}

fn shutdown(&mut self) {
if let Some(port) = self.port.take() {
ffi::cleanup_mock_server(port);
}
if let Some(pact) = self.pact.take() {
ffi::free_pact_handle(pact);
}
}
}

fn traced(step: &Step) {
trace::step(&step.keyword, &step.value);
}

fn docstring(step: &Step) -> anyhow::Result<&str> {
step.docstring.as_deref().ok_or_else(|| anyhow!("step has no doc string"))
}

#[given(regex = r"^a (V3|V4) HTTP interaction with a POST request with the following JSON body:$")]
fn interaction_with_body(world: &mut IntegrationJsonWorld, step: &Step, spec: String) -> anyhow::Result<()> {
traced(step);
world.spec = spec;
let pact = ffi::new_pact(&format!("{}-integration-json-c", world.spec.to_lowercase()), "p");
ffi::with_specification(pact, world.specification()?);
let i = ffi::new_interaction(pact, "a request with integration JSON");
ffi::with_request(i, "POST", "/path");
if !ffi::with_body(i, InteractionPart_Request, "application/json", docstring(step)?) {
bail!("pactffi_with_body failed");
}
ffi::response_status(i, 200);
world.pact = Some(pact);
world.interaction = Some(i);
Ok(())
}

#[when("the Pact file for the test is generated")]
fn pact_generated(world: &mut IntegrationJsonWorld, step: &Step) -> anyhow::Result<()> {
traced(step);
let dir = world.pact_dir();
fs::create_dir_all(&dir)?;
let rc = ffi::pact_handle_write_file(world.pact()?, &dir.to_string_lossy(), true);
if rc != 0 {
bail!("pactffi_pact_handle_write_file failed with {rc}");
}
let file = fs::read_dir(&dir)?.next().ok_or_else(|| anyhow!("no pact file written"))??.path();
world.pact_json = serde_json::from_str(&fs::read_to_string(file)?)?;
Ok(())
}

#[when("the mock server is started with the interaction")]
fn mock_server_started(world: &mut IntegrationJsonWorld, step: &Step) -> anyhow::Result<()> {
traced(step);
let port = ffi::create_mock_server_for_transport(world.pact()?, "::1", 0, "http");
if port < 0 {
bail!("pactffi_create_mock_server_for_transport failed with {port}");
}
world.port = Some(port);
Ok(())
}

#[when(regex = r"^a POST request is made to the mock server with the JSON body '(.*)'$")]
async fn request_made(world: &mut IntegrationJsonWorld, step: &Step, body: String) -> anyhow::Result<()> {
traced(step);
let port = world.port.ok_or_else(|| anyhow!("mock server not started"))?;
let url = format!("http://[::1]:{port}/path");
let res = reqwest::Client::new().post(&url).header("content-type", "application/json").body(body).send().await?;
trace::note(format!("HTTP POST {url} -> {}", res.status()));
Ok(())
}

#[then(regex = r"^the mock server status will be (OK|NOT OK)$")]
fn mock_server_status(world: &mut IntegrationJsonWorld, step: &Step, status: String) -> anyhow::Result<()> {
traced(step);
let port = world.port.ok_or_else(|| anyhow!("mock server not started"))?;
let matched = ffi::mock_server_matched(port);
let mismatches = ffi::mock_server_mismatches(port).unwrap_or_default();
match (status.as_str(), matched) {
("OK", false) => bail!("Expected the mock server to match, but it had mismatches: {mismatches}"),
("NOT OK", true) => bail!("Expected the mock server to have mismatches, but it matched"),
_ => Ok(()),
}
}

#[then(regex = r"^the request body in the Pact file will be '(.*)'$")]
fn request_body(world: &mut IntegrationJsonWorld, step: &Step, expected: String) -> anyhow::Result<()> {
traced(step);
let expected: Value = serde_json::from_str(&expected)?;
let actual = world.request_body();
if *actual != expected {
bail!("Expected the request body to be {expected} but was {actual}");
}
Ok(())
}

#[then("the request body matching rules in the Pact file will be:")]
fn request_body_rules(world: &mut IntegrationJsonWorld, step: &Step) -> anyhow::Result<()> {
traced(step);
let expected: Value = serde_json::from_str(docstring(step)?)?;
let actual = &world.request()["matchingRules"]["body"];
if *actual != expected {
bail!("Expected the request body matching rules to be {expected} but were {actual}");
}
Ok(())
}

#[then("the request body in the Pact file will have no matching rules")]
fn no_request_body_rules(world: &mut IntegrationJsonWorld, step: &Step) -> anyhow::Result<()> {
traced(step);
let rules = &world.request()["matchingRules"]["body"];
if !(rules.is_null() || rules.as_object().is_some_and(|o| o.is_empty())) {
bail!("Expected no request body matching rules but found {rules}");
}
Ok(())
}

#[tokio::main]
async fn main() {
let lib = model::ffi_lib();
ffi::load(&lib).unwrap_or_else(|e| panic!("could not load {lib}: {e}"));

IntegrationJsonWorld::cucumber()
.max_concurrent_scenarios(1)
.fail_on_skipped()
.before(|_feature, _rule, scenario, world| Box::pin(async move {
trace::reset();
world.scenario_id = scenario.name.replace(['/', '\\', ':'], "_");
let _ = fs::remove_dir_all(world.pact_dir());
}))
.after(|feature, _rule, scenario, _ev, world| Box::pin(async move {
if let Some(world) = world {
world.shutdown();
}
let dir = env::var("FFI_TRACE_DIR").unwrap_or_else(|_| "target/ffi-trace".into());
let path = PathBuf::from(dir).join(format!("FFI {}", feature.name))
.join(format!("{}.md", scenario.name.replace(['/', '\\', ':'], "_")));
if let Err(e) = trace::write(&path, &feature.name, &scenario.name) {
eprintln!("could not write trace {}: {e}", path.display());
}
}))
.filter_run_and_exit(FEATURES, |_feature, _rule, scenario| !scenario.tags.iter().any(|t| t == "wip"))
.await;
}
Loading
Loading