Mock the SellerMagnet API in Rust tests by pointing reqwest's blocking Client at a real local HTTP server instead of hand-mocking the client: the mockito crate (crates.io) spins one up per test, and Client::new's own base argument, the same seam client.rs's doc comment names for SELLERMAGNET_API_BASE, points at it. The unchanged client.rs, models.rs and retry.rs from the Rust quickstart run against it exactly as shipped, so no credit is spent and no request leaves the machine.
Key Takeaways
- Point
Client::newat a real local mockito server, never a hand-written mock ofget_once(),lookup()orretry::get()themselves. - Swap the public
Client::sleepfield for a function that records the wait in a sharedMutex<Vec<Duration>>, so a 429/500 retry test proves a wait happened without actually blocking. - A 429 is free and retried; a 500 without Retry-After is refunded (one retry, then stop on a second); a 502/503 is billed on every attempt, capped at 4.
- A 404 is a real, billed answer. Retrying it only pays for the same answer twice, so retry.rs never retries it.
- Run with
--test-threads=1: the wait recorder is one static shared by the whole binary, since a plainfn(Duration)pointer cannot capture a per-test variable.
Why not just call the real API in a Rust test suite?
Every SellerMagnet API request is billed per the table below, whether it comes from production code or cargo test. A CI run that fires on every push would spend credits on every build, and a 404, a 429 or a 502 a test wants to force on demand cannot be forced on the live API at all. A real local mock server makes every status code, including the rare ones, reproducible on every run, at zero cost.
| 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 (unsupported marketplace) | free | no | fix the request, no retry |
| 429 concurrency cap | free | yes | wait Retry-After, then retry |
| 500 internal error (no Retry-After) | refunded | yes | retry once, then stop |
| 502 / 503 upstream | billed | yes | retry up to the attempt cap |
How do I point the client at a mock without changing it?
Client::new(base, key, timeout) already takes the API's base URL as a plain string argument, the exact seam Client::from_env's own doc comment names for SELLERMAGNET_API_BASE in tests. A test builds a mockito::Server, scripts one or more routes on it with .mock("GET", path), then calls Client::new(&server.url(), "test-key", Duration::from_secs(5)) directly - no environment variable, no trait, no change to client.rs, models.rs or retry.rs at all.
One real structural step the quickstart's original layout does not need: cargo new builds a binary-only crate (just src/main.rs), and an integration test in tests/ can only import a library crate, never a binary's private modules directly. Add a src/lib.rs with pub mod client; pub mod models; pub mod retry; next to the existing files - main.rs keeps its own mod client; mod models; mod retry; declarations unchanged and still builds as before, and tests/integration.rs reaches the same three files through the new library target with use amazon_rust::client::{Client, Error, is_asin};.

Cargo.toml - mockito is a dev-dependency only, never shipped with the quickstart
[package]
name = "amazon-rust"
version = "0.1.0"
edition = "2024"
[dependencies]
reqwest = { version = "0.13", features = ["blocking", "json", "query"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dev-dependencies]
mockito = "1"

What does a full cargo test scenario suite look like?
Each test builds its own mockito::Server (so scenarios never share a port or a scripted route), calls .sleep = recording_sleep on its Client so the 429/500/502/503 scenarios finish in milliseconds instead of waiting out retry.rs's real exponential backoff, and clears the shared WAITS recorder first. The suite proves the actual billing math by reading client.billed() after each call, the same counter main.rs's own credits charged: line prints in production.
tests/integration.rs - the scenario suite, run for real below
//! Integration tests for the Rust quickstart's own client.rs/models.rs/retry.rs, unmodified,
//! against a real local mock HTTP server (mockito), never a hand-written mock of the client
//! or retry logic. `Client::sleep` is swapped to a function that records the wait instead of
//! std::thread::sleep (client.rs's own doc comment names this as the test seam), so the suite
//! runs in well under a second with no real retry delays. mockito spins up its own listener per
//! `Server::new()`, so scenarios run on different ports and do not collide; the shared `WAITS`
//! recorder is reset at the top of every scenario and the suite is run single-threaded
//! (`cargo test -- --test-threads=1`) so recorded waits are never read mid-write by another test.
use std::sync::Mutex;
use std::time::Duration;
use amazon_rust::client::Client;
use amazon_rust::models::{Offers, Statistics};
use amazon_rust::client::is_asin;
static WAITS: Mutex<Vec<Duration>> = Mutex::new(Vec::new());
fn recording_sleep(d: Duration) {
WAITS.lock().unwrap().push(d);
}
fn reset_waits() {
WAITS.lock().unwrap().clear();
}
fn waits_len() -> usize {
WAITS.lock().unwrap().len()
}
fn new_client(base: &str) -> Client {
let mut c = Client::new(base, "test-key", Duration::from_secs(5)).unwrap();
c.sleep = recording_sleep;
c
}
fn ok_envelope(data: &str) -> String {
format!(r#"{{"success": true, "data": {data}}}"#)
}
fn err_envelope(message: &str) -> String {
format!(r#"{{"success": false, "message": "{message}"}}"#)
}
// --- 1. Happy path: a real buy box price decodes to Some(f64), one credit billed. ---
#[test]
fn lookup_happy_path_decodes_price() {
reset_waits();
let mut server = mockito::Server::new();
let m = server
.mock("GET", "/amazon-product-lookup")
.match_query(mockito::Matcher::Any)
.with_status(200)
.with_body(ok_envelope(
r#"{"productInfo": {"buyBoxInfo": {"price": 444.99, "currencyCode": "USD"}}}"#,
))
.create();
let c = new_client(&server.url());
let product = c.lookup("B0CL61F39H", "ATVPDKIKX0DER").unwrap();
assert_eq!(product.buy_box_info.price, Some(444.99));
assert_eq!(product.buy_box_info.currency_code, "USD");
assert_eq!(c.billed(), 1);
m.assert();
}
// --- 2. "N/A" decodes to None, never 0.0 and never a decode failure. ---
#[test]
fn lookup_na_price_decodes_to_none() {
reset_waits();
let mut server = mockito::Server::new();
server
.mock("GET", "/amazon-product-lookup")
.match_query(mockito::Matcher::Any)
.with_status(200)
.with_body(ok_envelope(
r#"{"productInfo": {"buyBoxInfo": {"price": "N/A", "currencyCode": "USD"}}}"#,
))
.create();
let c = new_client(&server.url());
let product = c.lookup("B0CL61F39H", "ATVPDKIKX0DER").unwrap();
assert_eq!(product.buy_box_info.price, None);
}
// --- 3. An empty buyBox object decodes to a seller_id of "", so featured() returns None. ---
#[test]
fn offers_empty_buy_box_has_no_featured_offer() {
reset_waits();
let mut server = mockito::Server::new();
server
.mock("GET", "/amazon-product-offers")
.match_query(mockito::Matcher::Any)
.with_status(200)
.with_body(ok_envelope(r#"{"buyBox": {}, "currency": {"code": "USD"}, "offers": []}"#))
.create();
let c = new_client(&server.url());
let offers = c.offers("B0CL61F39H", "ATVPDKIKX0DER").unwrap();
assert!(offers.featured().is_none());
}
// --- 4. buyBox.totalPrice is not rounded by the API; the client rounds it once. ---
#[test]
fn offers_buy_box_total_price_rounded_once() {
reset_waits();
let mut server = mockito::Server::new();
server
.mock("GET", "/amazon-product-offers")
.match_query(mockito::Matcher::Any)
.with_status(200)
.with_body(ok_envelope(
r#"{"buyBox": {"sellerId": "A123", "totalPrice": 418.00000000001}, "currency": {"code": "EUR"}, "offers": []}"#,
))
.create();
let c = new_client(&server.url());
let offers: Offers = c.offers("B0CLTBHXWQ", "APJ6JRA9NG5V4").unwrap();
assert_eq!(offers.buy_box.total_price, 418.0);
}
// --- 5. Statistics minor units: everywhere except amazon.co.jp divides by 100. ---
#[test]
fn statistics_minor_units_divides_by_100_outside_japan() {
reset_waits();
let mut server = mockito::Server::new();
server
.mock("GET", "/amazon-product-statistics")
.match_query(mockito::Matcher::Any)
.with_status(200)
.with_body(ok_envelope(r#"{"buyBoxPrice": 41800, "buyBoxFulfillment": "FBM"}"#))
.create();
let c = new_client(&server.url());
let stats: Statistics = c.statistics("B0CLTBHXWQ", "APJ6JRA9NG5V4").unwrap();
let minor = stats.buy_box_price.unwrap();
assert_eq!(minor.to_decimal("APJ6JRA9NG5V4"), 418.00);
}
// --- 6. On amazon.co.jp the same field is whole yen; to_decimal must NOT divide it. ---
#[test]
fn statistics_minor_units_not_divided_on_japan() {
reset_waits();
let mut server = mockito::Server::new();
server
.mock("GET", "/amazon-product-statistics")
.match_query(mockito::Matcher::Any)
.with_status(200)
.with_body(ok_envelope(r#"{"buyBoxPrice": 3980, "buyBoxFulfillment": "FBA"}"#))
.create();
let c = new_client(&server.url());
let stats: Statistics = c.statistics("B0CL61F39H", "A1VC38T7YXB528").unwrap();
let minor = stats.buy_box_price.unwrap();
assert_eq!(minor.to_decimal("A1VC38T7YXB528"), 3980.0);
}
// --- 7. A billed 404 (not on this marketplace) is never retried: exactly one credit, one call. ---
#[test]
fn lookup_404_is_billed_once_and_not_retried() {
reset_waits();
let mut server = mockito::Server::new();
let m = server
.mock("GET", "/amazon-product-lookup")
.match_query(mockito::Matcher::Any)
.with_status(404)
.with_body(err_envelope("Invalid product"))
.expect(1)
.create();
let c = new_client(&server.url());
let err = c.lookup("B0NOTFOUND", "ATVPDKIKX0DER").unwrap_err();
assert!(matches!(err, amazon_rust::client::Error::Api { status: 404, .. }));
assert_eq!(c.billed(), 1);
assert_eq!(waits_len(), 0);
m.assert();
}
// --- 8. A free-gate 400 (unsupported marketplace) is never billed and never retried. ---
#[test]
fn statistics_free_gate_400_is_not_billed() {
reset_waits();
let mut server = mockito::Server::new();
let m = server
.mock("GET", "/amazon-product-statistics")
.match_query(mockito::Matcher::Any)
.with_status(400)
.with_body(err_envelope("Marketplace not supported for statistics"))
.expect(1)
.create();
let c = new_client(&server.url());
let res: Result<Statistics, _> = c.statistics("B0CL61F39H", "A2VIGQ35RCS4UG");
assert!(matches!(res, Err(amazon_rust::client::Error::Api { status: 400, .. })));
assert_eq!(c.billed(), 0);
m.assert();
}
// --- 9. A free 429 is retried honouring Retry-After, then succeeds; only the success is billed. ---
#[test]
fn lookup_429_is_retried_and_only_success_is_billed() {
reset_waits();
let mut server = mockito::Server::new();
let m429 = server
.mock("GET", "/amazon-product-lookup")
.match_query(mockito::Matcher::Any)
.with_status(429)
.with_header("Retry-After", "2")
.with_body(err_envelope("Max 40 concurrent requests per API key. Retry shortly."))
.expect(1)
.create();
let m200 = server
.mock("GET", "/amazon-product-lookup")
.match_query(mockito::Matcher::Any)
.with_status(200)
.with_body(ok_envelope(
r#"{"productInfo": {"buyBoxInfo": {"price": 444.99, "currencyCode": "USD"}}}"#,
))
.create();
let c = new_client(&server.url());
let product = c.lookup("B0CL61F39H", "ATVPDKIKX0DER");
assert!(product.is_ok());
assert_eq!(c.billed(), 1); // only the 200 is billed; the free 429 is not
assert_eq!(waits_len(), 1); // exactly one wait, for the one retried 429
assert!(WAITS.lock().unwrap()[0] >= Duration::from_secs(2)); // honoured Retry-After: 2
m429.assert();
m200.assert();
}
// --- 10. A 500 WITHOUT Retry-After is refunded; one retry costs nothing extra, then succeeds. ---
#[test]
fn statistics_500_without_retry_after_is_refunded_then_succeeds() {
reset_waits();
let mut server = mockito::Server::new();
let m500 = server
.mock("GET", "/amazon-product-statistics")
.match_query(mockito::Matcher::Any)
.with_status(500)
.with_body(err_envelope("An internal error occurred. Please try again shortly."))
.expect(1)
.create();
let m200 = server
.mock("GET", "/amazon-product-statistics")
.match_query(mockito::Matcher::Any)
.with_status(200)
.with_body(ok_envelope(r#"{"buyBoxPrice": 41800, "buyBoxFulfillment": "FBM"}"#))
.create();
let c = new_client(&server.url());
let res: Result<Statistics, _> = c.statistics("B0CLTBHXWQ", "APJ6JRA9NG5V4");
assert!(res.is_ok());
assert_eq!(c.billed(), 1); // only the 200 is billed; the refunded 500 is not counted
m500.assert();
m200.assert();
}
// --- 11. Two 500s IN A ROW (both carrying Retry-After, so both billed) stop after the second; ---
// --- the loop never reaches a third attempt (retry.rs's own "report it, don't loop" rule). ---
#[test]
fn two_consecutive_500s_with_retry_after_stop_without_a_third_attempt() {
reset_waits();
let mut server = mockito::Server::new();
let m = server
.mock("GET", "/amazon-product-lookup")
.match_query(mockito::Matcher::Any)
.with_status(500)
.with_header("Retry-After", "1")
.with_body(err_envelope("An internal error occurred."))
.expect(2)
.create();
let c = new_client(&server.url());
let err = c.lookup("B0CL61F39H", "ATVPDKIKX0DER").unwrap_err();
assert!(matches!(err, amazon_rust::client::Error::Api { status: 500, .. }));
assert_eq!(c.billed(), 2); // both 500s carried Retry-After, so both were billed
m.assert();
}
// --- 12. A 502 is billed on every attempt, capped at the 4-attempt limit. ---
#[test]
fn offers_502_is_billed_every_attempt_capped_at_four() {
reset_waits();
let mut server = mockito::Server::new();
let m = server
.mock("GET", "/amazon-product-offers")
.match_query(mockito::Matcher::Any)
.with_status(502)
.with_body(err_envelope("Bad gateway"))
.expect(4)
.create();
let c = new_client(&server.url());
let err = c.offers("B0CL61F39H", "ATVPDKIKX0DER").unwrap_err();
assert!(matches!(err, amazon_rust::client::Error::Api { status: 502, .. }));
assert_eq!(c.billed(), 4);
m.assert();
}
// --- 13. A 503 is retried to the same 4-attempt cap. ---
#[test]
fn statistics_503_is_capped_at_four_attempts() {
reset_waits();
let mut server = mockito::Server::new();
let m = server
.mock("GET", "/amazon-product-statistics")
.match_query(mockito::Matcher::Any)
.with_status(503)
.with_body(err_envelope("Service unavailable"))
.expect(4)
.create();
let c = new_client(&server.url());
let res: Result<Statistics, _> = c.statistics("B0CLTBHXWQ", "APJ6JRA9NG5V4");
assert!(res.is_err());
assert_eq!(c.billed(), 4);
m.assert();
}
// --- 14. The per-IP limit answers 429 with a non-JSON (HTML) body; it must not crash the ---
// --- decoder, and the default message is used instead of a failed deserialize. ---
#[test]
fn non_json_429_body_does_not_crash_and_is_retried() {
reset_waits();
let mut server = mockito::Server::new();
let m429 = server
.mock("GET", "/amazon-product-lookup")
.match_query(mockito::Matcher::Any)
.with_status(429)
.with_header("content-type", "text/html")
.with_body("<html><body>Too Many Requests</body></html>")
.expect(1)
.create();
let m200 = server
.mock("GET", "/amazon-product-lookup")
.match_query(mockito::Matcher::Any)
.with_status(200)
.with_body(ok_envelope(
r#"{"productInfo": {"buyBoxInfo": {"price": 19.99, "currencyCode": "USD"}}}"#,
))
.create();
let c = new_client(&server.url());
let product = c.lookup("B0CL61F39H", "ATVPDKIKX0DER");
assert!(product.is_ok());
m429.assert();
m200.assert();
}
// --- 15. A malformed ASIN is rejected by is_asin() before any HTTP call: zero credits. ---
#[test]
fn malformed_asin_is_rejected_before_any_call() {
assert!(!is_asin("B0CL61F39")); // 9 characters
assert!(!is_asin("b0cl61f39h")); // lower case
assert!(is_asin("B0CL61F39H"));
}
// --- 16. A connect error (server not reachable at all) never reaches the API, so it is free; ---
// --- it is still retried, since a connection refusal can be transient. ---
#[test]
fn connection_refused_is_free_and_retried() {
reset_waits();
// Port 1 is a privileged port no local test server binds to: the connection is refused.
let c = new_client("http://127.0.0.1:1");
let err = c.lookup("B0CL61F39H", "ATVPDKIKX0DER").unwrap_err();
assert!(matches!(err, amazon_rust::client::Error::Http(_)));
assert_eq!(c.billed(), 0);
}
cargo test -- --test-threads=1 output (unmodified run)
running 16 tests
test connection_refused_is_free_and_retried ... ok
test lookup_404_is_billed_once_and_not_retried ... ok
test lookup_429_is_retried_and_only_success_is_billed ... ok
test lookup_happy_path_decodes_price ... ok
test lookup_na_price_decodes_to_none ... ok
test malformed_asin_is_rejected_before_any_call ... ok
test non_json_429_body_does_not_crash_and_is_retried ... ok
test offers_502_is_billed_every_attempt_capped_at_four ... ok
test offers_buy_box_total_price_rounded_once ... ok
test offers_empty_buy_box_has_no_featured_offer ... ok
test statistics_500_without_retry_after_is_refunded_then_succeeds ... ok
test statistics_503_is_capped_at_four_attempts ... ok
test statistics_free_gate_400_is_not_billed ... ok
test statistics_minor_units_divides_by_100_outside_japan ... ok
test statistics_minor_units_not_divided_on_japan ... ok
test two_consecutive_500s_with_retry_after_stop_without_a_third_attempt ... ok
test result: ok. 16 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.49s
Never hand-write a fake of get() or lookup() itself
A fake that reimplements lookup() or retry::get() tests the fake's own logic, not the real client. Point the real client at a real local server one level below your code instead, 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 or redirect the one call the real code makes to the network, whatever shape that takes in the language. The Python mock-testing guide fakes requests.Session.get, the Go guide fakes http.RoundTripper, and the PHP guide points Guzzle's base URL at a local php -S stub; this guide points reqwest at a real local mockito server, one layer below Client::get_once. The 429/Retry-After guide and the 502/503 retry guide are the production behaviour this suite checks against; keep all of them 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 Rust 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 404 or a 502 a test wants to force on demand cannot be forced on the live API at all. mockito spins up a real local HTTP server per test, so client.rs/models.rs/retry.rs from the quickstart send real HTTP requests that never leave the machine and never spend a credit.
Why point Client::new at a local mockito server instead of mocking reqwest itself?
reqwest's blocking Client has no built-in seam for swapping its transport the way Go's http.RoundTripper does, so hand-mocking it would mean patching private fields or adding a trait indirection the published quickstart does not have. Client::new already takes a base URL as its first argument (SELLERMAGNET_API_BASE is the documented test seam in client.rs's own doc comment), so a real local server is the natural fake: it tests get_once(), get() and the typed lookup()/offers()/statistics() wrappers exactly as shipped.
How do I avoid real waits for a 429 or 500 retry test?
Swap Client::sleep, a public fn(Duration) field client.rs exposes for exactly this, to a function that records the wait in a Mutex<Vec<Duration>> instead of calling std::thread::sleep. The suite can then assert both that a wait happened and roughly how long it asked for, without the test actually blocking.
Why run the suite with --test-threads=1?
Client::sleep is a plain fn(Duration) pointer, not a closure, so it cannot capture a per-test variable; the recorder has to be one static Mutex<Vec<Duration>> shared by the whole test binary. Rust runs tests in parallel threads by default, so two tests asserting on that same static at once would race. Each test clears it first and mockito gives every test its own server on its own port, so correctness only needs --test-threads=1, not a server-level change.
Should a client that forgets to point at the mock still reach the real API?
No single test in this suite does that, since every test builds its own Client::new(&server.url(), ...) explicitly rather than reading SELLERMAGNET_API_BASE from the environment. A suite that does rely on the environment variable should assert it is set before any test runs, the same way a Go or PHP fake panics or 500s on an unrouted path, so a missing mock fails loudly instead of quietly billing a real credit.
Bottom line: point reqwest's blocking Client at a real local mockito server (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 record retry waits instead of letting them actually block. The whole suite above runs in about 2.5 seconds and spends zero credits.