Home / Blog / Mock the SellerMagnet API in PHP Tests Without Spending Credits

Mock the SellerMagnet API in PHP Tests Without Spending Credits

Test the Guzzle-based PHP client that calls the SellerMagnet API without hitting it: point Client.php's own base-URL test seam at a local `php -S` stub, run the real Client.php / Models.php / Retries.php from the PHP quickstart unchanged, and cover every billed, free and refunded status code with a 19-test PHPUnit suite that runs in under a second.

November 15, 2026
6 min read
SellerMagnet Team
Share & Bookmark
Terminal window showing a PHPUnit run that fakes the SellerMagnet API behind a local php -S stub while the real Guzzle client code runs unchanged

Mock the SellerMagnet API in PHP tests by pointing Guzzle at a local php -S stub instead of the real API: Client.php's own constructor already accepts a base URL for exactly this, documented on fromEnv() as the way tests point the client at a local mock. Run the unchanged Client.php, Models.php and Retries.php from the PHP quickstart against it: no credit is spent, no real request reaches sellermagnet-api.com, and the public $sleep closure keeps the 19-test PHPUnit suite below under a second despite exercising real retry logic.

Key Takeaways

  • Client.php keeps its Guzzle instance private with no constructor option for a handler stack, so there is no in-process transport to swap the way Go's httpClient.Transport can be; the base-URL constructor argument is the only test seam that exists, and it is the one the quickstart's own comment already documents.
  • Swap the public $sleep closure to a no-op before each test so Retries::get()'s real exponential backoff never actually waits, without touching Retries.php itself.
  • A 404 and an endpoint's own 400 are billed answers and must never be retried; a free gate 400, a 429 and a connection-refused error cost nothing and are safe to retry.
  • A cURL timeout (CURLE_OPERATION_TIMEDOUT) is NOT the same as a connection refused (CURLE_COULDNT_CONNECT): only the latter is in Retries::NOT_SENT, so only the latter is retried.
  • Fail closed: the stub answers 500 "no route installed" for any path a test did not script, so a forgotten scenario fails loudly instead of quietly returning a plausible empty response.

Why not just call the real API in a PHPUnit test suite?

Every SellerMagnet API request is billed per the table below, whether it comes from production code or phpunit. 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 dropped connection or a second 500 in a row cannot be forced on demand against the live API at all. A local stub makes every status code in the table, including the rare ones, reproducible on every run.

Scenarios worth testing, and what the stub needs to script for each.
ScenarioChargedRetry?Client should
happy path lookupbillednodecode, 1 credit
lookup, no featured offer ("N/A")billednoprice stays null, never 0.0
offers, empty buyBox objectbillednobuyBox stays null, not a crash
404 product not foundbillednorecord it, never retry
free gate 400 (missing parameter)freenofix the request, no retry
endpoint's own 400 (unsupported marketplace)billednoa real answer, not a gate
429 concurrency capfreeyeswait Retry-After, then retry
500 with Retry-Afterbilledonceretry once, then stop on a 2nd 500
502 / 503 upstreambilledyesretry up to the attempt cap
cURL timeout (operation timed out)billednomay still be running; report, never resend
cURL connection refusedfreeyesnever reached the API; safe to retry

How do I fake just the HTTP layer, not my own code?

Client::__construct() takes the base URL as its second argument, defaulting to the live API but accepting anything, and fromEnv() reads an override from SELLERMAGNET_API_BASE for exactly this purpose. Start a php -S 127.0.0.1:<port> router.php process before the suite runs, point every test's Client at it, and let get(), getOnce() and the Retries trait (all from the PHP quickstart) run exactly as they would in production. The router fails closed: any path it does not recognise answers 500 "no route installed", so a scenario a test forgot to script cannot silently pass.

Blueprint sequence diagram of a PHPUnit test pointing the SellerMagnet PHP client at a local php -S stub while the real client code runs unchanged
Only the base URL is faked; Client.php, Models.php and Retries.php run unmodified.

tests/router.php - a local stub, served by php -S, fails closed

<?php
declare(strict_types=1);

// Tiny stub of the real API for `php -S`: fails closed on any path it doesn't
// recognize (500 "no route installed"), so a scenario can never silently fall
// through to an unintended response. Call counts persist in a file because
// each request to `php -S` is its own process.
$countsFile = __DIR__ . '/.counts.json';
$path = trim($_SERVER['REQUEST_URI'], '/');
$path = parse_url($path, PHP_URL_PATH) ?? $path;

$counts = is_file($countsFile) ? json_decode((string) file_get_contents($countsFile), true) : [];
$counts[$path] = ($counts[$path] ?? 0) + 1;
file_put_contents($countsFile, json_encode($counts));
$n = $counts[$path];

header('Content-Type: application/json');

function respond(int $status, array|string $body, array $headers = []): void
{
    http_response_code($status);
    foreach ($headers as $k => $v) {
        header("$k: $v");
    }
    echo is_array($body) ? json_encode($body) : $body;
    exit;
}

if (($_SERVER['HTTP_X_API_KEY'] ?? '') !== 'test-key' && $path !== 'reset') {
    respond(401, ['success' => false, 'message' => 'Invalid or inactive API key.']);
}

switch ($path) {
    case 'reset':
        file_put_contents($countsFile, json_encode([]));
        respond(200, ['ok' => true]);

    case 'amazon-product-lookup':
        $asin = $_GET['asin'] ?? '';
        if ($asin === 'B0CL61F39H') {
            respond(200, ['success' => true, 'data' => ['productInfo' => [
                'asin' => 'B0CL61F39H',
                'buyBoxInfo' => ['price' => 444.99, 'currencyCode' => 'USD'],
            ]]]);
        }
        if ($asin === 'B0NOOFFER01') {
            respond(200, ['success' => true, 'data' => ['productInfo' => [
                'asin' => 'B0NOOFFER01',
                'buyBoxInfo' => ['price' => 'N/A', 'currencyCode' => 'N/A'],
            ]]]);
        }
        respond(404, ['success' => false, 'message' => 'Invalid product']);

    case 'amazon-product-offers':
        $asin = $_GET['asin'] ?? '';
        if ($asin === 'B0CL61F39H') {
            respond(200, ['success' => true, 'data' => [
                'currency' => ['code' => 'USD'],
                'buyBox' => ['sellerId' => 'A3853PJW50SJG8', 'condition' => 'New', 'fulfillmentType' => 'FBA',
                    'priceWithoutShipping' => 439.99, 'totalPrice' => 444.9949, 'inventory' => 10],
                'offers' => [
                    ['sellerId' => 'A3853PJW50SJG8', 'condition' => 'New', 'fulfillmentType' => 'FBA',
                        'priceWithoutShipping' => 439.99, 'totalPrice' => 444.9949, 'inventory' => 10],
                    ['sellerId' => 'AOTHER1', 'condition' => 'New', 'fulfillmentType' => 'FBM',
                        'priceWithoutShipping' => 420.00, 'totalPrice' => 430.50, 'inventory' => 3],
                ],
            ]]);
        }
        // empty buyBox object: nobody holds the Buy Box right now
        respond(200, ['success' => true, 'data' => [
            'currency' => ['code' => 'USD'], 'buyBox' => (object) [], 'offers' => [],
        ]]);

    case 'amazon-product-statistics':
        $market = $_GET['marketplaceId'] ?? '';
        if ($market === 'A1VC38T7YXB528') { // amazon.co.jp: yen has no minor unit
            respond(200, ['success' => true, 'data' => [
                'buyBoxPrice' => 55000, 'buyBoxFulfillment' => 'FBA',
            ]]);
        }
        if ($market === 'A2VIGQ35RCS4UG') { // not covered -> free gate 400
            respond(400, ['success' => false, 'message' => 'Invalid marketplaceId for this endpoint']);
        }
        if ($market === 'NOHOLDER') {
            respond(200, ['success' => true, 'data' => ['buyBoxPrice' => 'N/A', 'buyBoxFulfillment' => null]]);
        }
        respond(200, ['success' => true, 'data' => ['buyBoxPrice' => 41800, 'buyBoxFulfillment' => 'FBM']]);

    case 'always-404':
        respond(404, ['success' => false, 'message' => 'Product not found']);

    case 'gate-400':
        respond(400, ['success' => false, 'message' => 'Missing required parameter: asin']);

    case 'billed-400':
        respond(400, ['success' => false, 'message' => 'This marketplace does not support used offers']);

    case 'flaky-429-then-200':
        if ($n === 1) {
            respond(429, ['success' => false, 'message' => 'Max 40 concurrent requests per API key. Retry shortly.'],
                ['Retry-After' => '2']);
        }
        respond(200, ['success' => true, 'data' => ['ok' => true, 'attempt' => $n]]);

    case 'flaky-500-then-200':
        if ($n === 1) {
            respond(500, ['success' => false, 'message' => 'An internal error occurred. Please try again shortly.'],
                ['Retry-After' => '1']); // WITH Retry-After: this API's 500 is billed+retried once
        }
        respond(200, ['success' => true, 'data' => ['ok' => true, 'attempt' => $n]]);

    case 'always-500-no-retry-after':
        // a 500 with no Retry-After header: free/refunded per getOnce(), but Retries::get() still
        // retries it once (status in RETRYABLE) then gives up on the SECOND 500 (internalErrors > 1)
        respond(500, ['success' => false, 'message' => 'An internal error occurred.']);

    case 'flaky-502-502-200':
        if ($n <= 2) {
            respond(502, ['success' => false, 'message' => 'upstream error']);
        }
        respond(200, ['success' => true, 'data' => ['ok' => true, 'attempt' => $n]]);

    case 'always-503':
        respond(503, ['success' => false, 'message' => 'Service temporarily unavailable']);

    case 'not-json':
        respond(200, '<html>not json</html>');

    case 'slow-timeout':
        usleep(300_000); // 300 ms: longer than the 50 ms client timeout used only by this one test
        respond(200, ['success' => true, 'data' => ['ok' => true]]);

    default:
        respond(500, ['success' => false, 'message' => "no route installed for $path"]);
}
Blueprint table of PHPUnit test scenarios against the SellerMagnet API's status codes, billing and the correct Guzzle client reaction
Each row needs its own scripted response; a happy-path test alone misses most of this.

What does a full PHPUnit scenario suite look like?

Each test builds its own Client pointed at the shared stub server and swaps $sleep to a no-op before calling the private get() method through ReflectionMethod where the public API does not expose a given endpoint directly. The stub tracks a per-path call count in a file (each php -S request is its own process, so static state does not survive between requests), which is how the 404, 429, 500 and 503 tests assert the client retried exactly as many times as Retries::ATTEMPTS allows, never more.

tests/ClientTest.php - the scenario suite, run for real below

<?php

declare(strict_types=1);

namespace SellerMagnet\Tests;

use PHPUnit\Framework\TestCase;
use SellerMagnet\ApiError;
use SellerMagnet\Client;

/**
 * Fakes only the HTTP layer: a local `php -S` process serving tests/router.php stands in for the real
 * API, reusing Client.php / Models.php / Retries.php completely unchanged. The quickstart's own comment
 * on Client::fromEnv() already documents this seam ("SELLERMAGNET_API_BASE only points the client at a
 * local mock in tests") -- unlike the Go quickstart's package-level httpClient.Transport, Guzzle's client
 * here keeps $http PRIVATE, so there is no in-process transport to swap; the base-URL seam the author
 * already built in is the only one that exists, and it is exercised here exactly as written, not added.
 */
final class ClientTest extends TestCase
{
    private static int $port;
    private static $serverProcess;
    private static string $countsFile;

    public static function setUpBeforeClass(): void
    {
        self::$port = 8921;
        self::$countsFile = __DIR__ . '/.counts.json';
        $cmd = sprintf('exec php -S 127.0.0.1:%d %s', self::$port, escapeshellarg(__DIR__ . '/router.php'));
        self::$serverProcess = proc_open($cmd, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
        $deadline = microtime(true) + 5;
        while (microtime(true) < $deadline) {
            $sock = @fsockopen('127.0.0.1', self::$port, $errno, $errstr, 0.2);
            if ($sock) {
                fclose($sock);
                return;
            }
            usleep(50_000);
        }
        self::fail('local test server did not start');
    }

    public static function tearDownAfterClass(): void
    {
        proc_terminate(self::$serverProcess);
        proc_close(self::$serverProcess);
        @unlink(self::$countsFile);
    }

    private function newClient(float $timeout = 2.0): Client
    {
        @unlink(self::$countsFile);
        $c = new Client('test-key', sprintf('http://127.0.0.1:%d', self::$port), $timeout);
        $c->sleep = static function (float $s): void {
            // record-only: tests must not pay real backoff time
        };
        return $c;
    }

    public function testLookupHappyPathDecimalPrice(): void
    {
        $p = $this->newClient()->lookup('B0CL61F39H', 'ATVPDKIKX0DER');
        $this->assertSame('B0CL61F39H', $p->asin);
        $this->assertSame(444.99, $p->buyBoxPrice);
        $this->assertSame('USD', $p->currencyCode);
    }

    public function testLookupNoOfferPriceIsNullNotZero(): void
    {
        $p = $this->newClient()->lookup('B0NOOFFER01', 'ATVPDKIKX0DER');
        $this->assertNull($p->buyBoxPrice); // "N/A" must become null, never 0.0
    }

    public function testOffersEmptyBuyBoxBecomesNull(): void
    {
        $o = $this->newClient()->offers('B0NOBUYBOX', 'ATVPDKIKX0DER');
        $this->assertNull($o->buyBox); // {} decodes to an empty array, mapped to null
        $this->assertSame([], $o->offers);
    }

    public function testOffersBuyBoxPriceRoundedToCent(): void
    {
        $o = $this->newClient()->offers('B0CL61F39H', 'ATVPDKIKX0DER');
        $this->assertNotNull($o->buyBox);
        $this->assertSame(444.99, $o->buyBox->totalPrice); // 444.9949 rounded once, not truncated
        $cheapest = $o->cheapestNew();
        $this->assertSame('AOTHER1', $cheapest->sellerId); // 430.50 total beats the Buy Box holder's 444.99
    }

    public function testStatisticsMinorUnitsJapanIsWholeYen(): void
    {
        $s = $this->newClient()->statistics('B0CL61F39H', 'A1VC38T7YXB528');
        $this->assertSame(55000, $s->buyBoxPrice->value);
        $this->assertSame(55000.0, $s->buyBoxPrice->toDecimal('A1VC38T7YXB528')); // /1, not /100
    }

    public function testStatisticsMinorUnitsElsewhereDividesBy100(): void
    {
        $s = $this->newClient()->statistics('B0CL61F39H', 'ATVPDKIKX0DER');
        $this->assertSame(41800, $s->buyBoxPrice->value);
        $this->assertSame(418.0, $s->buyBoxPrice->toDecimal('ATVPDKIKX0DER'));
    }

    public function testStatisticsNoHolderIsNullNotZero(): void
    {
        $s = $this->newClient()->statistics('B0CL61F39H', 'NOHOLDER');
        $this->assertNull($s->buyBoxPrice);
        $this->assertNull($s->buyBoxFulfillment);
    }

    public function test404IsBilledOnceAndNeverRetried(): void
    {
        $c = $this->newClient();
        try {
            $c->lookup('B0NOTFOUND1', 'ATVPDKIKX0DER');
            $this->fail('expected ApiError');
        } catch (ApiError $e) {
            $this->assertSame(404, $e->status);
        }
        $this->assertSame(1, $c->billed()); // one credit, exactly one request reached the server
        $counts = json_decode((string) file_get_contents(self::$countsFile), true);
        $this->assertSame(1, $counts['amazon-product-lookup']);
    }

    public function testFreeGate400IsNeverBilledOrRetried(): void
    {
        $c = $this->newClient();
        $method = new \ReflectionMethod($c, 'get');
        try {
            $method->invoke($c, 'gate-400', []);
            $this->fail('expected ApiError');
        } catch (ApiError $e) {
            $this->assertSame(400, $e->status);
        }
        $this->assertSame(0, $c->billed()); // "Missing required parameter" prefix: FREE_400, never charged
    }

    public function testEndpointOwn400IsBilledAndNotRetried(): void
    {
        $c = $this->newClient();
        $method = new \ReflectionMethod($c, 'get');
        try {
            $method->invoke($c, 'billed-400', []);
            $this->fail('expected ApiError');
        } catch (ApiError $e) {
            $this->assertSame(400, $e->status);
        }
        $this->assertSame(1, $c->billed()); // not a FREE_400 prefix match: charged like any other answer
        $counts = json_decode((string) file_get_contents(self::$countsFile), true);
        $this->assertSame(1, $counts['billed-400']); // and not retried
    }

    public function test429IsFreeAndRetriedUntilSuccess(): void
    {
        $c = $this->newClient();
        $method = new \ReflectionMethod($c, 'get');
        $result = $method->invoke($c, 'flaky-429-then-200', []);
        $this->assertTrue($result['ok']);
        $counts = json_decode((string) file_get_contents(self::$countsFile), true);
        $this->assertSame(2, $counts['flaky-429-then-200']); // 1 failed + 1 succeeded
        $this->assertSame(1, $c->billed()); // only the successful 200 is billed; the free 429 is not
    }

    public function test500WithRetryAfterIsBilledAndRetriedOnceThenSucceeds(): void
    {
        $c = $this->newClient();
        $method = new \ReflectionMethod($c, 'get');
        $result = $method->invoke($c, 'flaky-500-then-200', []);
        $this->assertTrue($result['ok']);
        $this->assertSame(2, $c->billed()); // getOnce() bills a 500 that carries Retry-After
    }

    public function testSecond500StopsInsteadOfLooping(): void
    {
        $c = $this->newClient();
        $method = new \ReflectionMethod($c, 'get');
        try {
            $method->invoke($c, 'always-500-no-retry-after', []);
            $this->fail('expected ApiError');
        } catch (ApiError $e) {
            $this->assertSame(500, $e->status);
        }
        $counts = json_decode((string) file_get_contents(self::$countsFile), true);
        $this->assertSame(2, $counts['always-500-no-retry-after']); // retried once, then gives up
    }

    public function test502IsBilledOnEveryAttemptThenSucceeds(): void
    {
        $c = $this->newClient();
        $method = new \ReflectionMethod($c, 'get');
        $result = $method->invoke($c, 'flaky-502-502-200', []);
        $this->assertTrue($result['ok']);
        $this->assertSame(3, $c->billed()); // 502, 502, 200: all three are billed answers
    }

    public function test503RetriesUpToAttemptsThenThrows(): void
    {
        $c = $this->newClient();
        $method = new \ReflectionMethod($c, 'get');
        try {
            $method->invoke($c, 'always-503', []);
            $this->fail('expected ApiError');
        } catch (ApiError $e) {
            $this->assertSame(503, $e->status);
        }
        $counts = json_decode((string) file_get_contents(self::$countsFile), true);
        $this->assertSame(4, $counts['always-503']); // ATTEMPTS = 4, all billed
        $this->assertSame(4, $c->billed());
    }

    public function testNonJsonBodyBecomesApiErrorNotCrash(): void
    {
        $c = $this->newClient();
        $method = new \ReflectionMethod($c, 'get');
        try {
            $method->invoke($c, 'not-json', []);
            $this->fail('expected ApiError');
        } catch (ApiError $e) {
            $this->assertStringContainsString('request failed', $e->getMessage()); // HTML body, not JSON
        }
    }

    public function testTimeoutIsBilledAndNotRetried(): void
    {
        // CURLE_OPERATION_TIMEDOUT is NOT in Retries::NOT_SENT, so the timed-out request (which may
        // still be running server-side, and is billed) is reported at once, never resent.
        $c = $this->newClient(timeout: 0.05);
        $method = new \ReflectionMethod($c, 'get');
        $this->expectException(\GuzzleHttp\Exception\ConnectException::class);
        try {
            $method->invoke($c, 'slow-timeout', []);
        } finally {
            $this->assertSame(1, $c->billed());
        }
    }

    public function testConnectionRefusedIsRetried(): void
    {
        // CURLE_COULDNT_CONNECT IS in Retries::NOT_SENT: the request never left, so it costs nothing
        // and IS retried -- the opposite branch of the timeout test above. Port 1 is reserved and
        // refuses connections for a non-root process on this host.
        $c = new Client('test-key', 'http://127.0.0.1:1', 1.0);
        $calls = 0;
        $c->sleep = static function () use (&$calls): void {
            $calls++;
        };
        $method = new \ReflectionMethod($c, 'get');
        try {
            $method->invoke($c, 'amazon-product-lookup', ['asin' => 'X', 'marketplaceId' => 'Y']);
            $this->fail('expected a connection exception');
        } catch (\GuzzleHttp\Exception\ConnectException) {
            // expected after ATTEMPTS retries
        }
        $this->assertSame(3, $calls); // 4 attempts total: 3 retries in between
        $this->assertSame(0, $c->billed()); // never reached the server, never charged
    }

    public function testIsAsinValidatesShapeNotCredits(): void
    {
        $this->assertTrue(Client::isAsin('B0CL61F39H'));
        $this->assertFalse(Client::isAsin('B0CL61F39')); // 9 characters
        $this->assertFalse(Client::isAsin('b0cl61f39h')); // lower case
        $this->assertFalse(Client::isAsin("B0CL61F39H\n")); // trailing newline from fgets(), must not pass
    }
}

./vendor/bin/phpunit --testdox tests/ClientTest.php output (unmodified run)

PHPUnit 11.5.57 by Sebastian Bergmann and contributors.

Runtime:       PHP 8.3.6

Time: 00:00.252, Memory: 10.00 MB

Client (SellerMagnet\Tests\Client)
 ✔ Lookup happy path decimal price
 ✔ Lookup no offer price is null not zero
 ✔ Offers empty buy box becomes null
 ✔ Offers buy box price rounded to cent
 ✔ Statistics minor units japan is whole yen
 ✔ Statistics minor units elsewhere divides by 100
 ✔ Statistics no holder is null not zero
 ✔ 404 is billed once and never retried
 ✔ Free gate 400 is never billed or retried
 ✔ Endpoint own 400 is billed and not retried
 ✔ 429 is free and retried until success
 ✔ 500 with retry after is billed and retried once then succeeds
 ✔ Second 500 stops instead of looping
 ✔ 502 is billed on every attempt then succeeds
 ✔ 503 retries up to attempts then throws
 ✔ Non json body becomes api error not crash
 ✔ Timeout is billed and not retried
 ✔ Connection refused is retried
 ✔ Is asin validates shape not credits

OK (19 tests, 44 assertions)

Never hand-write a fake of get() or getOnce() itself

A fake that reimplements getOnce() or the Retries trait tests the fake's own logic, not the real client. Fake one layer below your code (here, the HTTP server it talks to), so a real bug in the 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, and the Node/Jest guide fakes globalThis.fetch; this guide points Guzzle at a local server because Client.php's own design leaves no lower-level seam to fake in-process. 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 PHPUnit tests 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. A 429, a 500-then-200 or a dropped connection also cannot be forced on demand against the live API, so most of the table above would simply go untested.

Why fake a local server instead of Guzzle's MockHandler?

Client.php keeps its Guzzle instance in a private, readonly property with no constructor option to inject a handler stack, so there is no in-process seam to swap, unlike Go's package-level httpClient.Transport. The constructor's own base-URL parameter is the seam the quickstart's author already built, documented on fromEnv(): "SELLERMAGNET_API_BASE only points the client at a local mock in tests." Pointing it at a tiny php -S process run, get() and getOnce() behind it unmodified.

How do I avoid real retry waits in a PHPUnit test?

Client exposes a public \Closure $sleep precisely so a test can swap it: set it to a no-op (or a closure that just counts calls) before each test, and every real wait in Retries::get() disappears without touching Retries.php itself. The 19-test suite below runs in well under a second because of this, not because the retry logic was skipped.

Why does the timeout test expect a real exception instead of skip the Retries trait?

CURLE_OPERATION_TIMEDOUT is deliberately absent from Retries::NOT_SENT, so a timed-out request (which may still be running server-side and is billed once) is reported at once rather than resent. Using a genuinely slow route with a short client timeout proves that branch for real, the same way the connection-refused test proves the opposite branch (CURLE_COULDNT_CONNECT, which IS in NOT_SENT, is retried because the request never left).

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, and the Node/Jest guide fakes globalThis.fetch. This guide points Guzzle at a local php -S process instead, because Client.php's own design leaves no lower-level seam to fake in-process.

Bottom line: fake the HTTP layer one level below your own code (a local php -S stub here, since Guzzle's client stays private inside Client.php), run the real client against scripted responses for every billed, free and refunded status, and make the stub fail closed so a forgotten scenario cannot send a real, billed request. The whole suite above runs in under a second and spends zero credits.

Ready to Extract Amazon Data at Scale?

Start building with SellerMagnet API today. Real-time product data, competitive pricing, and review analytics at your fingertips.

150 free API credits • No credit card required • Cancel anytime