β‘ Chaos Engineering, Transport Failures & Resilience Hardening
Verifying an application's behavior under pristine network conditions covers only the sunny path. In distributed cloud environments and Kubernetes clusters, microservices routinely encounter transport-level network disruptions: socket drops mid-transmission, hung TCP handshakes, intermittent latency spikes (jitter), malformed packet chunks, and sudden connection resets (RST packets). Attempting to validate client-side timeout configurations, retry policies, or circuit breakers against live APIs is unsafe and untestable. WireMock's Fault Injection and Latency Simulation Engine enables controlled chaos testing directly inside your automation suite. By manipulating com.github.tomakehurst.wiremock.http.Fault and statistical distribution models (such as LogNormal and uniform jitter) in conjunction with REST Assured, test engineers verify that client timeout bounds fail fast, retry loops prevent cascading failures, and downstream outages are isolated gracefully.
WIREMOCK TRANSPORT-LEVEL CHAOS & LATENCY INJECTION ARCHITECTURE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β REST ASSURED CLIENT (Apache HttpClient Socket Transport Layer) β
β Timeout Thresholds: connectTimeout = 2000ms | socketTimeout = 3000ms β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Dispatches HTTP Request over Loopback Socket)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β WIREMOCK EMBEDDED SERVER INTERCEPTOR ENGINE β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββ
βΌ βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β FAULT INJECTION (TCP SOCKET CORRUPTION) β β LATENCY & JITTER SIMULATION β
ββββββββββββββββββββββββββββββββββββββββββββββββ€ ββββββββββββββββββββββββββββββββββββββββββββββββ€
β 1. Fault.EMPTY_RESPONSE β β 1. Fixed Latency Delay: β
β β’ Closes socket with zero HTTP bytes β β β’ withFixedDelay(2500) β
β β’ Triggers NoHttpResponseException β β 2. Statistical LogNormal Distribution: β
β 2. Fault.RANDOM_DATA_THEN_CLOSE β β β’ withLogNormalRandomDelay(median, sigma) β
β β’ Emits garbage binary octets β β β’ Models long-tail 99th percentile lag β
β β’ Triggers MalformedChunkCodingException β β 3. Uniform Jitter Distribution: β
β 3. Fault.PEER_CONNECTION_RESET_BY_PEER β β β’ withUniformRandomDelay(100, 800) β
β β’ Emits TCP RST packet mid-stream β β 4. Chunked Dribble Delay: β
β 4. Fault.MALFORMED_RESPONSE_CHUNK β β β’ withChunkedDribbleDelay(chunks, totalMs)β
β β’ Corrupts Transfer-Encoding chunk frames β β β’ Delivers payload byte-by-byte slowly β
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CLIENT RESILIENCE VERIFICATION: Assert exceptions, fallback circuits & retry interceptors β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Fault.EMPTY_RESPONSE to close the TCP connection immediately without sending any response headers or bytes, verifying that the client catches NoHttpResponseException.
package com.nikita.restassured.wiremock.faults;
import com.github.tomakehurst.wiremock.http.Fault;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import org.apache.http.NoHttpResponseException;
import org.testng.Assert;
import org.testng.annotations.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
public class EmptyResponseFaultTest extends WireMockBaseTest {
@Test(description = "Verify client resilience when WireMock drops TCP connection via EMPTY_RESPONSE")
public void testEmptyResponseSocketDrop() {
// Configure stub to accept connection and immediately sever socket with 0 bytes:
stubFor(get(urlEqualTo("/v1/payments/charge"))
.willReturn(aResponse()
.withFault(Fault.EMPTY_RESPONSE)));
try {
given()
.spec(mockSpec)
.when()
.get("/v1/payments/charge");
Assert.fail("Expected transport failure on dropped socket, but request completed!");
} catch (Exception e) {
System.out.println("[β] Intercepted expected socket exception: " + e.getClass().getName());
System.out.println(" Message: " + e.getMessage());
// Validate root cause is an abrupt termination (NoHttpResponseException or SocketException)
boolean isDroppedSocket = e.getMessage().contains("failed to respond") ||
e.getMessage().contains("Connection reset") ||
e.getCause() instanceof NoHttpResponseException;
Assert.assertTrue(isDroppedSocket, "Exception must indicate an abrupt server disconnect!");
}
}
}
Fault.RANDOM_DATA_THEN_CLOSE to send non-HTTP random garbage octets over the wire, verifying that the client detects malformed protocol bytes and prevents invalid state transitions.
package com.nikita.restassured.wiremock.faults;
import com.github.tomakehurst.wiremock.http.Fault;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import org.apache.http.ProtocolException;
import org.testng.Assert;
import org.testng.annotations.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
public class RandomDataFaultTest extends WireMockBaseTest {
@Test(description = "Verify client rejects malformed non-HTTP random byte stream")
public void testRandomDataGarbageStream() {
// WireMock sends random junk bytes then severs the socket
stubFor(get(urlEqualTo("/v1/students/corrupted-stream"))
.willReturn(aResponse()
.withFault(Fault.RANDOM_DATA_THEN_CLOSE)));
try {
given()
.spec(mockSpec)
.when()
.get("/v1/students/corrupted-stream");
Assert.fail("Expected protocol violation exception on random garbage byte stream!");
} catch (Exception e) {
System.out.println("[β] Protocol parsing exception intercepted: " + e.getClass().getSimpleName());
System.out.println(" Diagnostic Detail: " + e.getMessage());
// Verify the client correctly rejects invalid HTTP stream data
Assert.assertNotNull(e.getMessage());
}
}
}
Fault.MALFORMED_RESPONSE_CHUNK to start streaming a Transfer-Encoding: chunked response and intentionally corrupt chunk boundaries mid-payload, triggering chunk parsing failures.
package com.nikita.restassured.wiremock.faults;
import com.github.tomakehurst.wiremock.http.Fault;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import org.testng.Assert;
import org.testng.annotations.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
public class MalformedChunkFaultTest extends WireMockBaseTest {
@Test(description = "Verify client fails fast when response chunk boundaries are corrupted mid-stream")
public void testMalformedChunkCoding() {
// Emits initial valid chunk header, then sends malformed framing bytes mid-stream
stubFor(get(urlEqualTo("/v1/reports/chunked-export"))
.willReturn(aResponse()
.withFault(Fault.MALFORMED_RESPONSE_CHUNK)));
try {
given()
.spec(mockSpec)
.when()
.get("/v1/reports/chunked-export");
Assert.fail("Expected chunk coding corruption exception, but call succeeded!");
} catch (Exception e) {
System.out.println("[β] Malformed chunk coding intercepted: " + e.getClass().getSimpleName());
System.out.println(" Detail: " + e.getMessage());
boolean isChunkError = e.getMessage().contains("chunk") ||
e.getMessage().contains("Premature end") ||
e.getMessage().contains("Garbage in end of chunk");
Assert.assertTrue(isChunkError, "Exception must reference chunk decoding failures!");
}
}
}
withFixedDelay(3500) in WireMock while setting a strict socketTimeout = 2000ms on REST Assured's HttpClientConfig, asserting a SocketTimeoutException occurs.
package com.nikita.restassured.wiremock.faults;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import io.restassured.config.HttpClientConfig;
import io.restassured.config.RestAssuredConfig;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.net.SocketTimeoutException;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
public class SocketTimeoutValidationTest extends WireMockBaseTest {
@Test(description = "Verify client socket timeout fires when WireMock fixed delay exceeds threshold")
public void testClientSocketTimeoutTriggered() {
// WireMock pauses for 3500ms before returning response
stubFor(get(urlEqualTo("/v1/external/slow-endpoint"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withFixedDelay(3500) // 3.5-second server delay
.withBody("{\"status\": \"LATE_RESPONSE\"}")));
// Configure strict 1500ms socket timeout on client side:
RestAssuredConfig strictTimeoutConfig = RestAssuredConfig.config()
.httpClient(HttpClientConfig.httpClientConfig()
.setParam("http.socket.timeout", 1500) // 1.5s timeout threshold
.setParam("http.connection.timeout", 1500));
long startEpoch = System.currentTimeMillis();
try {
given()
.spec(mockSpec)
.config(strictTimeoutConfig)
.when()
.get("/v1/external/slow-endpoint");
Assert.fail("Expected SocketTimeoutException, but call completed without timing out!");
} catch (Exception e) {
long duration = System.currentTimeMillis() - startEpoch;
System.out.printf("[β] SocketTimeoutException caught after %d ms (Threshold: 1500ms)%n", duration);
System.out.println(" Exception Class: " + e.getClass().getName());
boolean isTimeout = e.getMessage().contains("Read timed out") ||
e.getCause() instanceof SocketTimeoutException;
Assert.assertTrue(isTimeout, "Exception must indicate a read timeout!");
Assert.assertTrue(duration >= 1400 && duration < 3000, "Timeout must fire close to 1500ms limit!");
}
}
}
withLogNormalRandomDelay() and withUniformRandomDelay() in WireMock to simulate variable latency spikes and verify client performance across statistical distributions.
package com.nikita.restassured.wiremock.faults;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import org.testng.annotations.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThan;
public class LatencyDistributionTest extends WireMockBaseTest {
@Test(description = "Simulate realistic long-tail latency spikes using LogNormal distribution")
public void testLogNormalLatencyJitter() {
// LogNormal distribution models real web traffic:
// Median delay: 300ms, Sigma (spread): 0.4.
// Most requests complete ~300ms; occasional 99th percentile calls take 800-1200ms.
stubFor(get(urlEqualTo("/v1/students/search"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withLogNormalRandomDelay(300, 0.4)
.withBody("{\"results\": [\"STU-88219\", \"STU-99412\"]}")));
for (int i = 1; i <= 3; i++) {
long start = System.currentTimeMillis();
given()
.spec(mockSpec)
.when()
.get("/v1/students/search")
.then()
.statusCode(200)
.time(greaterThanOrEqualTo(100L))
.time(lessThan(3000L));
long duration = System.currentTimeMillis() - start;
System.out.printf("[LogNormal Sample %d] Round-trip latency: %d ms%n", i, duration);
}
}
@Test(description = "Simulate uniform random jitter bounded between 200ms and 600ms")
public void testUniformRandomJitter() {
// Uniform distribution: delay is evenly distributed between lower and upper bounds
stubFor(get(urlEqualTo("/v1/courses/catalog"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withUniformRandomDelay(200, 600)
.withBody("{\"catalogStatus\": \"ONLINE\"}")));
long start = System.currentTimeMillis();
given()
.spec(mockSpec)
.when()
.get("/v1/courses/catalog")
.then()
.statusCode(200)
.time(greaterThanOrEqualTo(180L))
.time(lessThan(1000L));
long duration = System.currentTimeMillis() - start;
System.out.printf("[Uniform Jitter] Round-trip latency: %d ms (Expected: 200-600ms)%n", duration);
}
}
withChunkedDribbleDelay(numberOfChunks, totalDuration) in WireMock to deliver response payload bytes in tiny, metered chunks across a defined duration.
package com.nikita.restassured.wiremock.faults;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import org.testng.annotations.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
public class ChunkedDribbleDelayTest extends WireMockBaseTest {
@Test(description = "Verify client handles slowly-trickling chunked responses using ChunkedDribbleDelay")
public void testSlowChunkedDribble() {
// Dribbles the response payload in 5 distinct chunks over 1500ms total duration
stubFor(get(urlEqualTo("/v1/media/slow-payload"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withChunkedDribbleDelay(5, 1500) // 5 chunks over 1.5 seconds
.withBody("{\"streamStatus\": \"FULLY_DELIVERED\", \"totalBytes\": 1024}")));
long start = System.currentTimeMillis();
given()
.spec(mockSpec)
.when()
.get("/v1/media/slow-payload")
.then()
.statusCode(200)
.body("streamStatus", equalTo("FULLY_DELIVERED"))
.time(greaterThanOrEqualTo(1400L)); // Must take at least 1.4s to assemble
long duration = System.currentTimeMillis() - start;
System.out.printf("[β] Dribbled payload assembled successfully in %d ms (Dribble total: 1500ms)%n", duration);
}
}
package com.nikita.restassured.wiremock.faults;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.http.Fault;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
public class CircuitBreakerResilienceTest {
private WireMockServer circuitServer;
private RequestSpecification circuitSpec;
@BeforeClass
public void setup() {
circuitServer = new WireMockServer(WireMockConfiguration.options().dynamicPort());
circuitServer.start();
circuitSpec = new RequestSpecBuilder()
.setBaseUri(circuitServer.baseUrl())
.build();
// SCENARIO: Trip circuit breaker with failures, then recover
// Call 1: Server fails with Fault.EMPTY_RESPONSE -> Transitions to FAILURE_1
circuitServer.stubFor(get(urlEqualTo("/v1/service/payment"))
.inScenario("CircuitBreakerScenario")
.whenScenarioStateIs(Scenario.STARTED)
.willSetStateTo("FAILURE_1")
.willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));
// Call 2: Server fails again with 503 Unavailable -> Transitions to CIRCUIT_OPEN
circuitServer.stubFor(get(urlEqualTo("/v1/service/payment"))
.inScenario("CircuitBreakerScenario")
.whenScenarioStateIs("FAILURE_1")
.willSetStateTo("CIRCUIT_OPEN")
.willReturn(aResponse().withStatus(503).withBody("Service Unavailable")));
// Call 3: Service recovers and returns 200 OK
circuitServer.stubFor(get(urlEqualTo("/v1/service/payment"))
.inScenario("CircuitBreakerScenario")
.whenScenarioStateIs("CIRCUIT_OPEN")
.willReturn(aResponse().withStatus(200).withBody("{\"status\": \"RECOVERED\"}")));
}
@Test(description = "Verify sequential state transitions through failure to recovery")
public void testCircuitBreakerLifecycle() {
// Invocations:
// Attempt 1: Expect socket failure
try {
given().spec(circuitSpec).get("/v1/service/payment");
Assert.fail("Attempt 1 should fail with dropped socket");
} catch (Exception expected) {
System.out.println("[*] Attempt 1 failed (Fault injected) -> Circuit tracking failure count: 1");
}
// Attempt 2: Expect 503 response
int attempt2Status = given().spec(circuitSpec).get("/v1/service/payment").getStatusCode();
Assert.assertEquals(attempt2Status, 503);
System.out.println("[*] Attempt 2 returned HTTP 503 -> Circuit breaker tripped to OPEN");
// Attempt 3: Service recovered, returns 200 OK
int attempt3Status = given().spec(circuitSpec).get("/v1/service/payment").getStatusCode();
Assert.assertEquals(attempt3Status, 200);
System.out.println("[β] Attempt 3 returned HTTP 200 -> Service recovered successfully");
}
@AfterClass(alwaysRun = true)
public void teardown() {
if (circuitServer != null) {
circuitServer.stop();
}
}
}
TestNG @Test(timeOut = ...), and verifying thread release on interrupted sockets.
package com.nikita.restassured.wiremock.faults;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import io.restassured.config.HttpClientConfig;
import io.restassured.config.RestAssuredConfig;
import org.testng.Assert;
import org.testng.annotations.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
public class DelayTriageTest extends WireMockBaseTest {
// ==========================================================================
// PITFALL: UNBOUNDED DELAYS HANGING CI/CD BUILDS
// When testing with withFixedDelay(30000) (30 seconds), if the client does not
// have an explicit socket timeout, the worker thread hangs indefinitely,
// causing CI pipeline jobs to time out after 60 minutes!
//
// DEFENSIVE MEASURE 1: Always set @Test(timeOut = 5000) in TestNG as a safety net!
// DEFENSIVE MEASURE 2: Always configure http.socket.timeout on RestAssuredConfig!
// ==========================================================================
@Test(timeOut = 4000, description = "TestNG safety timeout ensures test aborts if client hangs on delay")
public void testSafeExecutionWithTimeoutGuard() {
// WireMock set to delay for 2000ms
stubFor(get(urlEqualTo("/v1/triage/bounded-delay"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withFixedDelay(2000)
.withBody("{\"triage\": \"BOUNDED_OK\"}")));
RestAssuredConfig safeConfig = RestAssuredConfig.config()
.httpClient(HttpClientConfig.httpClientConfig()
.setParam("http.socket.timeout", 3000)
.setParam("http.connection.timeout", 2000));
long start = System.currentTimeMillis();
given()
.spec(mockSpec)
.config(safeConfig)
.when()
.get("/v1/triage/bounded-delay")
.then()
.statusCode(200);
long duration = System.currentTimeMillis() - start;
System.out.printf("[β] Bounded delay test completed in %d ms (Well within 4000ms TestNG guard)%n", duration);
Assert.assertTrue(duration >= 1900 && duration < 3500);
}
}
WIREMOCK FAULT INJECTION & LATENCY SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β FAULT / DELAY CONSTRUCT β DSL SYNTAX EXAMPLE β CLIENT EXCEPTION β PRIMARY RESILIENCE OBJECTIVE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Empty Response β withFault(Fault.EMPTY_RESP) β NoHttpResponseEx β Simulates socket drop with 0B β
β Random Data & Close β withFault(Fault.RANDOM_DATA) β ProtocolExceptionβ Tests malformed packet guard β
β Malformed Chunk Frame β withFault(Fault.MALFORMED..) β MalformedChunkEx β Tests broken chunked transfersβ
β Reset By Peer β withFault(Fault.PEER_RESET) β SocketException β Simulates TCP RST packet dropsβ
β Fixed Latency Delay β withFixedDelay(2000) β SocketTimeoutEx β Validates client SLA timeouts β
β LogNormal Jitter β withLogNormalRandomDelay(m,s)β N/A (Statistical)β Models realistic long-tail lagβ
β Uniform Jitter β withUniformRandomDelay(min,m)β N/A (Bounded) β Simulates latency variance β
β Chunked Dribble Delay β withChunkedDribbleDelay(c,ms)β Slow stream read β Tests streaming read timeouts β
β Global Delay Setting β WireMock.setGlobalDelay(ms) β All endpoints β Adds baseline lag globally β
β TestNG Timeout Guard β @Test(timeOut = 5000) β TestTimeoutEx β Prevents hung CI test workers β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 FAULT INJECTION & LATENCY BEST PRACTICES: β
β 1. Always set @Test(timeOut = ...) guards: Prevent hanging CI builds during latency testing. β
β 2. Test both connection and socket timeouts: Differentiate between connect lag and read delays. β
β 3. Use LogNormal distributions for realistic lag: Capture 99th-percentile spikes beyond static delays. β
β 4. Verify circuit breaker state transitions: Test OPEN, HALF-OPEN, and CLOSED states with stubs. β
β 5. Validate client fallback logic on Fault.EMPTY_RESPONSE: Confirm graceful degradation on drops. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ