Mock the SellerMagnet API in C tests by pointing the C quickstart's own SELLERMAGNET_API_BASE environment variable (already documented in client_from_env()) at a real local POSIX socket server: fake_server.c scripts one response per request and sellermagnet.c, decode.c and retry.c run completely unmodified against it over real HTTP on localhost. No credit is spent, no network call leaves the loopback interface, and nothing beyond the quickstart's own libcurl and json-c (plus pthread, already in libc on Linux) is required.
Key Takeaways
- The C quickstart's own
client_from_env()already readsSELLERMAGNET_API_BASE"for pointing the client at a local mock server in tests"; that env var is the seam, no code change needed. - Make the fake fail closed: a request before a test installs a response gets a 500 "no route installed" answer, never a silently plausible empty one.
- A 429 is free and worth retrying; a 500 without Retry-After is refunded and worth one retry; a 502/503 is billed on every attempt, so cap the attempts.
- Swap retry.c's own
retry_sleepfunction pointer to a recording no-op instead of shrinking its backoff math, so the real retry decision runs without the suite sleeping through it. - The published
Client.billedcounter is a plain, non-atomiclong: a concurrency test gives each thread its ownClient(as a real multi-threaded caller would) instead of pretending one shared counter is race-safe when it was never built to be.
Why not just call the real API in a C test suite?
Every SellerMagnet API request is billed per the table below, whether it comes from production code or a test run. A CI run that fires on every push would spend credits on every build, a slow or flaky network turns a code bug into a failed pipeline, and a 429 or a second 500 in a row cannot be forced on demand against the live API at all. A fake server makes every status code in the table, including the rare ones, reproducible on every run.
| Scenario | Charged | Retry? | Client should |
|---|---|---|---|
| happy path lookup | billed | no | decode, 1 credit |
| lookup, no featured offer ("N/A") | billed | no | price stays absent, never 0 |
| offers buyBox {} (nobody holds it) | billed | no | no offer cell, not a crash |
| offers buyBox.totalPrice 0.0 | billed | no | 0.0 is not a real offer |
| statistics not covered (free 400) | free | no | "not covered", never billed |
| 404 product not found | billed | no | record it; never retry |
| 401 bad key | free | no | stop; never retry |
| 429 concurrency cap | free | yes | wait Retry-After, then retry |
| 500 internal error | refunded | yes | retry once, then stop |
| 502 / 503 upstream | billed | yes | retry up to the attempt cap |
| connection refused | free | yes | never reached the API |
| non-JSON error body | billed | no | parsed safely, never crash |
How do I fake just the server, not my own code?
client_from_env() already reads SELLERMAGNET_API_BASE, documented as existing "only for pointing the client at a local mock server in tests". fake_server.c turns that seam into something a test suite can script per scenario: fake_server_install(route) appends exactly one response to a FIFO queue (one entry per request, mutex-guarded so concurrent callers never race on which response goes to which connection's identity), and an empty queue answers 500 "no route installed", so a test that forgets to install a response fails loudly instead of reaching for a plausible empty answer. client_get_once() and get_with_retry() (both from the C quickstart) run exactly as they would in production.

fake_server.c - a real local POSIX socket server, scriptable per test, fails closed
#include "fake_server.h"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#define MAX_ROUTES 128
static int listen_fd = -1;
static int server_port = 0;
static char base_url[64];
static pthread_t accept_thread;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static FakeRoute queue[MAX_ROUTES];
static int queue_len = 0;
static int queue_pos = 0; /* next unconsumed index */
static int calls = 0;
static int running = 0;
static void send_response(int fd, int status, const char *body, int retry_after) {
char head[512];
int body_len = body ? (int)strlen(body) : 0;
int n;
if (retry_after >= 0) {
n = snprintf(head, sizeof(head),
"HTTP/1.1 %d X\r\nContent-Type: application/json\r\nRetry-After: %d\r\n"
"Content-Length: %d\r\nConnection: close\r\n\r\n",
status, retry_after, body_len);
} else {
n = snprintf(head, sizeof(head),
"HTTP/1.1 %d X\r\nContent-Type: application/json\r\n"
"Content-Length: %d\r\nConnection: close\r\n\r\n",
status, body_len);
}
if (write(fd, head, (size_t)n) < 0) return;
if (body_len) { if (write(fd, body, (size_t)body_len) < 0) return; }
}
static void *handle_conn(void *argp) {
int fd = *(int *)argp;
free(argp);
/* Read (and discard) the request up to the blank line; a GET has no body to worry about. */
char buf[4096];
size_t total = 0;
for (;;) {
ssize_t r = read(fd, buf + total, sizeof(buf) - 1 - total);
if (r <= 0) break;
total += (size_t)r;
buf[total] = '\0';
if (total >= 4 && strstr(buf, "\r\n\r\n")) break;
if (total >= sizeof(buf) - 1) break;
}
pthread_mutex_lock(&lock);
calls++;
int have = queue_pos < queue_len;
FakeRoute r;
if (have) {
r = queue[queue_pos];
queue_pos++;
}
pthread_mutex_unlock(&lock);
if (have) {
send_response(fd, r.status, r.body, r.retry_after);
} else {
send_response(fd, 500, "{\"success\":false,\"message\":\"no route installed\"}", -1);
}
close(fd);
return NULL;
}
static void *accept_loop(void *unused) {
(void)unused;
while (running) {
struct sockaddr_in addr;
socklen_t alen = sizeof(addr);
int fd = accept(listen_fd, (struct sockaddr *)&addr, &alen);
if (fd < 0) {
if (!running) break;
continue;
}
pthread_t t;
int *fdp = malloc(sizeof(int));
*fdp = fd;
pthread_create(&t, NULL, handle_conn, fdp);
pthread_detach(t);
}
return NULL;
}
const char *fake_server_start(void) {
if (running) return base_url;
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
int opt = 1;
setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
struct sockaddr_in addr = {0};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = 0; /* ephemeral port, assigned by the kernel */
if (bind(listen_fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
perror("bind");
exit(1);
}
socklen_t alen = sizeof(addr);
getsockname(listen_fd, (struct sockaddr *)&addr, &alen);
server_port = ntohs(addr.sin_port);
listen(listen_fd, 64);
running = 1;
pthread_create(&accept_thread, NULL, accept_loop, NULL);
snprintf(base_url, sizeof(base_url), "http://127.0.0.1:%d/api", server_port);
return base_url;
}
void fake_server_install(FakeRoute route) {
pthread_mutex_lock(&lock);
if (queue_len < MAX_ROUTES) queue[queue_len++] = route;
pthread_mutex_unlock(&lock);
}
int fake_server_call_count(void) {
pthread_mutex_lock(&lock);
int c = calls;
pthread_mutex_unlock(&lock);
return c;
}
void fake_server_reset(void) {
pthread_mutex_lock(&lock);
queue_len = 0;
queue_pos = 0;
calls = 0;
pthread_mutex_unlock(&lock);
}
void fake_server_stop(void) {
if (!running) return;
running = 0;
shutdown(listen_fd, SHUT_RDWR);
close(listen_fd);
pthread_join(accept_thread, NULL);
}

What does a full scenario suite look like, with no new dependency?
fake_server_start() binds one ephemeral port for the whole process and fake_server_reset() clears its FIFO queue and call counter between tests, so a leftover scripted response from one scenario can never leak into the next. Each test builds a plain Client struct pointed at that server (no client_from_env() call needed once the seam itself is proven once), with retry_sleep swapped to a recording no-op, so the 429/500/502 scenarios exercise retry.c's real decision logic - which codes retry, which stop after one 500, which cap at 4 attempts - without the suite actually sleeping through an exponential backoff. A dedicated concurrency test fires 5 lookups at once, each with its own Client, to prove no request the fake server answers ever goes missing.
test_runner.c - the scenario suite, run for real below
/* test_runner.c - a self-built reflection-free runner (no CUnit/Check dependency), matching the
quickstart's own "standard library is enough" pitch (libcurl + json-c only). Each scenario is a
plain function returning 1 (pass) or 0 (fail, with a printed reason); main() runs them in order
and reports a PASS/FAIL tally. */
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/decode.h"
#include "../src/retry.h"
#include "../src/sellermagnet.h"
#include "fake_server.h"
/* retry.c defines this with external linkage (not static); declared here instead of touching the
published retry.h, which must stay byte-identical to the quickstart. */
extern void (*retry_sleep)(int seconds);
static int recorded_sleep_calls = 0;
static int recorded_sleep_last_seconds = -1;
static void no_sleep(int seconds) {
recorded_sleep_calls++;
recorded_sleep_last_seconds = seconds;
}
#define CHECK(cond, msg) do { if (!(cond)) { printf(" FAIL: %s\n", msg); return 0; } } while (0)
static Client make_client(const char *base) {
Client c;
memset(&c, 0, sizeof(c));
snprintf(c.base, sizeof(c.base), "%s", base);
snprintf(c.key, sizeof(c.key), "%s", "test-key-123");
c.timeout_s = 5;
c.billed = 0;
return c;
}
/* ---- 1: happy path, via the real documented SELLERMAGNET_API_BASE/KEY env seam ---- */
static int test_happy_path_env_seam(void) {
fake_server_reset();
const char *base = fake_server_start();
setenv("SELLERMAGNET_API_BASE", base, 1);
setenv("SELLERMAGNET_API_KEY", "test-key-123", 1);
fake_server_install((FakeRoute){200,
"{\"success\":true,\"data\":{\"productInfo\":{\"asin\":\"B0CL61F39H\",\"title\":\"Test\",\"link\":\"l\","
"\"buyBoxInfo\":{\"price\":42.5,\"currencyCode\":\"USD\",\"sellerId\":\"S1\"}}}}", -1});
Client *c = client_from_env();
CHECK(c != NULL, "client_from_env should succeed with both env vars set");
struct json_object *out = NULL;
ApiResult res;
const char *keys[] = {"asin", "marketplaceId"};
const char *vals[] = {"B0CL61F39H", "ATVPDKIKX0DER"};
int rc = client_get_once(c, "amazon-product-lookup", keys, vals, 2, &out, &res);
CHECK(rc == 0, "expected success");
struct json_object *info = NULL;
json_object_object_get_ex(out, "productInfo", &info);
double price;
struct json_object *bbi = NULL;
json_object_object_get_ex(info, "buyBoxInfo", &bbi);
CHECK(double_or_na(bbi, "price", &price) == 1, "price should decode as a number");
CHECK(price == 42.5, "price value mismatch");
CHECK(c->billed == 1, "a 200 must bill exactly once");
json_object_put(out);
client_free(c);
return 1;
}
/* ---- 2: "N/A" price decodes to no value, never a crash ---- */
static int test_na_price_to_null(void) {
struct json_object *obj = json_tokener_parse("{\"price\":\"N/A\"}");
double v;
CHECK(double_or_na(obj, "price", &v) == 0, "\"N/A\" must not decode as a number");
json_object_put(obj);
return 1;
}
/* ---- 3: an empty buyBox object has no price ---- */
static int test_empty_buybox_no_price(void) {
struct json_object *obj = json_tokener_parse("{}");
double v;
CHECK(double_or_na(obj, "totalPrice", &v) == 0, "an empty buyBox must not yield a price");
json_object_put(obj);
return 1;
}
/* ---- 4: a buyBox totalPrice of exactly 0.0 is not "a price" (main.c's own total > 0.0 guard) ---- */
static int test_zero_price_not_a_real_price(void) {
struct json_object *obj = json_tokener_parse("{\"totalPrice\":0.0}");
double v;
int decoded = double_or_na(obj, "totalPrice", &v);
CHECK(decoded == 1, "0.0 is still a decodable number");
CHECK(!(decoded && v > 0.0), "main.c's offer_cell logic must treat 0.0 as no real offer");
json_object_put(obj);
return 1;
}
/* ---- 5: statistics' free 400 (uncovered marketplace) never bills ---- */
static int test_statistics_free_400_not_billed(void) {
fake_server_reset();
fake_server_install((FakeRoute){400, "{\"success\":false,\"message\":\"marketplace not covered\"}", -1});
Client c = make_client(fake_server_start());
struct json_object *out = NULL;
ApiResult res;
const char *keys[] = {"asin", "marketplaceId"};
const char *vals[] = {"B0CL61F39H", "A2VIGQ35RCS4UG"};
int rc = client_get_once(&c, "amazon-product-statistics", keys, vals, 2, &out, &res);
CHECK(rc != 0, "a free-gate 400 is an error, not a success");
CHECK(res.status == 400, "status mismatch");
CHECK(c.billed == 0, "a free-gate 400 must never bill");
return 1;
}
/* ---- 6: a billed 404 is never retried ---- */
static int test_404_billed_not_retried(void) {
fake_server_reset();
fake_server_install((FakeRoute){404, "{\"success\":false,\"message\":\"Invalid product\"}", -1});
Client c = make_client(fake_server_start());
struct json_object *out = NULL;
ApiResult res;
const char *keys[] = {"asin", "marketplaceId"};
const char *vals[] = {"B0NOTFOUND", "ATVPDKIKX0DER"};
int rc = get_with_retry(&c, "amazon-product-lookup", keys, vals, 2, &out, &res);
CHECK(rc != 0, "404 must be reported as an error");
CHECK(fake_server_call_count() == 1, "404 must not be retried");
CHECK(c.billed == 1, "a 404 is billed exactly once");
return 1;
}
/* ---- 7: a malformed (9-char) ASIN is skipped before it ever costs a credit ---- */
static int test_malformed_asin_skipped(void) {
fake_server_reset();
fake_server_start();
CHECK(is_asin("B0CL61F39") == 0, "a 9-character string is not a valid ASIN");
CHECK(is_asin("b0cl61f39h") == 0, "lower-case must be rejected, not upper-cased");
CHECK(is_asin("B0CL61F39H") == 1, "a real 10-char upper-alnum ASIN must pass");
CHECK(fake_server_call_count() == 0, "a format check must never touch the network");
return 1;
}
/* ---- 8: a 429 is retried honouring the server's own Retry-After, then succeeds ---- */
static int test_429_retried_honours_retry_after(void) {
fake_server_reset();
fake_server_install((FakeRoute){429, "{\"success\":false,\"message\":\"rate limited\"}", 5});
fake_server_install((FakeRoute){200, "{\"success\":true,\"data\":{\"ok\":true}}", -1});
Client c = make_client(fake_server_start());
recorded_sleep_calls = 0;
recorded_sleep_last_seconds = -1;
retry_sleep = no_sleep;
struct json_object *out = NULL;
ApiResult res;
const char *keys[] = {"asin"};
const char *vals[] = {"B0CL61F39H"};
int rc = get_with_retry(&c, "amazon-product-lookup", keys, vals, 1, &out, &res);
retry_sleep = NULL;
CHECK(rc == 0, "the retry must eventually succeed");
CHECK(fake_server_call_count() == 2, "exactly one retry expected");
CHECK(recorded_sleep_calls == 1, "one backoff wait expected");
CHECK(recorded_sleep_last_seconds >= 5, "wait must honour the server's Retry-After, not just the fixed backoff");
CHECK(c.billed == 1, "only the succeeding 200 is billed, not the free 429");
if (out) json_object_put(out);
return 1;
}
/* ---- 9: a 500 is refunded, retried once, and billed only once it succeeds ---- */
static int test_500_refunded_then_success(void) {
fake_server_reset();
fake_server_install((FakeRoute){500, "{\"success\":false,\"message\":\"internal\"}", -1});
fake_server_install((FakeRoute){200, "{\"success\":true,\"data\":{\"ok\":true}}", -1});
Client c = make_client(fake_server_start());
retry_sleep = no_sleep;
struct json_object *out = NULL;
ApiResult res;
const char *keys[] = {"asin"};
const char *vals[] = {"B0CL61F39H"};
int rc = get_with_retry(&c, "amazon-product-lookup", keys, vals, 1, &out, &res);
retry_sleep = NULL;
CHECK(rc == 0, "a single 500 followed by a 200 must succeed");
CHECK(c.billed == 1, "the refunded 500 must not bill; only the 200 bills");
if (out) json_object_put(out);
return 1;
}
/* ---- 10: a second consecutive 500 is reported, not retried a third time ---- */
static int test_second_consecutive_500_stops(void) {
fake_server_reset();
fake_server_install((FakeRoute){500, "{\"success\":false,\"message\":\"internal\"}", -1});
fake_server_install((FakeRoute){500, "{\"success\":false,\"message\":\"internal again\"}", -1});
Client c = make_client(fake_server_start());
retry_sleep = no_sleep;
struct json_object *out = NULL;
ApiResult res;
const char *keys[] = {"asin"};
const char *vals[] = {"B0CL61F39H"};
int rc = get_with_retry(&c, "amazon-product-lookup", keys, vals, 1, &out, &res);
retry_sleep = NULL;
CHECK(rc != 0, "two 500s in a row must be reported as a failure");
CHECK(fake_server_call_count() == 2, "must stop after exactly two attempts, not retry a third time");
CHECK(c.billed == 0, "two refunded 500s must never bill");
return 1;
}
/* ---- 11: a 502 is billed on every attempt up to the cap ---- */
static int test_502_billed_every_attempt(void) {
fake_server_reset();
for (int i = 0; i < 4; i++)
fake_server_install((FakeRoute){502, "{\"success\":false,\"message\":\"bad gateway\"}", -1});
Client c = make_client(fake_server_start());
retry_sleep = no_sleep;
struct json_object *out = NULL;
ApiResult res;
const char *keys[] = {"asin"};
const char *vals[] = {"B0CL61F39H"};
int rc = get_with_retry(&c, "amazon-product-lookup", keys, vals, 1, &out, &res);
retry_sleep = NULL;
CHECK(rc != 0, "4 consecutive 502s must exhaust the attempt cap and fail");
CHECK(fake_server_call_count() == 4, "exactly 4 attempts expected (ATTEMPTS)");
CHECK(c.billed == 4, "every 502, including retries, is billed");
return 1;
}
/* ---- 12: a 401 is never retried (an answer, not a transient failure) ---- */
static int test_401_not_retried(void) {
fake_server_reset();
fake_server_install((FakeRoute){401, "{\"success\":false,\"message\":\"bad key\"}", -1});
Client c = make_client(fake_server_start());
retry_sleep = no_sleep;
struct json_object *out = NULL;
ApiResult res;
const char *keys[] = {"asin"};
const char *vals[] = {"B0CL61F39H"};
int rc = get_with_retry(&c, "amazon-product-lookup", keys, vals, 1, &out, &res);
retry_sleep = NULL;
CHECK(rc != 0, "401 must be reported as an error");
CHECK(fake_server_call_count() == 1, "401 must not be retried");
CHECK(c.billed == 0, "401 (dead key) must never bill");
return 1;
}
/* ---- 13: a non-JSON body on a billed error status is handled, never crashes the parser ---- */
static int test_non_json_error_body(void) {
fake_server_reset();
for (int i = 0; i < 4; i++)
fake_server_install((FakeRoute){502, "<html>upstream broken</html>", -1});
Client c = make_client(fake_server_start());
retry_sleep = no_sleep;
struct json_object *out = NULL;
ApiResult res;
const char *keys[] = {"asin"};
const char *vals[] = {"B0CL61F39H"};
int rc = get_with_retry(&c, "amazon-product-lookup", keys, vals, 1, &out, &res);
retry_sleep = NULL;
CHECK(rc != 0, "a non-JSON 502 body is still a failure, not a crash");
CHECK(strstr(res.message, "non-JSON") != NULL, "message should say the body was not JSON");
CHECK(c.billed == 4, "every billed 502 attempt still counts even with a non-JSON body");
return 1;
}
/* ---- 14: a real connection-refused error is treated as transport-level and retried ---- */
static int test_transport_error_connection_refused(void) {
fake_server_reset();
fake_server_start(); /* keep the real server up but unused: this client points elsewhere */
Client c = make_client("http://127.0.0.1:1/api"); /* privileged port, nothing listens: ECONNREFUSED */
c.timeout_s = 2;
retry_sleep = no_sleep;
struct json_object *out = NULL;
ApiResult res;
const char *keys[] = {"asin"};
const char *vals[] = {"B0CL61F39H"};
int rc = get_with_retry(&c, "amazon-product-lookup", keys, vals, 1, &out, &res);
retry_sleep = NULL;
CHECK(rc != 0, "an unreachable server must fail");
CHECK(res.is_transport == 1, "a connection refusal is a transport error, not an HTTP status");
CHECK(c.billed == 0, "a request that never reached the API must never bill");
CHECK(fake_server_call_count() == 0, "the real server was never touched by this client");
return 1;
}
/* ---- 15: N concurrent lookups (one Client instance per thread) are each billed exactly once,
no call lost and no call double-counted ---- */
typedef struct { Client c; int ok; } ThreadArg;
static void *conc_worker(void *argp) {
ThreadArg *a = (ThreadArg *)argp;
struct json_object *out = NULL;
ApiResult res;
const char *keys[] = {"asin"};
const char *vals[] = {"B0CL61F39H"};
int rc = client_get_once(&a->c, "amazon-product-lookup", keys, vals, 1, &out, &res);
a->ok = (rc == 0);
if (out) json_object_put(out);
return NULL;
}
static int test_concurrent_requests(void) {
fake_server_reset();
const char *base = fake_server_start();
const int N = 5;
for (int i = 0; i < N; i++)
fake_server_install((FakeRoute){200, "{\"success\":true,\"data\":{\"ok\":true}}", -1});
ThreadArg args[5];
pthread_t th[5];
for (int i = 0; i < N; i++) {
args[i].c = make_client(base);
pthread_create(&th[i], NULL, conc_worker, &args[i]);
}
long billed_sum = 0;
for (int i = 0; i < N; i++) {
pthread_join(th[i], NULL);
CHECK(args[i].ok, "every concurrent request must succeed");
billed_sum += args[i].c.billed;
}
CHECK(billed_sum == N, "every concurrent request must bill exactly once, none lost or doubled");
CHECK(fake_server_call_count() == N, "the server must see exactly N requests");
return 1;
}
/* ---- 16: statistics minor-unit decoding: whole yen on JP, cents elsewhere ---- */
static int test_minor_to_decimal_jp_vs_others(void) {
CHECK(minor_to_decimal(41800, "A1VC38T7YXB528") == 41800.0, "JP must stay whole yen, not /100");
CHECK(minor_to_decimal(41800, "ATVPDKIKX0DER") == 418.0, "every non-JP marketplace divides by 100");
return 1;
}
/* ---- 17: a negative-cents history point does not decode as a number the caller can misuse ---- */
static int test_long_or_na_rejects_non_int(void) {
struct json_object *obj = json_tokener_parse("{\"buyBoxPrice\":\"N/A\"}");
long v;
CHECK(long_or_na(obj, "buyBoxPrice", &v) == 0, "a non-integer buyBoxPrice must decode as absent, not 0");
json_object_put(obj);
struct json_object *obj2 = json_tokener_parse("{\"buyBoxPrice\":41800}");
CHECK(long_or_na(obj2, "buyBoxPrice", &v) == 1 && v == 41800, "a real integer must decode correctly");
json_object_put(obj2);
return 1;
}
typedef struct { const char *name; int (*fn)(void); } TestCase;
int main(void) {
TestCase cases[] = {
{"happy_path_env_seam", test_happy_path_env_seam},
{"na_price_to_null", test_na_price_to_null},
{"empty_buybox_no_price", test_empty_buybox_no_price},
{"zero_price_not_a_real_price", test_zero_price_not_a_real_price},
{"statistics_free_400_not_billed", test_statistics_free_400_not_billed},
{"404_billed_not_retried", test_404_billed_not_retried},
{"malformed_asin_skipped", test_malformed_asin_skipped},
{"429_retried_honours_retry_after", test_429_retried_honours_retry_after},
{"500_refunded_then_success", test_500_refunded_then_success},
{"second_consecutive_500_stops", test_second_consecutive_500_stops},
{"502_billed_every_attempt", test_502_billed_every_attempt},
{"401_not_retried", test_401_not_retried},
{"non_json_error_body", test_non_json_error_body},
{"transport_error_connection_refused", test_transport_error_connection_refused},
{"concurrent_requests", test_concurrent_requests},
{"minor_to_decimal_jp_vs_others", test_minor_to_decimal_jp_vs_others},
{"long_or_na_rejects_non_int", test_long_or_na_rejects_non_int},
};
int n = (int)(sizeof(cases) / sizeof(cases[0]));
int pass = 0;
for (int i = 0; i < n; i++) {
printf("[%2d/%2d] %-40s ", i + 1, n, cases[i].name);
int ok = cases[i].fn();
printf("%s\n", ok ? "PASS" : "FAIL");
if (ok) pass++;
}
fake_server_stop();
printf("\n%d/%d scenarios passed\n", pass, n);
return pass == n ? 0 : 1;
}
./test/run output (unmodified run)
amazon-product-lookup: 429: rate limited (retry 1/3 in 5 s)
amazon-product-lookup: 500: internal (retry 1/3 in 1 s)
amazon-product-lookup: 500: internal (retry 1/3 in 1 s)
amazon-product-lookup: 502: bad gateway (retry 1/3 in 1 s)
amazon-product-lookup: 502: bad gateway (retry 2/3 in 2 s)
amazon-product-lookup: 502: bad gateway (retry 3/3 in 3 s)
amazon-product-lookup: 502: non-JSON response (status 502) (retry 1/3 in 1 s)
amazon-product-lookup: 502: non-JSON response (status 502) (retry 2/3 in 2 s)
amazon-product-lookup: 502: non-JSON response (status 502) (retry 3/3 in 3 s)
amazon-product-lookup: -1: transport: Couldn't connect to server (retry 1/3 in 1 s)
amazon-product-lookup: -1: transport: Couldn't connect to server (retry 2/3 in 2 s)
amazon-product-lookup: -1: transport: Couldn't connect to server (retry 3/3 in 3 s)
[ 1/17] happy_path_env_seam PASS
[ 2/17] na_price_to_null PASS
[ 3/17] empty_buybox_no_price PASS
[ 4/17] zero_price_not_a_real_price PASS
[ 5/17] statistics_free_400_not_billed PASS
[ 6/17] 404_billed_not_retried PASS
[ 7/17] malformed_asin_skipped PASS
[ 8/17] 429_retried_honours_retry_after PASS
[ 9/17] 500_refunded_then_success PASS
[10/17] second_consecutive_500_stops PASS
[11/17] 502_billed_every_attempt PASS
[12/17] 401_not_retried PASS
[13/17] non_json_error_body PASS
[14/17] transport_error_connection_refused PASS
[15/17] concurrent_requests PASS
[16/17] minor_to_decimal_jp_vs_others PASS
[17/17] long_or_na_rejects_non_int PASS
17/17 scenarios passed
Never hand-write a fake of get_with_retry itself
A fake that reimplements client_get_once or retry.c's own backoff tests the fake's own logic, not the real client. Fake one layer below your code - here, the socket it talks to - so a real bug in the JSON decoding or retry logic still shows up as a failing test.
Does the same pattern work for other languages?
Yes, fake the one call the real code makes to the network, whichever shape that takes. The Python guide fakes requests.Session.get, the Go guide fakes http.RoundTripper, the Rust guide points reqwest at a local mockito server, and the Elixir guide rolls a similar ~100-line :gen_tcp listener for a client with no handler-injection seam of its own; this guide does the same thing with raw POSIX sockets and pthreads instead, since the C quickstart already has no HTTP server library to borrow a seam from. The 429/Retry-After guide and the 502/503 retry guide are the production behaviour this suite checks against; keep all three in sync when the retry logic changes. Credit costs and the free trial are on the pricing page, and every endpoint's parameters are in the API documentation and code examples.
Frequently Asked Questions
Can C tests just call the real SellerMagnet API instead of faking it?
They can, but every call is billed the same as production traffic, so a CI run that fires on every push spends credits on every build, and a flaky network turns a code bug into a failed pipeline. A local fake server lets every billed, free and refunded status show up on demand while sellermagnet.c, decode.c and retry.c from the C quickstart run completely unmodified.
Why hand-roll a socket server instead of linking libmicrohttpd?
The C quickstart's own pitch is "libcurl and json-c, nothing else"; pulling in a new HTTP server library just for tests breaks that. fake_server.c is about 100 lines of plain POSIX sockets and pthreads (both already linked for any real C network program): bind an ephemeral port, accept in a loop, hand each connection to a detached thread that reads the request up to the blank line and writes back whichever response is next in the FIFO queue.
Why not use Check or CUnit for the test runner?
Either works fine here too, but matching the quickstart's own "no build tool, no new dependency" pitch, test_runner.c is a plain array of {name, function pointer} pairs that main() loops over and reports PASS or FAIL for, compiled with nothing beyond the gcc and libraries the quickstart itself already needs.
How do I avoid real waits for a 429 or 500 retry test?
This suite does not shrink retry.c's own backoff math, only its wait: retry.c already exposes a void (*retry_sleep)(int seconds) function pointer, NULL (real sleep) in production, that a test swaps to a recording no-op. The real retry decision runs - which status codes retry, which stop after one 500, which cap at the 4-attempt limit - without the test suite actually sleeping through an exponential backoff.
Does the fake server handle concurrent requests safely?
Yes, with one honest caveat: the published Client struct's own billed counter is a plain long, not atomic, so this suite gives each concurrent caller its own Client instance (exactly how a multi-threaded program would use the library in practice) and sums their billed counts after joining every thread, rather than sharing one Client across threads. A dedicated scenario fires 5 lookups at once against one shared fake_server and asserts the server saw exactly 5 requests with none lost.
Should the fake answer anything if a test forgets to install a route?
No. fake_server_install() queues one scripted response per call, FIFO; once the queue is empty, the next request gets a 500 "no route installed" instead of a silently plausible empty answer, so a forgotten fake_server_install() call fails the test loudly.
Bottom line: point whatever base-URL seam your language's quickstart already exposes (here, the C quickstart's own SELLERMAGNET_API_BASE environment variable) at a local socket fake, run the real client code against scripted responses for every billed, free and refunded status, and make the fake fail closed so a forgotten scenario cannot send a real, billed request. The whole suite above runs in well under a second - retry.c's own retry_sleep function pointer is swapped to a no-op, so the real retry decisions run without any real waiting - and spends zero credits, with nothing beyond gcc, libcurl and json-c.