Mock the SellerMagnet API in Go tests by faking only http.RoundTripper, never your own client code: swap httpClient.Transport for a fake that scripts the status code and body each test needs, and run the unchanged get(), Lookup(), GetOffers() and withRetry() from the Go quickstart against it. No credit is spent, no network call leaves the test, and go test -race proves the fake itself is safe for the quickstart's own goroutine worker pool.
Key Takeaways
- Fake
http.RoundTripper, the one interfacehttp.Client.Do()calls through; never fakeget()orLookup()themselves. - Make the fake fail closed: a request before a test installs its scripted route should panic, not silently reach the real API.
- A 429 is free and worth waiting out for real; a 500 is refunded and worth one retry; a 502/503 is billed on every attempt, so cap the attempts.
- This suite does not shrink retry.go's backoff, so the 429/500/502 tests take a few real seconds - proof the actual wait and Retry-After handling work.
- Run with
-race: the worker pool shares one http.Client across goroutines, so the fake's own call log needs a mutex or the race detector fails the suite.
Why not just call the real API in a Go test suite?
Every SellerMagnet API request is billed per the table below, whether it comes from production code or go test. 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 404 or a 429 a test wants to simulate on demand cannot be forced on the live API at all. A fake transport makes every status code - including ones that are rare in practice - reproducible on every run.
| Scenario | Charged | Retry? | Client should |
|---|---|---|---|
| happy path lookup | billed | no | decode, 1 credit |
| 404 product not found | billed | no | record it; do not retry |
| free gate 400 (missing marketplaceId) | free | no | fix the request, no retry |
| 401 insufficient credits | free | no | stop; top up credits |
| 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 |
How do I fake just the transport, not my own code?
Go's http.Client sends every request through its Transport field, an http.RoundTripper. Replace it once with a type whose RoundTrip method returns a scripted *http.Response built from a status, a JSON body and headers, then let get(), Lookup() and withRetry() (all from the Go quickstart) run exactly as they would in production. The fake defaults to a route that panics, so a test that forgets to script a response fails loudly instead of letting a real, billed request through.

fake_transport.go - fakes only http.RoundTripper, fails closed
package main
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/url"
"os"
"sync"
)
// fakeTransport fakes only http.RoundTripper, the one interface httpClient.Do() calls through.
// client.go, get.go, lookup.go, offers.go and retry.go run completely unmodified.
type routeFunc func(endpoint string, params url.Values) (status int, body any, headers http.Header)
type callRecord struct {
Endpoint string
Params url.Values
}
var (
mu sync.Mutex
currentRoute routeFunc
calls []callRecord
)
func blockedRoute(endpoint string, params url.Values) (int, any, http.Header) {
panic("fake_transport: call install(route) first - no request may reach the real API")
}
func init() {
if os.Getenv("SELLERMAGNET_API_KEY") == "" {
os.Setenv("SELLERMAGNET_API_KEY", "test-key")
}
currentRoute = blockedRoute
httpClient.Transport = fakeTransport{}
}
// install scripts the next test's route and resets the call log; always reset back to
// blockedRoute by the caller (via reset()) so a forgotten setup fails loudly, not quietly.
func install(route routeFunc) {
mu.Lock()
defer mu.Unlock()
currentRoute = route
calls = nil
}
func reset() {
mu.Lock()
defer mu.Unlock()
currentRoute = blockedRoute
calls = nil
}
func callCount() int {
mu.Lock()
defer mu.Unlock()
return len(calls)
}
type fakeTransport struct{}
func (fakeTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if req.Header.Get("X-Api-Key") == "" {
panic("fake_transport: X-Api-Key header missing on request")
}
endpoint := req.URL.Path[len("/api/"):]
mu.Lock()
route := currentRoute
calls = append(calls, callRecord{Endpoint: endpoint, Params: req.URL.Query()})
mu.Unlock()
status, body, headers := route(endpoint, req.URL.Query())
var raw []byte
if s, isStr := body.(string); isStr {
raw = []byte(s) // simulates an HTML error page: not valid JSON
} else {
raw, _ = json.Marshal(body)
}
if headers == nil {
headers = http.Header{}
}
return &http.Response{
StatusCode: status,
Body: io.NopCloser(bytes.NewReader(raw)),
Header: headers,
Request: req,
}, nil
}
func ok(data any) (int, any, http.Header) {
return 200, map[string]any{"success": true, "data": data}, nil
}
func fail(status int, message string, headers http.Header) (int, any, http.Header) {
return status, map[string]any{"success": false, "message": message}, headers
}

What does a full go test -race scenario suite look like?
Each test calls install(route) with its own scripted response and defers reset(), so a forgotten setup in the next test cannot inherit a leftover route. The 429, 500 and 502 scenarios run retry.go's real jittered backoff rather than shrinking it, so a pass is proof the actual wait and Retry-After handling work, at the cost of a few real seconds per test. A dedicated goroutine test drives the quickstart's own five-worker pool against the fake to prove the fake's shared call log is race-safe under -race, the same guarantee the quickstart's main.go relies on for its real http.Client.
main_test.go - the scenario suite, run for real below
package main
import (
"context"
"net/http"
"net/url"
"testing"
"time"
)
const (
testASIN = "B0CL61F39H"
testMP = "ATVPDKIKX0DER"
)
func product(price any) map[string]any {
return map[string]any{
"asin": testASIN,
"title": "PlayStation5 console (slim)",
"link": "https://www.amazon.com/dp/" + testASIN,
"buyBoxInfo": map[string]any{
"price": price,
"currencyCode": "USD",
"sellerId": "Amazon",
},
}
}
func TestHTTPClientUses120sTimeout(t *testing.T) {
if httpClient.Timeout != 120*time.Second {
t.Fatalf("httpClient.Timeout = %v, want 120s", httpClient.Timeout)
}
}
func TestHappyPathParsesTheRealResponseShape(t *testing.T) {
defer reset()
install(func(ep string, p url.Values) (int, any, http.Header) {
return ok(map[string]any{"productInfo": product(444.99)})
})
got, err := Lookup(context.Background(), testASIN, testMP)
if err != nil {
t.Fatal(err)
}
if got.ASIN != testASIN || got.BuyBoxInfo.Price.Value == nil || *got.BuyBoxInfo.Price.Value != 444.99 {
t.Fatalf("unexpected product: %+v", got)
}
if callCount() != 1 {
t.Fatalf("calls = %d, want 1", callCount())
}
}
func TestNoFeaturedOfferPriceIsNotANumber(t *testing.T) {
defer reset()
install(func(ep string, p url.Values) (int, any, http.Header) {
return ok(map[string]any{"productInfo": product("N/A")})
})
got, err := Lookup(context.Background(), testASIN, testMP)
if err != nil {
t.Fatal(err)
}
if got.BuyBoxInfo.Price.Value != nil {
t.Fatalf("Price.Value = %v, want nil for \"N/A\"", *got.BuyBoxInfo.Price.Value)
}
}
func Test404IsBilledAndMustNotBeRetried(t *testing.T) {
defer reset()
install(func(ep string, p url.Values) (int, any, http.Header) {
return fail(404, "Product not found.", nil)
})
_, err := Lookup(context.Background(), testASIN, testMP)
var apiErr *APIError
if err == nil {
t.Fatal("want an error")
}
if !errorsAs(err, &apiErr) || apiErr.Status != 404 {
t.Fatalf("err = %v, want *APIError{Status:404}", err)
}
if callCount() != 1 {
t.Fatalf("calls = %d, want 1 (no retry on a billed 404)", callCount())
}
}
func TestFreeGate400MissingMarketplaceID(t *testing.T) {
defer reset()
install(func(ep string, p url.Values) (int, any, http.Header) {
return fail(400, "Missing required parameter(s): marketplaceId", nil)
})
_, err := Lookup(context.Background(), testASIN, "")
var apiErr *APIError
if !errorsAs(err, &apiErr) || apiErr.Status != 400 {
t.Fatalf("err = %v, want *APIError{Status:400}", err)
}
}
func Test401InsufficientCreditsIsNotRetried(t *testing.T) {
defer reset()
install(func(ep string, p url.Values) (int, any, http.Header) {
return fail(401, "Insufficient user credits.", nil)
})
err := withRetry(context.Background(), 4, func(ctx context.Context) error {
_, e := Lookup(ctx, testASIN, testMP)
return e
})
var apiErr *APIError
if !errorsAs(err, &apiErr) || apiErr.Status != 401 {
t.Fatalf("err = %v, want *APIError{Status:401}", err)
}
if callCount() != 1 {
t.Fatalf("calls = %d, want 1 (401 is never retried)", callCount())
}
}
func Test429ConcurrencyCapIsFreeAndRetried(t *testing.T) {
defer reset()
n := 0
install(func(ep string, p url.Values) (int, any, http.Header) {
n++
if n == 1 {
h := http.Header{}
h.Set("Retry-After", "1")
return fail(429, "Max 40 concurrent requests per API key. Retry shortly.", h)
}
return ok(map[string]any{"productInfo": product(444.99)})
})
start := time.Now()
var got *Product
err := withRetry(context.Background(), 4, func(ctx context.Context) error {
p, e := Lookup(ctx, testASIN, testMP)
got = p
return e
})
elapsed := time.Since(start)
if err != nil {
t.Fatal(err)
}
if got.ASIN != testASIN {
t.Fatalf("unexpected product: %+v", got)
}
if callCount() != 2 {
t.Fatalf("calls = %d, want 2 (one retry after the free 429)", callCount())
}
if elapsed < 1*time.Second {
t.Fatalf("elapsed = %v, want >= 1s (must honour Retry-After, not a shorter backoff)", elapsed)
}
}
func Test500IsRefundedAndRetriedExactlyOnce(t *testing.T) {
defer reset()
install(func(ep string, p url.Values) (int, any, http.Header) {
return fail(500, "Internal error.", nil)
})
err := withRetry(context.Background(), 4, func(ctx context.Context) error {
_, e := Lookup(ctx, testASIN, testMP)
return e
})
var apiErr *APIError
if !errorsAs(err, &apiErr) || apiErr.Status != 500 {
t.Fatalf("err = %v, want *APIError{Status:500}", err)
}
if callCount() != 2 {
t.Fatalf("calls = %d, want 2 (exactly one retry after a 500, then stop)", callCount())
}
}
func Test502IsBilledAndRetriedUpToTheAttemptCap(t *testing.T) {
defer reset()
install(func(ep string, p url.Values) (int, any, http.Header) {
return fail(502, "Upstream error.", nil)
})
err := withRetry(context.Background(), 3, func(ctx context.Context) error {
_, e := Lookup(ctx, testASIN, testMP)
return e
})
var apiErr *APIError
if !errorsAs(err, &apiErr) || apiErr.Status != 502 {
t.Fatalf("err = %v, want *APIError{Status:502}", err)
}
if callCount() != 3 {
t.Fatalf("calls = %d, want 3 (502 is billed on every attempt, so the cap must be respected)", callCount())
}
}
func TestOffersBuyBoxTotalPriceIsRoundedAfterDecoding(t *testing.T) {
defer reset()
install(func(ep string, p url.Values) (int, any, http.Header) {
return ok(map[string]any{
"asin": testASIN,
"buyBox": map[string]any{
"sellerId": "A3TM3N0HNB9V0F",
"totalPrice": 419.8299999999999, // float addition drift, not rounded by the API
},
"offers": []any{},
})
})
got, err := GetOffers(context.Background(), testASIN, testMP)
if err != nil {
t.Fatal(err)
}
if got.BuyBox.TotalPrice != 419.83 {
t.Fatalf("BuyBox.TotalPrice = %v, want 419.83 (rounded once after decoding)", got.BuyBox.TotalPrice)
}
}
func TestEmptyBuyBoxDecodesToZeroValueNeverACrash(t *testing.T) {
defer reset()
install(func(ep string, p url.Values) (int, any, http.Header) {
return ok(map[string]any{"asin": testASIN, "buyBox": map[string]any{}, "offers": []any{}})
})
got, err := GetOffers(context.Background(), testASIN, testMP)
if err != nil {
t.Fatal(err)
}
if got.BuyBox.SellerID != "" {
t.Fatalf("BuyBox.SellerID = %q, want empty for a suppressed Buy Box", got.BuyBox.SellerID)
}
}
func TestFakeTransportFailsClosedWithoutInstall(t *testing.T) {
reset() // leaves currentRoute at blockedRoute, no defer-install follows
defer func() {
if r := recover(); r == nil {
t.Fatal("want a panic when no route was installed")
}
}()
_, _ = Lookup(context.Background(), testASIN, testMP)
}
func TestFiveGoroutinesShareOneClientSafely(t *testing.T) {
defer reset()
install(func(ep string, p url.Values) (int, any, http.Header) {
time.Sleep(5 * time.Millisecond) // simulate latency so the workers overlap
return ok(map[string]any{"productInfo": product(444.99)})
})
asins := []string{"B0CL61F39H", "B0CLTBHXWQ", "B0CL61F39H", "B0CLTBHXWQ", "B0CL61F39H"}
results := make(chan []string, len(asins))
for _, a := range asins {
go func(asin string) { results <- lookupRow(asin, testMP) }(a)
}
for range asins {
row := <-results
if row[4] != "" {
t.Fatalf("unexpected row error: %v", row)
}
}
if callCount() != len(asins) {
t.Fatalf("calls = %d, want %d (no batch endpoint, one request per ASIN)", callCount(), len(asins))
}
}
func TestMalformedASINIsSkippedBeforeAnyCallIsBilled(t *testing.T) {
defer reset()
install(func(ep string, p url.Values) (int, any, http.Header) {
t.Fatal("a malformed ASIN must never reach the API")
return 0, nil, nil
})
row := lookupRow("not-an-asin", testMP)
if row[4] == "" || callCount() != 0 {
t.Fatalf("row = %v, calls = %d, want 0 calls and a skip message", row, callCount())
}
}
// errorsAs is errors.As without importing it twice across files; kept local to this test file.
func errorsAs(err error, target **APIError) bool {
apiErr, ok := err.(*APIError)
if ok {
*target = apiErr
}
return ok
}
go test -race -v ./... output (unmodified run)
=== RUN TestHTTPClientUses120sTimeout
--- PASS: TestHTTPClientUses120sTimeout (0.00s)
=== RUN TestHappyPathParsesTheRealResponseShape
--- PASS: TestHappyPathParsesTheRealResponseShape (0.00s)
=== RUN TestNoFeaturedOfferPriceIsNotANumber
--- PASS: TestNoFeaturedOfferPriceIsNotANumber (0.00s)
=== RUN Test404IsBilledAndMustNotBeRetried
--- PASS: Test404IsBilledAndMustNotBeRetried (0.00s)
=== RUN TestFreeGate400MissingMarketplaceID
--- PASS: TestFreeGate400MissingMarketplaceID (0.00s)
=== RUN Test401InsufficientCreditsIsNotRetried
--- PASS: Test401InsufficientCreditsIsNotRetried (0.00s)
=== RUN Test429ConcurrencyCapIsFreeAndRetried
--- PASS: Test429ConcurrencyCapIsFreeAndRetried (2.26s)
=== RUN Test500IsRefundedAndRetriedExactlyOnce
--- PASS: Test500IsRefundedAndRetriedExactlyOnce (2.66s)
=== RUN Test502IsBilledAndRetriedUpToTheAttemptCap
--- PASS: Test502IsBilledAndRetriedUpToTheAttemptCap (7.22s)
=== RUN TestOffersBuyBoxTotalPriceIsRoundedAfterDecoding
--- PASS: TestOffersBuyBoxTotalPriceIsRoundedAfterDecoding (0.00s)
=== RUN TestEmptyBuyBoxDecodesToZeroValueNeverACrash
--- PASS: TestEmptyBuyBoxDecodesToZeroValueNeverACrash (0.00s)
=== RUN TestFakeTransportFailsClosedWithoutInstall
--- PASS: TestFakeTransportFailsClosedWithoutInstall (0.00s)
=== RUN TestFiveGoroutinesShareOneClientSafely
--- PASS: TestFiveGoroutinesShareOneClientSafely (0.01s)
=== RUN TestMalformedASINIsSkippedBeforeAnyCallIsBilled
--- PASS: TestMalformedASINIsSkippedBeforeAnyCallIsBilled (0.00s)
PASS
ok example.com/amazon-go 12.153s
Never hand-write a fake of get() or Lookup() itself
A fake that reimplements Lookup() or withRetry() tests the fake's own logic, not the real client. Fake the transport one level below your code, 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, whatever that call is. The Python mock-testing guide fakes requests.Session.get, and the Node/Jest guide fakes globalThis.fetch; this guide fakes Go's http.RoundTripper, one layer below http.Client.Do. 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 Go 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, and a flaky network turns a code bug into a failed pipeline. Faking only the RoundTripper keeps the real client.go/get.go/lookup.go/offers.go/retry.go under test while the API itself never sees a request.
Why fake http.RoundTripper instead of the get() function?
http.RoundTripper is the one interface http.Client.Do() calls through, so replacing httpClient.Transport leaves get(), Lookup(), GetOffers() and withRetry() completely unmodified. A hand-written fake of get() itself would test the fake's logic, not the client that ships.
How do I avoid real waits for a 429 or 500 retry test?
This suite does not shrink the backoff: retry.go's own jittered exponential wait runs for real, so a passing 429/500/502 test is proof the real wait and the real Retry-After handling work, not just that the code path was reached. Expect those three tests to take a few seconds each.
Does go test -race matter for this fake?
Yes. The worker pool in main.go runs five goroutines against one shared http.Client, so the fake transport's call log needs a mutex or -race fails the suite the moment two goroutines log a call at once - a bug class a single-threaded test run would never catch.
Should the fake allow a request through if a test forgets to call install()?
No. Leave httpClient.Transport defaulting to a RoundTripper that panics, and have every test install its own scripted route and defer a reset. A forgotten install then fails the test loudly with a panic instead of quietly sending a real, billed request.
Bottom line: fake http.RoundTripper (or your language's equivalent one layer below the HTTP call), run the real client code against scripted responses for every billed, free and refunded status, and make the fake fail closed so a forgotten setup cannot send a real, billed request. The whole suite above runs in about 12 seconds - most of it real retry waits it refuses to fake - and spends zero credits.