We just got a question from one of our prospects:
"How can I implement conditional error responses in my API mocks? Specifically, I want to:
- Return an error every 100th API call
- Return an error based on system time (e.g., every 10 minutes)
For a specific endpoint like 'hello':
- Return a normal JSON response for most requests
- Return an error response after every 1000 requests
The error responses should work seamlessly with my existing mock responses. What's the best way to implement this kind of controlled failure testing?" -
Software Developer He is a sample of how you can return an error for a single mock whenever the minute is in the 10s (10, 20, 30,...), and every 100 requests randomly return an error as well.
This is for a single mock. You can also do it for all mocks or selected mocks, depending on your requirements, with a different solution, etc., which we are happy to share.
So please share your business requirement or testing scenario you are looking for with support@trafficparrot.com
Paste this in the response body (see screenshot attached):
{{#with (now format='mm') as |currentMinute|}}
{{#with (randomInteger 1 101) as |requestId|}}
{{#if (or
(eq (math currentMinute '%' 10) "0")
(eq (math requestId '%' 100) "0")
)}}{{modifyResponse 'statusCode' 503}}
{
"error": "Service temporarily unavailable",
"details": "Error triggered by time (10 min interval) or simulated request count",
"currentMinute": {{currentMinute}},
"requestId": {{requestId}}
}
{{else}}
{
"normalResponse": "This is your regular JSON response",
"timestamp": "{{now format='yyyy-MM-dd\'T\'HH:mm:ss.SSSXXX'}}",
"requestId": {{requestId}}
}
{{/if}}
{{/with}}
{{/with}}
You can test the randomness by running:
support@support-pcs:~/tmp$ for i in {1..1000}; do echo "Request $i" && curl -v http://localhost:8081/hello >> test_random.log 2>&1 && echo -e "\n---" >> test_random.log; done
support@support-pcs:~/tmp$ grep "Service temporarily unavailable" test_random.log | wc -l
10
support@support-pcs:~/tmp$ grep -B 20 "Service temporarily unavailable" test_random.log | head -n 20
> GET /hello HTTP/1.1
> Host: localhost:8081
> User-Agent: curl/7.81.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 503 Service Unavailable
< Matched-Stub-Id: 8c4695d4-f94e-4ba8-9793-ee5dcbfba6b5
< Matched-Stub-Name: hello-8c4695d4-f94e-4ba8-9793-ee5dcbfba6b5.json
< Content-Length: 201
< Server: Jetty(9.4.56.v20240826)
<
{ [201 bytes data]
100 201 100 201 0 0 54046 0 --:--:-- --:--:-- --:--:-- 67000
* Connection #0 to host localhost left intact
You can test the time error response by running:
support@support-pcs:~/tmp$ while true; do current_time=$(date +"%H:%M:%S"); echo "Time: $current_time" && curl -i http://localhost:8081/hello && echo -e "\n-------------------\n" && sleep 10; done