Mock the SellerMagnet API in R tests by pointing sm_request() at a real local httpuv server instead of the live API: SellerMagnet.R already reads a SELLERMAGNET_API_BASE override for exactly this, the same test seam the quickstart documents. Run the unchanged SellerMagnet.R and Retry.R from the R quickstart against it: no credit is spent, no real request reaches sellermagnet-api.com, and swapping base R's Sys.sleep() to a no-op keeps a 32-scenario suite that exercises real retry logic under a second.
Key Takeaways
- httr::GET has no injectable transport handler the way Go's http.RoundTripper does, so the constructor-style base URL argument (
SELLERMAGNET_API_BASE) already documented in SellerMagnet.R is the only test seam that exists, and it is the one the quickstart's own comment already names. - Swap base R's
Sys.sleepto a no-op in the global environment after sourcing Retry.R, not before: R resolves an unqualified function call through the caller's environment chain at CALL time, not at the time the function was defined, so the swap intercepts every real wait without touching Retry.R itself. - jsonlite's fromJSON() simplifies an empty JSON array to a plain list(), not a zero-row data.frame, so nrow() on it is NULL rather than 0; has_rows() checks is.data.frame() first for exactly this reason, and only a dedicated empty-offers test catches a regression here.
- A 404 and a billed 400 are real answers and must never be retried; a free gate 400, 401, 403 and a malformed ASIN cost nothing and are rejected or stopped before any request leaves the client.
- Fail closed: the stub answers 500 "no route installed" for any path a test forgot to script, so a missing scenario fails loudly instead of quietly returning a plausible empty response.
Why not just call the real API in an R test suite?
Every SellerMagnet API request is billed per the table below, whether it comes from production code or a test runner. A CI job 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 second 500 in a row or a 503 retry cap 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.
| Scenario | Charged | Retry? | Client should |
|---|---|---|---|
| happy path lookup | billed | no | decode, 1 credit |
| lookup, no featured offer ("N/A") | billed | no | price stays the string "N/A", never 0 |
| offers, empty buyBox / offers[] | billed | no | has_rows() check, not a crash |
| offers with real rows | billed | no | totalPrice readable, buyBox decoded |
| statistics minor-unit cents | billed | no | distinct type from lookup's decimal price |
| 404 product not found | billed | no | record it, never retry |
| free gate 400 (uncovered marketplace) | free | no | fix the request, no retry |
| 401 / 403 credits or key | free | no | stop at once |
| 429 concurrency cap | free | yes | wait Retry-After, then retry |
| 500 without Retry-After | refunded | once | retry once, then stop on a 2nd 500 |
| 502 / 503 upstream | billed | yes | retry up to the attempt cap |
| malformed ASIN / trailing newline | n/a | no | skipped before it reaches the fake |
How do I fake just the HTTP layer, not my own R code?
sm_request() reads its base URL from Sys.getenv("SELLERMAGNET_API_BASE", "https://sellermagnet-api.com/api"), so setting that environment variable before sourcing Retry.R points every call lookup(), offers() and statistics() make at a local server instead. A real httpuv server (not a mock object) queues one scripted JSON response per endpoint per test and fails closed: any path with nothing queued answers 500 "no route installed", so a scenario a test forgot to script cannot silently pass.

SellerMagnet.R - the real quickstart client, unchanged
# SellerMagnet.R - a small httr + jsonlite client for the SellerMagnet API.
library(httr)
library(jsonlite)
# ASIN check: base R's default TRE regex engine correctly rejects a trailing
# newline before "$", but perl=TRUE (PCRE) accepts one, the same trap documented
# for Perl/Elixir/PowerShell in this series - verified directly, not assumed.
# Stay on the default (non-PCRE) engine for this exact reason.
is_asin <- function(asin) {
is.character(asin) && length(asin) == 1 && grepl("^[A-Z0-9]{10}$", asin)
}
new_session <- function(api_key = Sys.getenv("SELLERMAGNET_API_KEY")) {
if (nchar(api_key) == 0) stop("SELLERMAGNET_API_KEY is not set")
list(api_key = api_key)
}
# One raw GET, no retry logic here. The key goes in the X-Api-Key header,
# never the query string - a key in a URL ends up in shell history and logs.
sm_request <- function(session, endpoint, params) {
base <- Sys.getenv("SELLERMAGNET_API_BASE", "https://sellermagnet-api.com/api")
httr::GET(paste0(base, "/", endpoint), query = params,
httr::add_headers(`X-Api-Key` = session$api_key),
httr::timeout(120))
}
# jsonlite trap, verified live: an EMPTY JSON array simplifies to a plain
# list(), not a 0-row data.frame, so nrow() on it is NULL, not 0. Every reader
# of a list-typed field (offers, variations, ...) must check is.data.frame()
# before calling nrow() or indexing rows, or a naive loop throws
# "argument must be coercible to non-negative integer" on the no-offers case.
has_rows <- function(x) is.data.frame(x) && nrow(x) > 0
Retry.R - the real quickstart retry policy, unchanged
# Retry.R - billing-aware retry on top of SellerMagnet.R::sm_request.
# Policy (status codes and billing):
# free, retry: 429 (honours Retry-After, up to MAX_ATTEMPTS)
# free, no retry: 401, 403, a gate 400 (missing/invalid marketplaceId)
# refunded, retry once: 500 without Retry-After
# billed, retry cap: 502, 503 (up to MAX_ATTEMPTS, each one billed)
# billed, no retry: 404, an endpoint 400 (e.g. a malformed ASIN on statistics)
source("SellerMagnet.R")
MAX_ATTEMPTS <- 4
# Returns list(status, body, attempts). body is jsonlite::fromJSON() of the
# response text, or NULL for a malformed-ASIN call that was never sent.
get_with_retry <- function(session, endpoint, params, asin_param = "asin") {
if (!is.null(params[[asin_param]]) && !is_asin(params[[asin_param]])) {
return(list(status = NA, body = NULL, attempts = 0, skipped = TRUE))
}
attempt <- 1
while (TRUE) {
resp <- sm_request(session, endpoint, params)
status <- httr::status_code(resp)
if (status %in% c(401, 403)) {
return(list(status = status, body = NULL, attempts = attempt, stop = TRUE))
}
if (status == 429 && attempt < MAX_ATTEMPTS) {
ra <- httr::headers(resp)[["retry-after"]]
Sys.sleep(if (is.null(ra)) 1 else as.numeric(ra))
attempt <- attempt + 1
next
}
if (status == 500 && attempt < 2) {
attempt <- attempt + 1
next
}
if (status %in% c(502, 503) && attempt < MAX_ATTEMPTS) {
ra <- httr::headers(resp)[["retry-after"]]
Sys.sleep(if (is.null(ra)) 1 else as.numeric(ra))
attempt <- attempt + 1
next
}
body <- tryCatch(jsonlite::fromJSON(httr::content(resp, as = "text", encoding = "UTF-8")),
error = function(e) NULL)
return(list(status = status, body = body, attempts = attempt))
}
}
lookup <- function(session, asin, marketplace_id) {
get_with_retry(session, "amazon-product-lookup", list(asin = asin, marketplaceId = marketplace_id))
}
offers <- function(session, asin, marketplace_id) {
get_with_retry(session, "amazon-product-offers", list(asin = asin, marketplaceId = marketplace_id))
}
statistics <- function(session, asin, marketplace_id) {
get_with_retry(session, "amazon-product-statistics", list(asin = asin, marketplaceId = marketplace_id))
}

What does a full R scenario suite look like?
Each scenario resets the fake server's queued responses and call log, queues exactly the responses that scenario needs for one endpoint, then calls lookup(), offers() or statistics() from the real, unmodified Retry.R. The fake server tracks a per-path call count in its own log file, which is how the 404, 429, 500, 502 and 503 scenarios assert the client retried exactly as many times as MAX_ATTEMPTS allows, never more. Overriding base R's Sys.sleep() after sourcing Retry.R but before any call means the swap is in place by call time, intercepting every real wait the 429/500/502/503 scenarios would otherwise sit through.
test_runner.R - the 32-scenario suite, run for real below
# test_runner.R - runs every scenario against the REAL, unmodified
# SellerMagnet.R / Retry.R from the quickstart. Only the HTTP layer is
# faked (a real local httpuv server, fake_server.R, started separately).
# Sys.sleep is swapped to a no-op so the 429/502/503 retry scenarios run
# in well under a second instead of actually sleeping out Retry-After.
setwd("/tmp/sm-apiblog-r")
Sys.setenv(SELLERMAGNET_API_KEY = "test-key")
Sys.setenv(SELLERMAGNET_API_BASE = "http://127.0.0.1:8931/api")
source("fake_helpers.R")
source("Retry.R") # sources SellerMagnet.R itself
# Swapped AFTER sourcing but BEFORE any call: R resolves Sys.sleep at call
# time via the function's enclosing environment (globalenv, since source()
# evaluates there by default), so this recorder intercepts every retry wait.
SLEEP_CALLS <- 0
Sys.sleep <- function(s) { SLEEP_CALLS <<- SLEEP_CALLS + 1; invisible(NULL) }
PASS <- 0
FAIL <- 0
fail_msgs <- c()
check <- function(name, cond) {
if (isTRUE(cond)) {
PASS <<- PASS + 1
cat(sprintf("PASS %s\n", name))
} else {
FAIL <<- FAIL + 1
fail_msgs <<- c(fail_msgs, name)
cat(sprintf("FAIL %s\n", name))
}
}
session <- new_session()
# 1. happy path lookup
fake_reset()
fake_install("amazon-product-lookup", 200,
list(success = TRUE, data = list(asin = "B0CL61F39H",
productInfo = list(buyBoxInfo = list(price = 444.99, currencyCode = "USD")))))
r <- lookup(session, "B0CL61F39H", "ATVPDKIKX0DER")
check("happy path lookup status 200", r$status == 200)
check("happy path lookup price decoded", r$body$data$productInfo$buyBoxInfo$price == 444.99)
check("happy path lookup billed once", fake_call_count("amazon-product-lookup") == 1)
# 2. N/A price stays the string "N/A", never coerced to 0
fake_reset()
fake_install("amazon-product-lookup", 200,
list(success = TRUE, data = list(asin = "B0NOOFFER1",
productInfo = list(buyBoxInfo = list(price = "N/A", currencyCode = "USD")))))
r <- lookup(session, "B0NOOFFER1", "ATVPDKIKX0DER")
check("N/A price stays the string N/A", identical(r$body$data$productInfo$buyBoxInfo$price, "N/A"))
# 3. jsonlite empty-array trap: offers=[] simplifies to list(), not a 0-row
# data.frame, so has_rows() must use is.data.frame() first.
fake_reset()
fake_install("amazon-product-offers", 200,
list(success = TRUE, data = list(asin = "B0EMPTYOFF", buyBox = list(), offers = list())))
r <- offers(session, "B0EMPTYOFF", "ATVPDKIKX0DER")
check("empty offers[] does not crash has_rows()", !has_rows(r$body$data$offers))
check("empty buyBox {} stays empty, not NA", length(r$body$data$buyBox) == 0)
# 4. offers with real rows: has_rows() is TRUE and totalPrice is readable
fake_reset()
fake_install("amazon-product-offers", 200,
list(success = TRUE, data = list(asin = "B0TWOOFFR1",
buyBox = list(sellerId = "A1SELLER", totalPrice = 444.98),
offers = list(list(sellerId = "A1SELLER", totalPrice = 444.98, inventory = 30),
list(sellerId = "A2SELLER", totalPrice = 449.00, inventory = 12)))))
r <- offers(session, "B0TWOOFFR1", "ATVPDKIKX0DER")
check("two offers decode", r$status == 200)
check("buyBox.totalPrice readable", r$body$data$buyBox$totalPrice == 444.98)
# 5. statistics returns integer cents, distinct from lookup's decimal price
fake_reset()
fake_install("amazon-product-statistics", 200,
list(success = TRUE, data = list(asin = "B0CL61F39H", buyBoxPrice = 41800)))
r <- statistics(session, "B0CL61F39H", "ATVPDKIKX0DER")
check("statistics buyBoxPrice is cents (int)", r$body$data$buyBoxPrice == 41800)
# 6. 404 billed, not retried
fake_reset()
fake_install("amazon-product-lookup", 404, list(success = FALSE, error = "not_found"))
r <- lookup(session, "B0UNKNOWN1", "ATVPDKIKX0DER")
check("404 returns status 404", r$status == 404)
check("404 not retried (1 call)", fake_call_count("amazon-product-lookup") == 1)
# 7. free gate 400 (missing/invalid marketplaceId), not retried
fake_reset()
fake_install("amazon-product-statistics", 400, list(success = FALSE, error = "marketplace_not_covered"))
r <- statistics(session, "B0CL61F39H", "A2Q3Y263D00KWC")
check("free gate 400 returns status 400", r$status == 400)
check("free gate 400 not retried (1 call)", fake_call_count("amazon-product-statistics") == 1)
# 8. 401 stops at once, no retry
fake_reset()
fake_install("amazon-product-lookup", 401, list(success = FALSE, error = "insufficient_credits"))
r <- lookup(session, "B0CL61F39H", "ATVPDKIKX0DER")
check("401 sets stop", isTRUE(r$stop))
check("401 not retried (1 call)", fake_call_count("amazon-product-lookup") == 1)
# 9. 403 stops at once too
fake_reset()
fake_install("amazon-product-lookup", 403, list(success = FALSE, error = "forbidden"))
r <- lookup(session, "B0CL61F39H", "ATVPDKIKX0DER")
check("403 sets stop", isTRUE(r$stop))
# 10. 429 honours Retry-After then succeeds (free, retried)
fake_reset()
fake_install("amazon-product-lookup", 429, NULL, headers = list("Retry-After" = "2"))
fake_install("amazon-product-lookup", 200,
list(success = TRUE, data = list(asin = "B0CL61F39H",
productInfo = list(buyBoxInfo = list(price = 19.99, currencyCode = "USD")))))
r <- lookup(session, "B0CL61F39H", "ATVPDKIKX0DER")
check("429-then-200 succeeds", r$status == 200 && r$attempts == 2)
check("429 retry was not billed beyond the final answer (2 calls total)",
fake_call_count("amazon-product-lookup") == 2)
# 11. 500 refunded, retried exactly once, then succeeds
fake_reset()
fake_install("amazon-product-lookup", 500, NULL)
fake_install("amazon-product-lookup", 200,
list(success = TRUE, data = list(asin = "B0CL61F39H",
productInfo = list(buyBoxInfo = list(price = 29.99, currencyCode = "USD")))))
r <- lookup(session, "B0CL61F39H", "ATVPDKIKX0DER")
check("500-then-200 succeeds in 2 attempts", r$status == 200 && r$attempts == 2)
# 12. two consecutive 500s: refund-retry-once means the SECOND 500 is
# returned as-is, not retried a third time (no infinite loop on a down API)
fake_reset()
fake_install("amazon-product-lookup", 500, NULL)
fake_install("amazon-product-lookup", 500, NULL)
r <- lookup(session, "B0CL61F39H", "ATVPDKIKX0DER")
check("second consecutive 500 stops instead of looping", r$status == 500 && r$attempts == 2)
check("500-500 makes exactly 2 calls, never a 3rd", fake_call_count("amazon-product-lookup") == 2)
# 13. 502 billed on every attempt, capped at MAX_ATTEMPTS
fake_reset()
fake_install("amazon-product-lookup", 502, NULL)
fake_install("amazon-product-lookup", 502, NULL)
fake_install("amazon-product-lookup", 200,
list(success = TRUE, data = list(asin = "B0CL61F39H",
productInfo = list(buyBoxInfo = list(price = 39.99, currencyCode = "USD")))))
r <- lookup(session, "B0CL61F39H", "ATVPDKIKX0DER")
check("502-502-then-200 succeeds in 3 attempts", r$status == 200 && r$attempts == 3)
# 14. 503 capped at MAX_ATTEMPTS (4), never a 5th attempt
fake_reset()
for (i in 1:4) fake_install("amazon-product-lookup", 503, NULL)
r <- lookup(session, "B0CL61F39H", "ATVPDKIKX0DER")
check("503 stays 503 after the attempt cap", r$status == 503)
check("503 capped at 4 calls, never a 5th", fake_call_count("amazon-product-lookup") == 4)
# 15. malformed ASIN: skipped before any request leaves the client (0 credits)
fake_reset()
r <- lookup(session, "4006380000000", "ATVPDKIKX0DER") # EAN barcode, not a 10-char ASIN
check("malformed ASIN is skipped, 0 calls made", isTRUE(r$skipped) && fake_call_count("amazon-product-lookup") == 0)
# 16. trailing newline on an ASIN is rejected by the default (non-PCRE) regex
# engine - the exact trap this client's comment documents.
fake_reset()
r <- lookup(session, "B0CL61F39H\n", "ATVPDKIKX0DER")
check("ASIN with a trailing newline is rejected (non-PCRE engine)", isTRUE(r$skipped))
# 17. non-JSON / malformed response body does not crash the client
fake_reset()
fake_install("amazon-product-lookup", 200, NULL) # empty body, not valid JSON
r <- lookup(session, "B0CL61F39H", "ATVPDKIKX0DER")
check("malformed body decodes to NULL, no crash", r$status == 200 && is.null(r$body))
# 18. a small batch (main.R pattern): one good, one 404, one malformed
fake_reset()
fake_install("amazon-product-lookup", 200,
list(success = TRUE, data = list(asin = "B0CL61F39H",
productInfo = list(buyBoxInfo = list(price = 444.99, currencyCode = "USD")))))
fake_install("amazon-product-lookup", 404, list(success = FALSE, error = "not_found"))
rows <- list()
for (asin in c("B0CL61F39H", "B0UNKNOWN2", "4006380000000")) {
if (!is_asin(asin)) { rows[[asin]] <- "skipped"; next }
rr <- lookup(session, asin, "ATVPDKIKX0DER")
rows[[asin]] <- rr$status
}
check("batch: good ASIN billed and decoded", rows[["B0CL61F39H"]] == 200)
check("batch: 404 ASIN billed once, recorded", rows[["B0UNKNOWN2"]] == 404)
check("batch: malformed ASIN skipped, 0 credits", rows[["4006380000000"]] == "skipped")
check("batch billed exactly 2 of 3 (malformed one is free)", fake_call_count("amazon-product-lookup") == 2)
# 19. retries never actually sleep in this suite (confirms the no-op swap
# intercepted every Sys.sleep call made above, not just asserted it would)
check("Sys.sleep was intercepted at least once (429/500/502/503 scenarios)", SLEEP_CALLS > 0)
cat(sprintf("\n%d passed, %d failed\n", PASS, FAIL))
if (FAIL > 0) {
cat("FAILED:", paste(fail_msgs, collapse = ", "), "\n")
quit(status = 1)
}
quit(status = 0)
Rscript test_runner.R output (unmodified run)
PASS happy path lookup status 200
PASS happy path lookup price decoded
PASS happy path lookup billed once
PASS N/A price stays the string N/A
PASS empty offers[] does not crash has_rows()
PASS empty buyBox {} stays empty, not NA
PASS two offers decode
PASS buyBox.totalPrice readable
PASS statistics buyBoxPrice is cents (int)
PASS 404 returns status 404
PASS 404 not retried (1 call)
PASS free gate 400 returns status 400
PASS free gate 400 not retried (1 call)
PASS 401 sets stop
PASS 401 not retried (1 call)
PASS 403 sets stop
PASS 429-then-200 succeeds
PASS 429 retry was not billed beyond the final answer (2 calls total)
PASS 500-then-200 succeeds in 2 attempts
PASS second consecutive 500 stops instead of looping
PASS 500-500 makes exactly 2 calls, never a 3rd
PASS 502-502-then-200 succeeds in 3 attempts
PASS 503 stays 503 after the attempt cap
PASS 503 capped at 4 calls, never a 5th
PASS malformed ASIN is skipped, 0 calls made
PASS ASIN with a trailing newline is rejected (non-PCRE engine)
PASS malformed body decodes to NULL, no crash
PASS batch: good ASIN billed and decoded
PASS batch: 404 ASIN billed once, recorded
PASS batch: malformed ASIN skipped, 0 credits
PASS batch billed exactly 2 of 3 (malformed one is free)
PASS Sys.sleep was intercepted at least once (429/500/502/503 scenarios)
32 passed, 0 failed
Never hand-write a fake of lookup() or get_with_retry() itself
A fake that reimplements get_with_retry() or the retry policy tests the fake's own logic, not the real client. Fake one layer below your code (here, the HTTP server it talks to over httr::GET), 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 Go guide fakes http.RoundTripper, the PHP guide points Guzzle at a local php -S stub, and the Rust guide points reqwest's blocking client at a local mockito server; this guide points httr at a real local httpuv server because httr::GET itself has 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 R 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 second 500 in a row or a 503 retry cap 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 a package like webmockr?
httr::GET has no injectable transport the way Go's http.RoundTripper or a mocking package can swap; the R quickstart's own sm_request() already reads SELLERMAGNET_API_BASE as an override, documented for exactly this purpose. Starting a real local httpuv server and pointing that environment variable at it runs SellerMagnet.R and Retry.R completely unmodified against a real socket, not a package-specific mock object.
How do I avoid real retry waits in an R test?
Retry.R calls the base Sys.sleep() function, which R resolves through the calling environment chain at call time, not at the time Retry.R was written. Defining a Sys.sleep <- function(s) invisible(NULL) in the test's global environment after sourcing Retry.R intercepts every real wait without touching Retry.R itself, so a 429/500/502/503 suite that would otherwise sleep several seconds runs in well under one.
Why does an empty offers[] need its own test?
jsonlite's fromJSON() simplifies an empty JSON array to a plain list(), not a zero-row data.frame, so nrow() on it is NULL rather than 0. A naive if (nrow(offers) > 0) throws "argument must be coercible to non-negative integer" the first time a product genuinely has no offers; has_rows() in SellerMagnet.R checks is.data.frame() first for exactly this reason, and this is the one scenario a happy-path-only test would never catch.
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 Go guide fakes http.RoundTripper, the PHP guide points Guzzle at a local php -S stub, and the Rust guide points reqwest's blocking client at a local mockito server. This guide does the same with a real local httpuv server, because httr::GET has no lower-level transport seam to fake in-process.
Bottom line: fake the HTTP layer one level below your own code (a real local httpuv server here, since httr::GET has no in-process transport to swap), 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 well under a second and spends zero credits.