contracts: consumer-driven contract testing lab (Spring Cloud Contract 5.0.3, Stubborn Contract 0.2.4, Pact JVM 4.7.7 on Spring Boot 4.2.0)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b7h4ZNF4BDUpJk3Zou
This commit is contained in:
Claude
2026-11-29 02:29:20 +05:30
parent d7497c8ab1
commit 8a429ca578
46 changed files with 1986 additions and 0 deletions
+2
View File
@@ -10,6 +10,7 @@ Runnable companion code for the testing posts on [ankurm.com](https://ankurm.com
| [`instancio/`](instancio) | Instancio: Generate Realistic Test Data Automatically in Java | Instancio 6.1.0, JUnit 6.1.3, JDK 25 | | [`instancio/`](instancio) | Instancio: Generate Realistic Test Data Automatically in Java | Instancio 6.1.0, JUnit 6.1.3, JDK 25 |
| [`gatling-spring-boot/`](gatling-spring-boot) | Load Testing Spring Boot with Gatling's Java DSL (and How It Compares to k6) | Gatling 3.16.0, Spring Boot 4.1.2, k6 v2.3.0, JDK 25 | | [`gatling-spring-boot/`](gatling-spring-boot) | Load Testing Spring Boot with Gatling's Java DSL (and How It Compares to k6) | Gatling 3.16.0, Spring Boot 4.1.2, k6 v2.3.0, JDK 25 |
| [`spring-test-slices/`](spring-test-slices) | Spring Boot 4 Test Slices: @WebMvcTest, @JsonTest, @RestClientTest and @DataJpaTest Compared | Spring Boot 4.1.2, JDK 25 | | [`spring-test-slices/`](spring-test-slices) | Spring Boot 4 Test Slices: @WebMvcTest, @JsonTest, @RestClientTest and @DataJpaTest Compared | Spring Boot 4.1.2, JDK 25 |
| [`contracts/`](contracts) | Consumer-Driven Contract Testing: Spring Cloud Contract vs Pact for Spring Boot | Spring Boot 4.2.0, Spring Cloud Contract 5.0.3, Stubborn Contract 0.2.4, Pact JVM 4.7.7, JDK 25 |
Every module keeps the real output of its tests in `output/`. Each test writes the transcript and asserts the same facts, so the numbers in the posts fail the build if they stop being true. Every module keeps the real output of its tests in `output/`. Each test writes the transcript and asserts the same facts, so the numbers in the posts fail the build if they stop being true.
@@ -18,4 +19,5 @@ cd mockito && ./scripts/run-all.sh
cd ../junit-6-migration && ./scripts/run-all.sh cd ../junit-6-migration && ./scripts/run-all.sh
cd ../assertj && ./scripts/run-all.sh cd ../assertj && ./scripts/run-all.sh
cd ../spring-test-slices && ./scripts/run-all.sh cd ../spring-test-slices && ./scripts/run-all.sh
cd ../contracts && ./scripts/run-all.sh
``` ```
+2
View File
@@ -0,0 +1,2 @@
target/
target-stubborn/
+66
View File
@@ -0,0 +1,66 @@
# contracts
Consumer-driven contract testing for a Spring Boot 4.2 service pair, done three ways against the same API:
**Spring Cloud Contract 5.0.3**, **Stubborn Contract 0.2.4** (its continuation) and **Pact JVM 4.7.7**.
Companion to the ankurm.com post *Consumer-Driven Contract Testing: Spring Cloud Contract vs Pact for Spring Boot*.
| Module | Role |
|---|---|
| [`orders-producer/`](orders-producer) | Boot app serving `GET /orders/{id}` and `POST /orders`. Holds the YAML contracts, the base class for the generated tests, and the Pact provider verification. Publishes `orders-producer-1.0.0-stubs.jar` |
| [`checkout-consumer/`](checkout-consumer) | Boot app with a `RestClient` based `OrderClient`. Has a Pact consumer test (writes the pact) and a stub runner test (uses the producer's stubs) |
`pom-stubborn.xml` in each module is the same build with Stubborn Contract coordinates (`sh.stubborn:*`); the contracts and sources are untouched.
## Versions
| | |
|---|---|
| JDK | Temurin 25.0.5.1 (LTS) |
| Spring Boot | 4.2.0 |
| Spring Cloud Contract | 5.0.3 (last release; it is no longer in the Spring Cloud 2026.0.0 BOM) |
| Stubborn Contract | 0.2.4 |
| Pact JVM | 4.7.7 (`consumer:junit5`, `provider:junit5`) |
| REST Assured | 7.0.0 (overrides the 5.5.7 that Spring Cloud Contract 5.0.3 brings) |
| WireMock | 3.13.2 |
## Run it
```bash
export JAVA_HOME=<jdk-25>
./scripts/run-all.sh # about 5 minutes, regenerates everything in output/
```
Or by hand, in this order (the pact has to exist before the producer verifies it, the stubs before the consumer uses them):
```bash
(cd checkout-consumer && mvn clean test -Dtest=OrdersPactConsumerTest)
mkdir -p orders-producer/src/test/resources/pacts
cp checkout-consumer/target/pacts/*.json orders-producer/src/test/resources/pacts/
(cd orders-producer && mvn clean install) # generated tests + pact verification + stubs jar
(cd checkout-consumer && mvn clean test -Dtest=OrdersStubConsumerTest)
```
Simulate a producer change with an environment variable (read as `orders.variant`):
```bash
ORDERS_VARIANT=rename-total mvn clean test # baseline | add-field | rename-total | drop-items | total-string
```
Always use `clean` after editing a contract: Spring Cloud Contract skips generation when it thinks the generated sources are up to date.
## Output
Every file in [`output/`](output) comes from a real run of `scripts/run-all.sh`, filtered by `scripts/clean.py` (launcher noise, Spring Boot banners, stack frames and WireMock request dumps removed; nothing retyped). Timings are replaced by `N`.
| File | What it shows |
|---|---|
| `01-versions.txt` | JDK, Maven and the resolved contract libraries |
| `02-consumer-pact-run.txt`, `03-pact-file.json` | the consumer test run and the pact it wrote |
| `04-producer-baseline.txt` | contract test generation, generated tests green, pact verified, stubs jar built |
| `05-generated-test.txt` | the JUnit class Spring Cloud Contract generated from the YAML |
| `06-stubs-jar.txt`, `07-wiremock-mapping.json` | what is inside the stubs jar |
| `08-consumer-stub-run.txt` | the consumer against the producer's stubs |
| `10`..`13-variant-*.txt` | four producer changes, each run through both tools |
| `20-restassured-5-groovy-5.txt` | the REST Assured 5.5.7 / Groovy 5.1.3 failure |
| `21`, `22` | producer renames a field in its contract and republishes; consumer meets the new stubs |
| `30`, `31` | the same contracts under Stubborn Contract 0.2.4 |
@@ -0,0 +1,76 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
<relativePath/>
</parent>
<groupId>com.ankurm.contracts</groupId>
<artifactId>checkout-consumer-stubborn</artifactId>
<version>1.0.0</version>
<properties>
<java.version>25</java.version>
<maven.compiler.release>25</maven.compiler.release>
<stubborn.version>0.2.4</stubborn.version>
<pact.version>4.7.7</pact.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>sh.stubborn</groupId>
<artifactId>stubborn-contract-dependencies</artifactId>
<version>${stubborn.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-restclient</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-restclient-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Cloud Contract: runs the producer's published stubs as WireMock -->
<dependency>
<groupId>sh.stubborn</groupId>
<artifactId>stubborn-contract-starter-stub-runner</artifactId>
<scope>test</scope>
</dependency>
<!-- Pact: the consumer writes the contract from its own tests -->
<dependency>
<groupId>au.com.dius.pact.consumer</groupId>
<artifactId>junit5</artifactId>
<version>${pact.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<directory>target-stubborn</directory>
<testSourceDirectory>src/test-stubborn/java</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
+82
View File
@@ -0,0 +1,82 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
<relativePath/>
</parent>
<groupId>com.ankurm.contracts</groupId>
<artifactId>checkout-consumer</artifactId>
<version>1.0.0</version>
<properties>
<java.version>25</java.version>
<maven.compiler.release>25</maven.compiler.release>
<scc.version>5.0.3</scc.version>
<rest-assured.version>7.0.0</rest-assured.version>
<pact.version>4.7.7</pact.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured-bom</artifactId>
<version>${rest-assured.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-dependencies</artifactId>
<version>${scc.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-restclient</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-restclient-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Cloud Contract: runs the producer's published stubs as WireMock -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
<scope>test</scope>
</dependency>
<!-- Pact: the consumer writes the contract from its own tests -->
<dependency>
<groupId>au.com.dius.pact.consumer</groupId>
<artifactId>junit5</artifactId>
<version>${pact.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,11 @@
package com.ankurm.contracts.checkout;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CheckoutApplication {
public static void main(String[] args) {
SpringApplication.run(CheckoutApplication.class, args);
}
}
@@ -0,0 +1,24 @@
package com.ankurm.contracts.checkout;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;
@Service
public class CheckoutService {
private final OrderClient orders;
public CheckoutService(OrderClient orders) {
this.orders = orders;
}
/** What the customer owes for a confirmed order. Anything else is not payable. */
public BigDecimal amountDue(long orderId) {
Order order = orders.find(orderId)
.orElseThrow(() -> new IllegalArgumentException("no such order " + orderId));
if (!"CONFIRMED".equals(order.status())) {
throw new IllegalStateException("order " + orderId + " is " + order.status());
}
return order.total();
}
}
@@ -0,0 +1,10 @@
package com.ankurm.contracts.checkout;
import java.math.BigDecimal;
/**
* The consumer's view of an order: only the three fields checkout actually uses.
* The producer also sends currency and items; this service never reads them, so a Pact contract
* written from this class does not mention them either.
*/
public record Order(long id, String status, BigDecimal total) {}
@@ -0,0 +1,44 @@
package com.ankurm.contracts.checkout;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
@Component
public class OrderClient {
public record Line(String sku, int qty) {}
private record CreateOrder(List<Line> items) {}
private final RestClient http;
public OrderClient(RestClient.Builder builder, @Value("${orders.base-url}") String baseUrl) {
this.http = builder.baseUrl(baseUrl).build();
}
public Optional<Order> find(long id) {
return http.get().uri("/orders/{id}", id)
.exchange((request, response) -> {
if (response.getStatusCode() == HttpStatus.NOT_FOUND) {
return Optional.<Order>empty();
}
if (response.getStatusCode().isError()) {
throw new IllegalStateException("orders-producer answered " + response.getStatusCode());
}
return Optional.of(response.bodyTo(Order.class));
});
}
public Order create(List<Line> lines) {
return http.post().uri("/orders")
.contentType(MediaType.APPLICATION_JSON)
.body(new CreateOrder(lines))
.retrieve()
.body(Order.class);
}
}
@@ -0,0 +1 @@
orders.base-url=http://localhost:8080
@@ -0,0 +1,49 @@
package com.ankurm.contracts.checkout;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.math.BigDecimal;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import sh.stubborn.contract.stubrunner.spring.AutoConfigureStubRunner;
import sh.stubborn.contract.stubrunner.StubsMode;
/**
* Consumer side of a Spring Cloud Contract. The stubs come from the producer's build, not from this
* project: the stub runner finds orders-producer-1.0.0-stubs.jar in ~/.m2, starts WireMock on port 8090
* and serves exactly the requests and responses the producer's contracts describe.
*/
@SpringBootTest(properties = "orders.base-url=http://localhost:8090")
@AutoConfigureStubRunner(
ids = "com.ankurm.contracts:orders-producer-stubborn:+:stubs:8090",
stubsMode = StubsMode.LOCAL)
class OrdersStubbornConsumerTest {
@Autowired
CheckoutService checkout;
@Autowired
OrderClient client;
@Test
void amountDueComesFromTheStubbedOrder() {
assertThat(checkout.amountDue(42)).isEqualByComparingTo(new BigDecimal("129.90"));
}
@Test
void unknownOrderIsNotPayable() {
assertThatThrownBy(() -> checkout.amountDue(999))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("no such order 999");
}
@Test
void createReturnsTheNewOrder() {
Order order = client.create(List.of(new OrderClient.Line("BOOK-1", 2)));
assertThat(order.id()).isEqualTo(1001);
assertThat(order.status()).isEqualTo("NEW");
}
}
@@ -0,0 +1,110 @@
package com.ankurm.contracts.checkout;
import static org.assertj.core.api.Assertions.assertThat;
import au.com.dius.pact.consumer.MockServer;
import au.com.dius.pact.consumer.dsl.LambdaDsl;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.consumer.junit5.PactConsumerTestExt;
import au.com.dius.pact.consumer.junit5.PactTestFor;
import au.com.dius.pact.core.model.PactSpecVersion;
import au.com.dius.pact.core.model.RequestResponsePact;
import au.com.dius.pact.core.model.annotations.Pact;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.web.client.RestClient;
/**
* Consumer side of a Pact contract. Running this class does two things: it checks that OrderClient
* works against a mock server shaped like the contract, and it writes target/pacts/*.json, the file
* the producer will later verify itself against.
*
* Only the fields checkout reads (id, status, total) appear in the contract, and they are matched by
* type, not by value. That is the consumer-driven part: the producer stays free to change anything else.
*/
@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "orders-producer", pactVersion = PactSpecVersion.V3)
class OrdersPactConsumerTest {
private static final Map<String, String> JSON = Map.of("Content-Type", "application/json");
@Pact(consumer = "checkout-consumer")
RequestResponsePact orderExists(PactDslWithProvider builder) {
return builder
.given("order 42 exists and is confirmed")
.uponReceiving("a request for order 42")
.path("/orders/42")
.method("GET")
.willRespondWith()
.status(200)
.headers(JSON)
.body(LambdaDsl.newJsonBody(o -> o
.integerType("id", 42)
.stringType("status", "CONFIRMED")
.decimalType("total", 129.90)).build())
.toPact();
}
@Pact(consumer = "checkout-consumer")
RequestResponsePact orderMissing(PactDslWithProvider builder) {
return builder
.given("order 999 does not exist")
.uponReceiving("a request for an unknown order")
.path("/orders/999")
.method("GET")
.willRespondWith()
.status(404)
.toPact();
}
@Pact(consumer = "checkout-consumer")
RequestResponsePact orderCreated(PactDslWithProvider builder) {
return builder
.given("orders can be created")
.uponReceiving("a request to create an order")
.path("/orders")
.method("POST")
.headers(JSON)
.body(LambdaDsl.newJsonBody(o -> o
.array("items", a -> a.object(l -> l.stringType("sku", "BOOK-1").integerType("qty", 2)))).build())
.willRespondWith()
.status(201)
.headers(JSON)
.body(LambdaDsl.newJsonBody(o -> o
.integerType("id", 1001)
.stringType("status", "NEW")
.decimalType("total", 129.90)).build())
.toPact();
}
@Test
@PactTestFor(pactMethod = "orderExists")
void readsAnExistingOrder(MockServer server) {
OrderClient client = new OrderClient(RestClient.builder(), server.getUrl());
Order order = client.find(42).orElseThrow();
assertThat(order.status()).isEqualTo("CONFIRMED");
assertThat(order.total()).isEqualByComparingTo(new BigDecimal("129.90"));
}
@Test
@PactTestFor(pactMethod = "orderMissing")
void anUnknownOrderIsEmpty(MockServer server) {
OrderClient client = new OrderClient(RestClient.builder(), server.getUrl());
assertThat(client.find(999)).isEmpty();
}
@Test
@PactTestFor(pactMethod = "orderCreated")
void createsAnOrder(MockServer server) {
OrderClient client = new OrderClient(RestClient.builder(), server.getUrl());
Order order = client.create(List.of(new OrderClient.Line("BOOK-1", 2)));
assertThat(order.id()).isEqualTo(1001);
assertThat(order.status()).isEqualTo("NEW");
}
}
@@ -0,0 +1,49 @@
package com.ankurm.contracts.checkout;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.math.BigDecimal;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.contract.stubrunner.spring.AutoConfigureStubRunner;
import org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties;
/**
* Consumer side of a Spring Cloud Contract. The stubs come from the producer's build, not from this
* project: the stub runner finds orders-producer-1.0.0-stubs.jar in ~/.m2, starts WireMock on port 8090
* and serves exactly the requests and responses the producer's contracts describe.
*/
@SpringBootTest(properties = "orders.base-url=http://localhost:8090")
@AutoConfigureStubRunner(
ids = "com.ankurm.contracts:orders-producer:+:stubs:8090",
stubsMode = StubRunnerProperties.StubsMode.LOCAL)
class OrdersStubConsumerTest {
@Autowired
CheckoutService checkout;
@Autowired
OrderClient client;
@Test
void amountDueComesFromTheStubbedOrder() {
assertThat(checkout.amountDue(42)).isEqualByComparingTo(new BigDecimal("129.90"));
}
@Test
void unknownOrderIsNotPayable() {
assertThatThrownBy(() -> checkout.amountDue(999))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("no such order 999");
}
@Test
void createReturnsTheNewOrder() {
Order order = client.create(List.of(new OrderClient.Line("BOOK-1", 2)));
assertThat(order.id()).isEqualTo(1001);
assertThat(order.status()).isEqualTo("NEW");
}
}
@@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
<relativePath/>
</parent>
<groupId>com.ankurm.contracts</groupId>
<artifactId>orders-producer-stubborn</artifactId>
<version>1.0.0</version>
<properties>
<java.version>25</java.version>
<maven.compiler.release>25</maven.compiler.release>
<stubborn.version>0.2.4</stubborn.version>
<pact.version>4.7.7</pact.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>sh.stubborn</groupId>
<artifactId>stubborn-contract-dependencies</artifactId>
<version>${stubborn.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>sh.stubborn</groupId>
<artifactId>stubborn-contract-starter-verifier</artifactId>
<scope>test</scope>
</dependency>
<!-- Pact provider verification: plain JUnit 5 + HTTP, no Spring integration module -->
<dependency>
<groupId>au.com.dius.pact.provider</groupId>
<artifactId>junit5</artifactId>
<version>${pact.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<directory>target-stubborn</directory>
<plugins>
<plugin>
<groupId>sh.stubborn</groupId>
<artifactId>stubborn-contract-maven-plugin</artifactId>
<version>${stubborn.version}</version>
<extensions>true</extensions>
<configuration>
<testFramework>JUNIT5</testFramework>
<testMode>EXPLICIT</testMode>
<baseClassForTests>com.ankurm.contracts.orders.ContractVerifierBase</baseClassForTests>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
+94
View File
@@ -0,0 +1,94 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
<relativePath/>
</parent>
<groupId>com.ankurm.contracts</groupId>
<artifactId>orders-producer</artifactId>
<version>1.0.0</version>
<properties>
<java.version>25</java.version>
<maven.compiler.release>25</maven.compiler.release>
<scc.version>5.0.3</scc.version>
<rest-assured.version>7.0.0</rest-assured.version>
<pact.version>4.7.7</pact.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- Spring Cloud Contract 5.0.3 ships REST Assured 5.5.7, which breaks on the Groovy 5.1.x that
Spring Boot 4.2 manages (NullPointerException inside Groovy's ClosureMetaClass). REST Assured 7 does not. -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured-bom</artifactId>
<version>${rest-assured.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-dependencies</artifactId>
<version>${scc.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-contract-verifier</artifactId>
<scope>test</scope>
</dependency>
<!-- Pact provider verification: plain JUnit 5 + HTTP, no Spring integration module -->
<dependency>
<groupId>au.com.dius.pact.provider</groupId>
<artifactId>junit5</artifactId>
<version>${pact.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
<version>${scc.version}</version>
<extensions>true</extensions>
<configuration>
<testFramework>JUNIT5</testFramework>
<testMode>EXPLICIT</testMode>
<baseClassForTests>com.ankurm.contracts.orders.ContractVerifierBase</baseClassForTests>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,9 @@
package com.ankurm.contracts.orders;
import java.math.BigDecimal;
import java.util.List;
/** The producer's own domain object. What goes on the wire is decided by {@link OrderRepresentation}. */
public record Order(long id, String status, BigDecimal total, String currency, List<Line> items) {
public record Line(String sku, int qty) {}
}
@@ -0,0 +1,39 @@
package com.ankurm.contracts.orders;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OrderController {
public record CreateOrder(List<Order.Line> items) {}
private final OrderRepository repository;
private final String variant;
OrderController(OrderRepository repository, @Value("${orders.variant:baseline}") String variant) {
this.repository = repository;
this.variant = variant;
}
@GetMapping("/orders/{id}")
ResponseEntity<Map<String, Object>> get(@PathVariable long id) {
return repository.find(id)
.map(o -> ResponseEntity.ok(OrderRepresentation.of(o, variant)))
.orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "ORDER_NOT_FOUND")));
}
@PostMapping("/orders")
ResponseEntity<Map<String, Object>> create(@RequestBody CreateOrder request) {
Order order = repository.create(request.items());
return ResponseEntity.status(HttpStatus.CREATED).body(OrderRepresentation.of(order, variant));
}
}
@@ -0,0 +1,43 @@
package com.ankurm.contracts.orders;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Repository;
@Repository
public class OrderRepository {
public static final long FIRST_NEW_ID = 1001;
private static final Map<String, BigDecimal> PRICES = Map.of("BOOK-1", new BigDecimal("64.95"), "PEN-7", new BigDecimal("5.00"));
private final Map<Long, Order> orders = new ConcurrentHashMap<>();
private final AtomicLong sequence = new AtomicLong(FIRST_NEW_ID);
public Optional<Order> find(long id) {
return Optional.ofNullable(orders.get(id));
}
public Order create(List<Order.Line> lines) {
BigDecimal total = lines.stream()
.map(l -> PRICES.getOrDefault(l.sku(), BigDecimal.ZERO).multiply(BigDecimal.valueOf(l.qty())))
.reduce(BigDecimal.ZERO, BigDecimal::add);
Order order = new Order(sequence.getAndIncrement(), "NEW", total, "INR", lines);
orders.put(order.id(), order);
return order;
}
public void save(Order order) {
orders.put(order.id(), order);
}
/** Test support: back to a known state so every contract starts from the same data. */
public void reset() {
orders.clear();
sequence.set(FIRST_NEW_ID);
save(new Order(42, "CONFIRMED", new BigDecimal("129.90"), "INR", List.of(new Order.Line("BOOK-1", 2))));
}
}
@@ -0,0 +1,40 @@
package com.ankurm.contracts.orders;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Builds the JSON the API returns. The {@code orders.variant} property exists only so this lab can
* simulate a producer change on demand; a real service would just have the change in its code.
*
* <ul>
* <li>{@code baseline} - id, status, total, currency, items</li>
* <li>{@code add-field} - baseline plus a new field "discount" (additive, backwards compatible)</li>
* <li>{@code rename-total} - "total" renamed to "totalAmount" (breaking for everyone who reads total)</li>
* <li>{@code drop-items} - "items" removed (breaking only for someone who reads items)</li>
* <li>{@code total-string} - "total" serialised as a string "129.90" instead of a number</li>
* </ul>
*/
public final class OrderRepresentation {
private OrderRepresentation() {}
public static Map<String, Object> of(Order o, String variant) {
Map<String, Object> json = new LinkedHashMap<>();
json.put("id", o.id());
json.put("status", o.status());
switch (variant) {
case "rename-total" -> json.put("totalAmount", o.total());
case "total-string" -> json.put("total", o.total().toPlainString());
default -> json.put("total", o.total());
}
json.put("currency", o.currency());
if (!variant.equals("drop-items")) {
json.put("items", o.items());
}
if (variant.equals("add-field")) {
json.put("discount", 0);
}
return json;
}
}
@@ -0,0 +1,11 @@
package com.ankurm.contracts.orders;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OrdersApplication {
public static void main(String[] args) {
SpringApplication.run(OrdersApplication.class, args);
}
}
@@ -0,0 +1 @@
spring.application.name=orders-producer
@@ -0,0 +1,29 @@
package com.ankurm.contracts.orders;
import io.restassured.RestAssured;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
/**
* Base class for the tests that Spring Cloud Contract generates from src/test/resources/contracts.
* Each generated test extends this class, so it is where the producer puts itself into the state
* the contract describes (order 42 exists, the next new id is 1001).
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class ContractVerifierBase {
@LocalServerPort
int port;
@Autowired
OrderRepository repository;
@BeforeEach
void setUp() {
RestAssured.baseURI = "http://localhost";
RestAssured.port = port;
repository.reset();
}
}
@@ -0,0 +1,60 @@
package com.ankurm.contracts.orders;
import au.com.dius.pact.provider.junit5.HttpTestTarget;
import au.com.dius.pact.provider.junit5.PactVerificationContext;
import au.com.dius.pact.provider.junit5.PactVerificationInvocationContextProvider;
import au.com.dius.pact.provider.junitsupport.Provider;
import au.com.dius.pact.provider.junitsupport.State;
import au.com.dius.pact.provider.junitsupport.loader.PactFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import java.math.BigDecimal;
import java.util.List;
/**
* Pact provider verification: replays every interaction recorded in the consumer's pact file
* against this running service and compares the real response with what the consumer said it needs.
* The pact file is the consumer's artefact; the producer team never writes it.
*/
@Provider("orders-producer")
@PactFolder("pacts")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(PactVerificationInvocationContextProvider.class)
class OrdersPactVerificationTest {
@LocalServerPort
int port;
@Autowired
OrderRepository repository;
@BeforeEach
void before(PactVerificationContext context) {
context.setTarget(new HttpTestTarget("localhost", port));
}
@TestTemplate
void verifyPact(PactVerificationContext context) {
context.verifyInteraction();
}
@State("order 42 exists and is confirmed")
void order42Exists() {
repository.reset();
}
@State("order 999 does not exist")
void order999Missing() {
repository.reset();
}
@State("orders can be created")
void canCreate() {
repository.reset();
}
}
@@ -0,0 +1,23 @@
description: posting order lines creates a NEW order with a computed total
name: shouldCreateOrder
request:
method: POST
url: /orders
headers:
Content-Type: application/json
body:
items:
- sku: "BOOK-1"
qty: 2
response:
status: 201
headers:
Content-Type: application/json
body:
id: 1001
status: "NEW"
total: 129.90
currency: "INR"
items:
- sku: "BOOK-1"
qty: 2
@@ -0,0 +1,11 @@
description: an unknown order id gives 404 with an error code
name: shouldReturn404ForUnknownOrder
request:
method: GET
url: /orders/999
response:
status: 404
headers:
Content-Type: application/json
body:
error: "ORDER_NOT_FOUND"
@@ -0,0 +1,17 @@
description: a confirmed order is returned by id
name: shouldReturnOrder
request:
method: GET
url: /orders/42
response:
status: 200
headers:
Content-Type: application/json
body:
id: 42
status: "CONFIRMED"
total: 129.90
currency: "INR"
items:
- sku: "BOOK-1"
qty: 2
@@ -0,0 +1,166 @@
{
"consumer": {
"name": "checkout-consumer"
},
"interactions": [
{
"description": "a request for order 42",
"providerStates": [
{
"name": "order 42 exists and is confirmed"
}
],
"request": {
"method": "GET",
"path": "/orders/42"
},
"response": {
"body": {
"id": 42,
"status": "CONFIRMED",
"total": 129.9
},
"headers": {
"Content-Type": "application/json"
},
"matchingRules": {
"body": {
"$.id": {
"combine": "AND",
"matchers": [
{
"match": "integer"
}
]
},
"$.status": {
"combine": "AND",
"matchers": [
{
"match": "type"
}
]
},
"$.total": {
"combine": "AND",
"matchers": [
{
"match": "decimal"
}
]
}
}
},
"status": 200
}
},
{
"description": "a request for an unknown order",
"providerStates": [
{
"name": "order 999 does not exist"
}
],
"request": {
"method": "GET",
"path": "/orders/999"
},
"response": {
"status": 404
}
},
{
"description": "a request to create an order",
"providerStates": [
{
"name": "orders can be created"
}
],
"request": {
"body": {
"items": [
{
"qty": 2,
"sku": "BOOK-1"
}
]
},
"headers": {
"Content-Type": "application/json"
},
"matchingRules": {
"body": {
"$.items[0].qty": {
"combine": "AND",
"matchers": [
{
"match": "integer"
}
]
},
"$.items[0].sku": {
"combine": "AND",
"matchers": [
{
"match": "type"
}
]
}
}
},
"method": "POST",
"path": "/orders"
},
"response": {
"body": {
"id": 1001,
"status": "NEW",
"total": 129.9
},
"headers": {
"Content-Type": "application/json"
},
"matchingRules": {
"body": {
"$.id": {
"combine": "AND",
"matchers": [
{
"match": "integer"
}
]
},
"$.status": {
"combine": "AND",
"matchers": [
{
"match": "type"
}
]
},
"$.total": {
"combine": "AND",
"matchers": [
{
"match": "decimal"
}
]
}
}
},
"status": 201
}
}
],
"metadata": {
"pact-jvm": {
"version": "4.7.7"
},
"pactSpecification": {
"version": "3.0.0"
}
},
"provider": {
"name": "orders-producer"
}
}
+25
View File
@@ -0,0 +1,25 @@
# JDK
openjdk version "25.0.5.1" 2026-11-17 LTS
OpenJDK Runtime Environment Temurin-25.0.5.1+2 (build 25.0.5.1+2-LTS)
OpenJDK 64-Bit Server VM Temurin-25.0.5.1+2 (build 25.0.5.1+2-LTS, mixed mode, sharing)
# Maven
Apache Maven 3.9.11 (3e54c93a704957b63ee3494413a2b544fd3d825b)
# producer, resolved test-scope contract libraries
org.springframework.cloud:spring-cloud-starter-contract-verifier:jar:5.0.3:test
org.springframework.cloud:spring-cloud-contract-verifier:jar:5.0.3:test
org.springframework.cloud:spring-cloud-contract-spec-groovy:jar:5.0.3:test
org.wiremock:wiremock-standalone:jar:3.13.2:test
org.apache.groovy:groovy:jar:5.1.3:test
io.rest-assured:rest-assured:jar:7.0.0:test
au.com.dius.pact.provider:junit5:jar:4.7.7:test
au.com.dius.pact:provider:jar:4.7.7:test
# consumer, resolved test-scope libraries
org.springframework.boot:spring-boot-starter-restclient:jar:4.2.0:compile
org.springframework.cloud:spring-cloud-starter-contract-stub-runner:jar:5.0.3:test
org.springframework.cloud:spring-cloud-contract-stub-runner:jar:5.0.3:test
org.springframework.cloud:spring-cloud-contract-wiremock:jar:5.0.3:test
org.wiremock:wiremock-standalone:jar:3.13.2:test
au.com.dius.pact.consumer:junit5:jar:4.7.7:test
@@ -0,0 +1,4 @@
[INFO] Running com.ankurm.contracts.checkout.OrdersPactConsumerTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.checkout.OrdersPactConsumerTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
+166
View File
@@ -0,0 +1,166 @@
{
"consumer": {
"name": "checkout-consumer"
},
"interactions": [
{
"description": "a request for order 42",
"providerStates": [
{
"name": "order 42 exists and is confirmed"
}
],
"request": {
"method": "GET",
"path": "/orders/42"
},
"response": {
"body": {
"id": 42,
"status": "CONFIRMED",
"total": 129.9
},
"headers": {
"Content-Type": "application/json"
},
"matchingRules": {
"body": {
"$.id": {
"combine": "AND",
"matchers": [
{
"match": "integer"
}
]
},
"$.status": {
"combine": "AND",
"matchers": [
{
"match": "type"
}
]
},
"$.total": {
"combine": "AND",
"matchers": [
{
"match": "decimal"
}
]
}
}
},
"status": 200
}
},
{
"description": "a request for an unknown order",
"providerStates": [
{
"name": "order 999 does not exist"
}
],
"request": {
"method": "GET",
"path": "/orders/999"
},
"response": {
"status": 404
}
},
{
"description": "a request to create an order",
"providerStates": [
{
"name": "orders can be created"
}
],
"request": {
"body": {
"items": [
{
"qty": 2,
"sku": "BOOK-1"
}
]
},
"headers": {
"Content-Type": "application/json"
},
"matchingRules": {
"body": {
"$.items[0].qty": {
"combine": "AND",
"matchers": [
{
"match": "integer"
}
]
},
"$.items[0].sku": {
"combine": "AND",
"matchers": [
{
"match": "type"
}
]
}
}
},
"method": "POST",
"path": "/orders"
},
"response": {
"body": {
"id": 1001,
"status": "NEW",
"total": 129.9
},
"headers": {
"Content-Type": "application/json"
},
"matchingRules": {
"body": {
"$.id": {
"combine": "AND",
"matchers": [
{
"match": "integer"
}
]
},
"$.status": {
"combine": "AND",
"matchers": [
{
"match": "type"
}
]
},
"$.total": {
"combine": "AND",
"matchers": [
{
"match": "decimal"
}
]
}
}
},
"status": 201
}
}
],
"metadata": {
"pact-jvm": {
"version": "4.7.7"
},
"pactSpecification": {
"version": "3.0.0"
}
},
"provider": {
"name": "orders-producer"
}
}
+31
View File
@@ -0,0 +1,31 @@
[INFO] Running com.ankurm.contracts.orders.OrdersTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.orders.OrdersTest
[INFO] Running com.ankurm.contracts.orders.OrdersPactVerificationTest
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
Given order 42 exists and is confirmed
a request for order 42
returns a response which
has status code 200 (OK)
has a matching body (OK)
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
Given order 999 does not exist
a request for an unknown order
returns a response which
has status code 404 (OK)
has a matching body (OK)
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
Given orders can be created
a request to create an order
returns a response which
has status code 201 (OK)
has a matching body (OK)
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.orders.OrdersPactVerificationTest
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
+93
View File
@@ -0,0 +1,93 @@
package com.ankurm.contracts.orders;
import com.ankurm.contracts.orders.ContractVerifierBase;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.restassured.specification.RequestSpecification;
import io.restassured.response.Response;
import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
import static io.restassured.RestAssured.*;
@SuppressWarnings("rawtypes")
public class OrdersTest extends ContractVerifierBase {
@Test
public void validate_shouldCreateOrder() throws Exception {
// given:
RequestSpecification request = given()
.header("Content-Type", "application/json")
.body("{\"items\":[{\"sku\":\"BOOK-1\",\"qty\":2}]}");
// when:
Response response = given().spec(request)
.post("/orders");
// then:
assertThat(response.statusCode()).isEqualTo(201);
assertThat(response.header("Content-Type")).isEqualTo("application/json");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['id']").isEqualTo(1001);
assertThatJson(parsedJson).field("['status']").isEqualTo("NEW");
assertThatJson(parsedJson).field("['total']").isEqualTo(129.9);
assertThatJson(parsedJson).field("['currency']").isEqualTo("INR");
assertThatJson(parsedJson).array("['items']").contains("['sku']").isEqualTo("BOOK-1");
assertThatJson(parsedJson).array("['items']").contains("['qty']").isEqualTo(2);
}
@Test
public void validate_shouldReturn404ForUnknownOrder() throws Exception {
// given:
RequestSpecification request = given();
// when:
Response response = given().spec(request)
.get("/orders/999");
// then:
assertThat(response.statusCode()).isEqualTo(404);
assertThat(response.header("Content-Type")).isEqualTo("application/json");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['error']").isEqualTo("ORDER_NOT_FOUND");
}
@Test
public void validate_shouldReturnOrder() throws Exception {
// given:
RequestSpecification request = given();
// when:
Response response = given().spec(request)
.get("/orders/42");
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).isEqualTo("application/json");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['id']").isEqualTo(42);
assertThatJson(parsedJson).field("['status']").isEqualTo("CONFIRMED");
assertThatJson(parsedJson).field("['total']").isEqualTo(129.9);
assertThatJson(parsedJson).field("['currency']").isEqualTo("INR");
assertThatJson(parsedJson).array("['items']").contains("['sku']").isEqualTo("BOOK-1");
assertThatJson(parsedJson).array("['items']").contains("['qty']").isEqualTo(2);
}
}
+20
View File
@@ -0,0 +1,20 @@
Archive: /root/.m2/repository/com/ankurm/contracts/orders-producer/1.0.0/orders-producer-1.0.0-stubs.jar
Length Date Time Name
--------- ---------- ----- ----
0 META-INF/
112 META-INF/MANIFEST.MF
0 META-INF/com.ankurm.contracts/
0 META-INF/com.ankurm.contracts/orders-producer/
0 META-INF/com.ankurm.contracts/orders-producer/1.0.0/
0 META-INF/com.ankurm.contracts/orders-producer/1.0.0/mappings/
0 META-INF/com.ankurm.contracts/orders-producer/1.0.0/mappings/orders/
0 META-INF/com.ankurm.contracts/orders-producer/1.0.0/contracts/
0 META-INF/com.ankurm.contracts/orders-producer/1.0.0/contracts/orders/
487 META-INF/com.ankurm.contracts/orders-producer/1.0.0/mappings/orders/shouldReturnOrder.json
752 META-INF/com.ankurm.contracts/orders-producer/1.0.0/mappings/orders/shouldCreateOrder.json
403 META-INF/com.ankurm.contracts/orders-producer/1.0.0/mappings/orders/shouldReturn404ForUnknownOrder.json
313 META-INF/com.ankurm.contracts/orders-producer/1.0.0/contracts/orders/shouldReturnOrder.yml
248 META-INF/com.ankurm.contracts/orders-producer/1.0.0/contracts/orders/shouldReturn404ForUnknownOrder.yml
435 META-INF/com.ankurm.contracts/orders-producer/1.0.0/contracts/orders/shouldCreateOrder.yml
--------- -------
2750 15 files
+16
View File
@@ -0,0 +1,16 @@
{
"id" : "e82107a2-c24d-4c1b-83e5-76e63809afb2",
"request" : {
"urlPath" : "/orders/42",
"method" : "GET"
},
"response" : {
"status" : 200,
"body" : "{\"id\":42,\"status\":\"CONFIRMED\",\"total\":129.9,\"currency\":\"INR\",\"items\":[{\"sku\":\"BOOK-1\",\"qty\":2}]}",
"headers" : {
"Content-Type" : "application/json"
},
"transformers" : [ "response-template", "spring-cloud-contract" ]
},
"uuid" : "e82107a2-c24d-4c1b-83e5-76e63809afb2"
}
@@ -0,0 +1,5 @@
[INFO] Running com.ankurm.contracts.checkout.OrdersStubConsumerTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.checkout.OrdersStubConsumerTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
+31
View File
@@ -0,0 +1,31 @@
[INFO] Running com.ankurm.contracts.orders.OrdersTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.orders.OrdersTest
[INFO] Running com.ankurm.contracts.orders.OrdersPactVerificationTest
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
Given order 42 exists and is confirmed
a request for order 42
returns a response which
has status code 200 (OK)
has a matching body (OK)
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
Given order 999 does not exist
a request for an unknown order
returns a response which
has status code 404 (OK)
has a matching body (OK)
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
Given orders can be created
a request to create an order
returns a response which
has status code 201 (OK)
has a matching body (OK)
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.orders.OrdersPactVerificationTest
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
@@ -0,0 +1,128 @@
[INFO] Running com.ankurm.contracts.orders.OrdersTest
[ERROR] Tests run: 3, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: N s <<< FAILURE! -- in com.ankurm.contracts.orders.OrdersTest
[ERROR] com.ankurm.contracts.orders.OrdersTest.validate_shouldReturnOrder -- Time elapsed: N s <<< ERROR!
java.lang.IllegalStateException: Parsed JSON [{"id":42,"status":"CONFIRMED","totalAmount":129.9,"currency":"INR","items":[{"sku":"BOOK-1","qty":2}]}] doesn't match the JSON path [$[?(@.['total'] == 129.9)]]
[ERROR] com.ankurm.contracts.orders.OrdersTest.validate_shouldCreateOrder -- Time elapsed: N s <<< ERROR!
java.lang.IllegalStateException: Parsed JSON [{"id":1001,"status":"NEW","totalAmount":129.9,"currency":"INR","items":[{"sku":"BOOK-1","qty":2}]}] doesn't match the JSON path [$[?(@.['total'] == 129.9)]]
[INFO] Running com.ankurm.contracts.orders.OrdersPactVerificationTest
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
Given order 42 exists and is confirmed
a request for order 42
returns a response which
has status code 200 (OK)
has a matching body (FAILED)
Failures:
1) Verifying a pact between checkout-consumer and orders-producer - a request for order 42 has a matching body
1.1) body: $ Actual map is missing the following keys: total
{
"id": 42,
"status": "CONFIRMED",
- "total": 129.9
+ "totalAmount": 129.90
}
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
Given order 999 does not exist
a request for an unknown order
returns a response which
has status code 404 (OK)
has a matching body (OK)
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
Given orders can be created
a request to create an order
returns a response which
has status code 201 (OK)
has a matching body (FAILED)
Failures:
1) Verifying a pact between checkout-consumer and orders-producer - a request to create an order has a matching body
1.1) body: $ Actual map is missing the following keys: total
{
"id": 1001,
"status": "NEW",
- "total": 129.9
+ "totalAmount": 129.90
}
[ERROR] Tests run: 3, Failures: 2, Errors: 0, Skipped: 0, Time elapsed: N s <<< FAILURE! -- in com.ankurm.contracts.orders.OrdersPactVerificationTest
[ERROR] com.ankurm.contracts.orders.OrdersPactVerificationTest.verifyPact(PactVerificationContext)[1] -- Time elapsed: N s <<< FAILURE!
java.lang.AssertionError:
checkout-consumer - Upon a request for order 42
Failures:
1) Verifying a pact between checkout-consumer and orders-producer - a request for order 42 has a matching body
1.1) body: $ Actual map is missing the following keys: total
{
"id": 42,
"status": "CONFIRMED",
- "total": 129.9
+ "totalAmount": 129.90
}
[ERROR] com.ankurm.contracts.orders.OrdersPactVerificationTest.verifyPact(PactVerificationContext)[3] -- Time elapsed: N s <<< FAILURE!
java.lang.AssertionError:
checkout-consumer - Upon a request to create an order
Failures:
1) Verifying a pact between checkout-consumer and orders-producer - a request to create an order has a matching body
1.1) body: $ Actual map is missing the following keys: total
{
"id": 1001,
"status": "NEW",
- "total": 129.9
+ "totalAmount": 129.90
}
[ERROR] Failures:
[ERROR] OrdersPactVerificationTest.verifyPact:43 checkout-consumer - Upon a request for order 42
Failures:
1) Verifying a pact between checkout-consumer and orders-producer - a request for order 42 has a matching body
1.1) body: $ Actual map is missing the following keys: total
{
"id": 42,
"status": "CONFIRMED",
- "total": 129.9
+ "totalAmount": 129.90
}
[ERROR] OrdersPactVerificationTest.verifyPact:43 checkout-consumer - Upon a request to create an order
Failures:
1) Verifying a pact between checkout-consumer and orders-producer - a request to create an order has a matching body
1.1) body: $ Actual map is missing the following keys: total
{
"id": 1001,
"status": "NEW",
- "total": 129.9
+ "totalAmount": 129.90
}
[ERROR] Errors:
[ERROR] OrdersTest.validate_shouldCreateOrder:40 ? IllegalState Parsed JSON [{"id":1001,"status":"NEW","totalAmount":129.9,"currency":"INR","items":[{"sku":"BOOK-1","qty":2}]}] doesn't match the JSON path [$[?(@.['total'] == 129.9)]]
[ERROR] OrdersTest.validate_shouldReturnOrder:87 ? IllegalState Parsed JSON [{"id":42,"status":"CONFIRMED","totalAmount":129.9,"currency":"INR","items":[{"sku":"BOOK-1","qty":2}]}] doesn't match the JSON path [$[?(@.['total'] == 129.9)]]
[ERROR] Tests run: 6, Failures: 2, Errors: 2, Skipped: 0
[INFO] BUILD FAILURE
@@ -0,0 +1,46 @@
[INFO] Running com.ankurm.contracts.orders.OrdersTest
com.jayway.jsonpath.PathNotFoundException: Missing property in path $['items']
com.jayway.jsonpath.PathNotFoundException: Missing property in path $['items']
[ERROR] Tests run: 3, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: N s <<< FAILURE! -- in com.ankurm.contracts.orders.OrdersTest
[ERROR] com.ankurm.contracts.orders.OrdersTest.validate_shouldReturnOrder -- Time elapsed: N s <<< ERROR!
java.lang.RuntimeException: com.jayway.jsonpath.PathNotFoundException: Missing property in path $['items']
Caused by: com.jayway.jsonpath.PathNotFoundException: Missing property in path $['items']
[ERROR] com.ankurm.contracts.orders.OrdersTest.validate_shouldCreateOrder -- Time elapsed: N s <<< ERROR!
java.lang.RuntimeException: com.jayway.jsonpath.PathNotFoundException: Missing property in path $['items']
Caused by: com.jayway.jsonpath.PathNotFoundException: Missing property in path $['items']
[INFO] Running com.ankurm.contracts.orders.OrdersPactVerificationTest
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
Given order 42 exists and is confirmed
a request for order 42
returns a response which
has status code 200 (OK)
has a matching body (OK)
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
Given order 999 does not exist
a request for an unknown order
returns a response which
has status code 404 (OK)
has a matching body (OK)
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
Given orders can be created
a request to create an order
returns a response which
has status code 201 (OK)
has a matching body (OK)
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.orders.OrdersPactVerificationTest
[ERROR] Errors:
[ERROR] OrdersTest.validate_shouldCreateOrder:42 ? Runtime com.jayway.jsonpath.PathNotFoundException: Missing property in path $['items']
[ERROR] OrdersTest.validate_shouldReturnOrder:89 ? Runtime com.jayway.jsonpath.PathNotFoundException: Missing property in path $['items']
[ERROR] Tests run: 6, Failures: 0, Errors: 2, Skipped: 0
[INFO] BUILD FAILURE
@@ -0,0 +1,86 @@
[INFO] Running com.ankurm.contracts.orders.OrdersTest
[ERROR] Tests run: 3, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: N s <<< FAILURE! -- in com.ankurm.contracts.orders.OrdersTest
[ERROR] com.ankurm.contracts.orders.OrdersTest.validate_shouldReturnOrder -- Time elapsed: N s <<< ERROR!
java.lang.IllegalStateException: Parsed JSON [{"id":42,"status":"CONFIRMED","total":"129.90","currency":"INR","items":[{"sku":"BOOK-1","qty":2}]}] doesn't match the JSON path [$[?(@.['total'] == 129.9)]]
[ERROR] com.ankurm.contracts.orders.OrdersTest.validate_shouldCreateOrder -- Time elapsed: N s <<< ERROR!
java.lang.IllegalStateException: Parsed JSON [{"id":1001,"status":"NEW","total":"129.90","currency":"INR","items":[{"sku":"BOOK-1","qty":2}]}] doesn't match the JSON path [$[?(@.['total'] == 129.9)]]
[INFO] Running com.ankurm.contracts.orders.OrdersPactVerificationTest
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
Given order 42 exists and is confirmed
a request for order 42
returns a response which
has status code 200 (OK)
has a matching body (FAILED)
Failures:
1) Verifying a pact between checkout-consumer and orders-producer - a request for order 42 has a matching body
1.1) body: $.total Expected '129.90' (String) to be a decimal number
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
Given order 999 does not exist
a request for an unknown order
returns a response which
has status code 404 (OK)
has a matching body (OK)
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target/test-classes/pacts/checkout-consumer-orders-producer.json]
Given orders can be created
a request to create an order
returns a response which
has status code 201 (OK)
has a matching body (FAILED)
Failures:
1) Verifying a pact between checkout-consumer and orders-producer - a request to create an order has a matching body
1.1) body: $.total Expected '129.90' (String) to be a decimal number
[ERROR] Tests run: 3, Failures: 2, Errors: 0, Skipped: 0, Time elapsed: N s <<< FAILURE! -- in com.ankurm.contracts.orders.OrdersPactVerificationTest
[ERROR] com.ankurm.contracts.orders.OrdersPactVerificationTest.verifyPact(PactVerificationContext)[1] -- Time elapsed: N s <<< FAILURE!
java.lang.AssertionError:
checkout-consumer - Upon a request for order 42
Failures:
1) Verifying a pact between checkout-consumer and orders-producer - a request for order 42 has a matching body
1.1) body: $.total Expected '129.90' (String) to be a decimal number
[ERROR] com.ankurm.contracts.orders.OrdersPactVerificationTest.verifyPact(PactVerificationContext)[3] -- Time elapsed: N s <<< FAILURE!
java.lang.AssertionError:
checkout-consumer - Upon a request to create an order
Failures:
1) Verifying a pact between checkout-consumer and orders-producer - a request to create an order has a matching body
1.1) body: $.total Expected '129.90' (String) to be a decimal number
[ERROR] Failures:
[ERROR] OrdersPactVerificationTest.verifyPact:43 checkout-consumer - Upon a request for order 42
Failures:
1) Verifying a pact between checkout-consumer and orders-producer - a request for order 42 has a matching body
1.1) body: $.total Expected '129.90' (String) to be a decimal number
[ERROR] OrdersPactVerificationTest.verifyPact:43 checkout-consumer - Upon a request to create an order
Failures:
1) Verifying a pact between checkout-consumer and orders-producer - a request to create an order has a matching body
1.1) body: $.total Expected '129.90' (String) to be a decimal number
[ERROR] Errors:
[ERROR] OrdersTest.validate_shouldCreateOrder:40 ? IllegalState Parsed JSON [{"id":1001,"status":"NEW","total":"129.90","currency":"INR","items":[{"sku":"BOOK-1","qty":2}]}] doesn't match the JSON path [$[?(@.['total'] == 129.9)]]
[ERROR] OrdersTest.validate_shouldReturnOrder:87 ? IllegalState Parsed JSON [{"id":42,"status":"CONFIRMED","total":"129.90","currency":"INR","items":[{"sku":"BOOK-1","qty":2}]}] doesn't match the JSON path [$[?(@.['total'] == 129.9)]]
[ERROR] Tests run: 6, Failures: 2, Errors: 2, Skipped: 0
[INFO] BUILD FAILURE
@@ -0,0 +1,14 @@
[INFO] Running com.ankurm.contracts.orders.OrdersTest
[ERROR] Tests run: 3, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: N s <<< FAILURE! -- in com.ankurm.contracts.orders.OrdersTest
[ERROR] com.ankurm.contracts.orders.OrdersTest.validate_shouldReturnOrder -- Time elapsed: N s <<< ERROR!
java.lang.NullPointerException
[ERROR] com.ankurm.contracts.orders.OrdersTest.validate_shouldReturn404ForUnknownOrder -- Time elapsed: N s <<< ERROR!
java.lang.NullPointerException
[ERROR] Errors:
[ERROR] OrdersTest.validate_shouldReturn404ForUnknownOrder:55 ? NullPointer
[ERROR] OrdersTest.validate_shouldReturnOrder:76 ? NullPointer
[ERROR] Tests run: 3, Failures: 0, Errors: 2, Skipped: 0
[INFO] BUILD FAILURE
@@ -0,0 +1,5 @@
[INFO] Running com.ankurm.contracts.orders.OrdersTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.orders.OrdersTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
@@ -0,0 +1,13 @@
[INFO] Running com.ankurm.contracts.checkout.OrdersStubConsumerTest
[ERROR] Tests run: 3, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: N s <<< FAILURE! -- in com.ankurm.contracts.checkout.OrdersStubConsumerTest
[ERROR] com.ankurm.contracts.checkout.OrdersStubConsumerTest.amountDueComesFromTheStubbedOrder -- Time elapsed: N s <<< FAILURE!
java.lang.AssertionError:
Expecting actual not to be null
[ERROR] Failures:
[ERROR] OrdersStubConsumerTest.amountDueComesFromTheStubbedOrder:33
Expecting actual not to be null
[ERROR] Tests run: 3, Failures: 1, Errors: 0, Skipped: 0
[INFO] BUILD FAILURE
+32
View File
@@ -0,0 +1,32 @@
[INFO] Using the model-based test generator [stubborn.contract.verifier.model-based-generator != false]
[INFO] Running com.ankurm.contracts.orders.OrdersTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.orders.OrdersTest
[INFO] Running com.ankurm.contracts.orders.OrdersPactVerificationTest
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target-stubborn/test-classes/pacts/checkout-consumer-orders-producer.json]
Given order 42 exists and is confirmed
a request for order 42
returns a response which
has status code 200 (OK)
has a matching body (OK)
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target-stubborn/test-classes/pacts/checkout-consumer-orders-producer.json]
Given order 999 does not exist
a request for an unknown order
returns a response which
has status code 404 (OK)
has a matching body (OK)
Verifying a pact between checkout-consumer and orders-producer
[Using File <repo>/contracts/orders-producer/target-stubborn/test-classes/pacts/checkout-consumer-orders-producer.json]
Given orders can be created
a request to create an order
returns a response which
has status code 201 (OK)
has a matching body (OK)
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.orders.OrdersPactVerificationTest
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
@@ -0,0 +1,5 @@
[INFO] Running com.ankurm.contracts.checkout.OrdersStubbornConsumerTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: N s -- in com.ankurm.contracts.checkout.OrdersStubbornConsumerTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""Reduce a Maven run to the lines that carry evidence: test results, assertion messages, pact verification
output. Removes launcher noise, Spring Boot banners and startup logs, WireMock request dumps and stack frames.
Usage: clean.py ROOT < raw > clean"""
import re, sys
root = sys.argv[1]
drop = re.compile(r"""^(
Picked\ up|WARNING:|OpenJDK\ 64-Bit|Mockito\ is\ currently|\[INFO\]\ (---|Scanning|Replacing|The\ original|Building|\ \ from|Deleting|Recompiling|Compiling|
skip|Will\ use|Directory\ with|Test\ Source|Using\ \[|Creating\ new|Generated|Converting|\ \ \ \ \ Spring|Stub\ Server|Files\ matching|
Total\ time|Finished|Results|Using\ auto|\ T\ E\ S\ T\ S|-----|Generating|Installing|Building\ jar|Copying|Nothing|Download)|
\d{4}-\d\d-\d\dT|\d\d:\d\d:\d\d\.\d+\ \[main\]|\s+at\ |\s+\.\.\.\ \d+\ more|
\s*\.\ \ \ ____|\s*/\\\\|\s*\(\ \(|\s*\\\\/|\s*'\ \ \||\s*=====|\ ::\ Spring\ Boot|
\s*Please\ note:|\s*and\ operating|\s*variable\ to|\[ERROR\]\s*$|\[INFO\]\s*$|\[ERROR\]\ (For\ more|Re-run|To\ see|Failed\ to\ execute|->\ \[Help|\[Help|See\ |Please\ read)|
Nov\ \d+,|org\.junit\.jupiter\.engine|OpenJDK|Found\ multiple|You\ may\ wish|\s+(jar:file|Content-Type|Host:|Content-Length|Connection|User-Agent)
)""", re.X)
out, skip_block = [], False
for line in sys.stdin:
line = line.rstrip("\n")
line = line.replace(root, "<repo>/contracts").replace("/root/.m2", "~/.m2")
line = re.sub(r"Time elapsed: [0-9.]+ s", "Time elapsed: N s", line)
# WireMock request/response dumps print between "127.0.0.1 - <verb>" / "Request received:" and the next test line
if re.match(r"^(127\.0\.0\.1 - |Request received:|Matched response definition:|Response:|-{10,}$)", line):
skip_block = True
if line.startswith("[INFO] Running") or line.startswith("[INFO] Tests run") or line.startswith("[ERROR] Tests run") or line.startswith("[INFO] BUILD") or line.startswith("[ERROR] Failures") or line.startswith("[ERROR] Errors"):
skip_block = False
if skip_block or drop.match(line):
continue
out.append(line)
text = "\n".join(out)
text = re.sub(r"\n{3,}", "\n\n", text).strip("\n")
print(text)
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env bash
# Regenerates every file in contracts/output/. Needs JDK 25, Maven, internet for the first build.
# Order matters: the pact is written by the consumer, then verified by the producer; the stubs are
# published by the producer, then used by the consumer.
set -uo pipefail
cd "$(dirname "$0")/.."
ROOT=$(pwd)
OUT=$ROOT/output
export pact_do_not_track=true
# keep only evidence: see scripts/clean.py
clean() { python3 -I scripts/clean.py "$ROOT"; }
mkdir -p "$OUT"
# FROM=n resumes at stage n without deleting earlier output (handy when something else on the machine kills a JVM)
[ -z "${FROM:-}" ] && rm -f "$OUT"/*.txt "$OUT"/*.json
stage() { [ "$1" -ge "${FROM:-1}" ]; }
run() { # run <dir> <outfile> <env...> -- <mvn args>
local dir=$1 file=$2; shift 2
local envs=(); while [ "$1" != "--" ]; do envs+=("$1"); shift; done; shift
( cd "$ROOT/$dir" && env "${envs[@]}" mvn -B "$@" 2>&1 ) | clean > "$OUT/$file"
}
{
echo "# JDK"; java -version 2>&1 | grep -v 'Picked up'
echo; echo "# Maven"; mvn -v 2>&1 | grep -v 'Picked up' | head -1
echo; echo "# producer, resolved test-scope contract libraries"
( cd orders-producer && mvn -B dependency:tree -Dscope=test 2>&1 ) | grep -E "spring-cloud-starter-contract-verifier|spring-cloud-contract-verifier:|wiremock-standalone|rest-assured:jar|groovy:jar|pact.provider:junit5|au.com.dius.pact:provider|spring-boot-starter-parent" | sed -E 's/^\[INFO\] [|+\\ -]*//'
echo; echo "# consumer, resolved test-scope libraries"
( cd checkout-consumer && mvn -B dependency:tree -Dscope=test 2>&1 ) | grep -E "stub-runner:jar|wiremock|pact.consumer:junit5|spring-boot-starter-restclient:" | sed -E 's/^\[INFO\] [|+\\ -]*//'
} > "$OUT/01-versions.txt"
stage 1 && {
# 1. consumer writes the pact (also proves OrderClient works against a mock shaped like the contract)
run checkout-consumer 02-consumer-pact-run.txt -- clean test -Dtest=OrdersPactConsumerTest
cp checkout-consumer/target/pacts/checkout-consumer-orders-producer.json "$OUT/03-pact-file.json"
mkdir -p orders-producer/src/test/resources/pacts
cp checkout-consumer/target/pacts/checkout-consumer-orders-producer.json orders-producer/src/test/resources/pacts/
# 2. producer: generate tests from contracts, verify the pact, publish stubs
run orders-producer 04-producer-baseline.txt -- clean install
cp orders-producer/target/generated-test-sources/contracts/com/ankurm/contracts/orders/OrdersTest.java "$OUT/05-generated-test.txt"
unzip -l ~/.m2/repository/com/ankurm/contracts/orders-producer/1.0.0/orders-producer-1.0.0-stubs.jar | sed -E 's/ +[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9:]+ +/ /' > "$OUT/06-stubs-jar.txt"
unzip -p ~/.m2/repository/com/ankurm/contracts/orders-producer/1.0.0/orders-producer-1.0.0-stubs.jar 'META-INF/com.ankurm.contracts/orders-producer/1.0.0/mappings/orders/shouldReturnOrder.json' > "$OUT/07-wiremock-mapping.json"
}
stage 3 && {
# 3. consumer runs against the published stubs
run checkout-consumer 08-consumer-stub-run.txt -- clean test -Dtest=OrdersStubConsumerTest
}
stage 4 && {
# 4. producer changes, one at a time. Same environment variable drives both tools.
i=10
for v in add-field rename-total drop-items total-string; do
run orders-producer "$i-variant-$v.txt" "ORDERS_VARIANT=$v" -- clean test; i=$((i+1))
done
}
stage 5 && {
# 5. REST Assured 5.5.7 (what Spring Cloud Contract 5.0.3 ships) against Groovy 5.1.3 (what Boot 4.2 manages)
run orders-producer 20-restassured-5-groovy-5.txt -- clean test -Dtest=OrdersTest -Drest-assured.version=5.5.7
}
stage 6 && {
# 6. the producer evolves its contract on purpose (rename total) and republishes stubs (SCC tests only: the old pact would rightly block it); the consumer meets the new stubs. Scratch copy keeps the repo sources untouched.
SCR=$(mktemp -d); cp -r orders-producer "$SCR/p"; rm -rf "$SCR/p/target"
sed -i 's/total:/totalAmount:/' "$SCR/p"/src/test/resources/contracts/orders/*.yml
( cd "$SCR/p" && ORDERS_VARIANT=rename-total mvn -B clean install -Dtest=OrdersTest 2>&1 ) | clean > "$OUT/21-evolved-contract-producer.txt"
run checkout-consumer 22-evolved-contract-consumer.txt -- clean test -Dtest=OrdersStubConsumerTest
rm -rf "$SCR"
# put the baseline stubs back
( cd orders-producer && mvn -B -q clean install 2>&1 ) >/dev/null
}
stage 7 && {
# 7. the same contracts under Stubborn Contract 0.2.4
run orders-producer 30-stubborn-producer.txt -- -f pom-stubborn.xml clean install
run checkout-consumer 31-stubborn-consumer.txt -- -f pom-stubborn.xml clean test
}
echo "done: $(ls "$OUT" | wc -l) files in $OUT/"