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

Mock the SellerMagnet API in Swift Tests Without Spending Credits

Test the URLSession client that calls the SellerMagnet API from Swift without hitting it: Client's own base-URL and sleeper constructor parameters already exist for exactly this, point them at a real local POSIX-socket HTTP server, run the real Client.swift / Models.swift from the quickstart unchanged, and cover every billed, free and refunded status code with a 45-scenario suite that runs in well under a second.

November 18, 2026
7 min read
SellerMagnet Team
Share & Bookmark
Terminal window showing a Swift test run that fakes the SellerMagnet API behind a local POSIX-socket server while the real URLSession client code runs unchanged

Mock the SellerMagnet API in Swift tests by pointing Client's own base constructor parameter at a real local HTTP server instead of the live API, and its sleeper parameter at a no-op closure instead of Thread.sleep: both already exist in the published Swift quickstart for exactly this. Run the unchanged Client.swift and Models.swift against a local POSIX-socket listener: no credit is spent, no real request reaches sellermagnet-api.com, and the injected sleeper keeps a 45-scenario suite that exercises real retry logic under a second.

Key Takeaways

  • Client.swift already takes base and sleeper as constructor parameters, defaulting to the live API and Thread.sleep respectively; a test only has to pass different values, never touch Client.swift itself.
  • Client builds its own URLSession internally with no injectable URLProtocol, so the base URL is the only network seam that exists; faking it means standing up a real local listener, not a mock object.
  • A 500 WITHOUT a Retry-After header is refunded and retried once; the SAME status WITH a Retry-After header is billed on every attempt and capped at 4, because Client's switch statement matches the where retryAfter == 0 guard first.
  • billedCalls never resets for the lifetime of one Client; a test that reuses one client across scenarios must read billed() before and after each scenario and assert the delta, not the absolute value.
  • Fail closed: the local server answers 500 "no route installed" for any endpoint 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 a Swift 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, a 500 that carries a Retry-After header, or a 503 retry cap cannot be forced on demand against the live API at all. A local server makes every status code in the table, including the rare ones, reproducible on every run.

Scenarios worth testing, and what the server needs to script for each.
ScenarioChargedRetry?Client should
happy path lookupbillednodecode, 1 credit
lookup, no featured offer ("N/A")billednoprice decodes to nil, never 0.0
offers, empty buyBox / offers[]billednobuyBox nil, offers [], cheapestNew() nil
statistics, JP minor unitsbillednowhole yen (divide by 1), cents elsewhere
404 product not foundbillednorecord it, never retry
free gate 400 (uncovered marketplace)freenofix the request, no retry
401 / 403 credits or keyfreenostop at once
429 concurrency capfreeyeswait Retry-After, then retry
500 without Retry-Afterrefundedonceretry once, then stop on a 2nd 500
500 WITH Retry-After / 502 / 503billedyesretry up to the attempt cap
malformed ASIN / trailing newlinen/anorejected by \A...\z before any call
200 with a non-JSON bodybillednoApiError, not a crash
connection refusedn/anoApiError.transport, not an HTTP status

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

Client.init() reads its base URL from ProcessInfo.processInfo.environment["SELLERMAGNET_API_BASE"] by default, but also accepts base and sleeper directly as constructor parameters, so a test constructs its own Client(key:base:sleeper:) pointed at a local server with a no-op sleeper, no environment variable needed. A real local HTTP/1.1 listener over a raw POSIX socket (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.

Blueprint sequence diagram of a Swift test pointing Client at a local POSIX-socket server while the real client code runs unchanged
Only the base URL and sleeper are swapped; Client.swift and Models.swift run unmodified.

Client.swift - the real quickstart client, unchanged

#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
import Foundation

/// The API answered with an error status; message is the API's own text, retryAfter in seconds.
enum ApiError: Error, CustomStringConvertible {
    case api(status: Int, message: String, retryAfter: Int)
    case shape(String)
    case transport(String)

    var description: String {
        switch self {
        case .api(let status, let message, _): return "\(status): \(message)"
        case .shape(let m): return m
        case .transport(let m): return m
        }
    }
}

/// Gate 400s (checked BEFORE billing) are free; every other 400 is charged.
private let FREE_400_PHRASES = ["Missing required parameter", "Invalid marketplaceId",
                                 "This endpoint is not available"]
private func isFreeGate400(_ message: String) -> Bool {
    FREE_400_PHRASES.contains { message.contains($0) }
}

/// One client, reused for every call. Auth is the X-Api-Key header (never api_key in the query
/// string: the query parameter wins when both are sent, and a key in the URL lands in server logs -
/// see the header-vs-query-string guide). sleeper is injectable so tests never really wait.
final class Client {
    private let key: String
    private let base: String
    private let sleeper: (Double) -> Void
    private let session: URLSession
    private var billedCalls = 0

    init(key: String,
         base: String = ProcessInfo.processInfo.environment["SELLERMAGNET_API_BASE"]
             ?? "https://sellermagnet-api.com/api",
         sleeper: @escaping (Double) -> Void = { Thread.sleep(forTimeInterval: $0) }) {
        self.key = key
        self.base = base
        self.sleeper = sleeper
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 120   // URLSession's own default is 60 s; the API can take longer
        self.session = URLSession(configuration: config)
    }

    static func fromEnv() -> Client {
        guard let key = ProcessInfo.processInfo.environment["SELLERMAGNET_API_KEY"], !key.isEmpty else {
            fatalError("set SELLERMAGNET_API_KEY")
        }
        return Client(key: key)
    }

    func billed() -> Int { billedCalls }

    /// `\A...\z` anchors the whole string, unlike `^...$`, which still matches before a trailing
    /// newline: a value read with a trailing "\n" from a CSV/file would otherwise pass as an ASIN.
    static func isAsin(_ s: String) -> Bool {
        s.range(of: "\\A[A-Z0-9]{10}\\z", options: .regularExpression) != nil
    }

    /// One HTTP GET. Throws ApiError.api for a non-2xx status or success:false, ApiError.transport
    /// for a connection error or timeout (these are never retried below: the request may still be
    /// running on the server, and it is already billed).
    private func getOnce(_ endpoint: String, _ params: [String: String]) throws -> [String: Any] {
        var comps = URLComponents(string: "\(base)/\(endpoint)")!
        comps.queryItems = params.map { URLQueryItem(name: $0.key, value: $0.value) }
        var req = URLRequest(url: comps.url!)
        req.httpMethod = "GET"
        req.setValue(key, forHTTPHeaderField: "X-Api-Key")

        let sem = DispatchSemaphore(value: 0)
        var resultData: Data?
        var resultResp: HTTPURLResponse?
        var resultErr: Error?
        let task = session.dataTask(with: req) { data, resp, err in
            resultData = data; resultResp = resp as? HTTPURLResponse; resultErr = err
            sem.signal()
        }
        task.resume()
        sem.wait()

        if let e = resultErr { throw ApiError.transport("\(e)") }
        guard let resp = resultResp, let data = resultData else { throw ApiError.transport("no response") }
        let retryAfter = Int(resp.value(forHTTPHeaderField: "Retry-After") ?? "") ?? 0
        let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
        if resp.statusCode != 200 || (json?["success"] as? Bool) != true {
            // A non-2xx body is not always JSON (e.g. a plain HTML 429 page from a proxy in
            // front of the API): fall back to a generic message instead of failing to parse.
            let message = json?["message"] as? String ?? "HTTP \(resp.statusCode)"
            throw ApiError.api(status: resp.statusCode, message: message, retryAfter: retryAfter)
        }
        guard let data = json?["data"] as? [String: Any] else { throw ApiError.shape("no data field") }
        return data
    }

    /// Retry only what a second attempt can fix: 429 (free), a 500 without Retry-After (refunded,
    /// once), a 500 WITH Retry-After / 502 / 503 (billed, capped at 4 attempts total). A 404 or an
    /// endpoint 400 is a final, billed answer: retrying it pays again for the same result.
    func getWithRetry(_ endpoint: String, _ params: [String: String], maxAttempts: Int = 4) throws -> [String: Any] {
        var attempt = 0
        var refundedRetryUsed = false
        while true {
            attempt += 1
            do {
                let data = try getOnce(endpoint, params)
                billedCalls += 1
                return data
            } catch ApiError.api(let status, let message, let retryAfter) {
                let free = status == 429 || status == 401 || status == 403 || (status == 400 && isFreeGate400(message))
                let refunded = status == 500 && retryAfter == 0
                if !free && !refunded { billedCalls += 1 }

                switch status {
                case 429:
                    if attempt < maxAttempts {
                        let wait = Double(max(retryAfter, 1))
                        FileHandle.standardError.write("\(endpoint): \(status): \(message) (retry \(attempt)/\(maxAttempts - 1) in \(wait)s)\n".data(using: .utf8)!)
                        sleeper(wait); continue
                    }
                case 500 where retryAfter == 0:
                    if !refundedRetryUsed && attempt < maxAttempts {
                        refundedRetryUsed = true
                        FileHandle.standardError.write("\(endpoint): \(status): \(message) (retry \(attempt)/\(maxAttempts - 1) in 0.0s, refunded)\n".data(using: .utf8)!)
                        sleeper(0)   // refunded, so one immediate retry costs nothing
                        continue
                    }
                case 500, 502, 503:
                    if attempt < maxAttempts {
                        let wait = Double(max(retryAfter, 2))
                        FileHandle.standardError.write("\(endpoint): \(status): \(message) (retry \(attempt)/\(maxAttempts - 1) in \(wait)s)\n".data(using: .utf8)!)
                        sleeper(wait); continue
                    }
                default:
                    break   // 404, endpoint 400, 401, 403: final, never retried
                }
                throw ApiError.api(status: status, message: message, retryAfter: retryAfter)
            }
        }
    }

    func lookup(_ asin: String, _ marketplaceId: String) throws -> Product {
        try Product.fromLookup(try getWithRetry("amazon-product-lookup", ["asin": asin, "marketplaceId": marketplaceId]))
    }

    func offers(_ asin: String, _ marketplaceId: String) throws -> Offers {
        Offers.from(try getWithRetry("amazon-product-offers", ["asin": asin, "marketplaceId": marketplaceId]))
    }

    func statistics(_ asin: String, _ marketplaceId: String) throws -> Statistics {
        Statistics.from(try getWithRetry("amazon-product-statistics", ["asin": asin, "marketplaceId": marketplaceId]))
    }
}
Blueprint table of Swift test scenarios against the SellerMagnet API's status codes, billing and the correct URLSession client reaction
Each row needs its own scripted response; a happy-path test alone misses most of this.

What does a full Swift 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 Client.swift. 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 maxAttempts allows, never more. Constructing Client with a no-op sleeper closure means the 429/500/502/503 scenarios that would otherwise sit through several seconds of real backoff complete immediately, without touching Client.swift's own retry logic at all.

fake_server.swift - the local HTTP/1.1 listener

// fake_server.swift - minimal real HTTP/1.1 listener over a raw POSIX socket
// (no extra package, matching the quickstart's own "URLSession and Foundation
// only" pitch). Routes are scripted by the test driver as one JSON file per
// queued response under routes/<endpoint>/NNNNNN.json; each file is written
// once and read once (never round-tripped), consumed lowest-number-first.
// Fails closed: an endpoint with nothing queued answers 500 "no route
// installed" so a forgotten script() call cannot fall through to a real
// request.
import Foundation
#if canImport(Glibc)
import Glibc
#endif

let routesDir = "/tmp/sm-apiblog-swift/routes"
let callsFile = "/tmp/sm-apiblog-swift/calls.log"
let port: UInt16 = 8941

func recvLine(_ fd: Int32) -> String {
    var line = [UInt8]()
    var byte: UInt8 = 0
    while true {
        let n = read(fd, &byte, 1)
        if n <= 0 { break }
        if byte == 0x0A { break }
        if byte != 0x0D { line.append(byte) }
    }
    return String(decoding: line, as: UTF8.self)
}

func sendAll(_ fd: Int32, _ data: [UInt8]) {
    var off = 0
    data.withUnsafeBufferPointer { buf in
        while off < data.count {
            let n = write(fd, buf.baseAddress!.advanced(by: off), data.count - off)
            if n <= 0 { break }
            off += n
        }
    }
}

func pathFor(_ endpoint: String) -> String {
    let safe = endpoint.replacingOccurrences(of: "/", with: "_")
    return "\(routesDir)/\(safe)"
}

func logCall(_ line: String) {
    let fm = FileManager.default
    if !fm.fileExists(atPath: callsFile) { _ = fm.createFile(atPath: callsFile, contents: nil) }
    if let h = FileHandle(forWritingAtPath: callsFile) {
        h.seekToEndOfFile()
        h.write((line + "\n").data(using: .utf8)!)
        h.closeFile()
    }
}

func popRoute(_ endpoint: String) -> (Int, [String: String], String)? {
    let dir = pathFor(endpoint)
    let fm = FileManager.default
    guard let files = try? fm.contentsOfDirectory(atPath: dir).sorted(), let first = files.first else {
        return nil
    }
    let full = "\(dir)/\(first)"
    guard let data = fm.contents(atPath: full),
          let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
        try? fm.removeItem(atPath: full)
        return nil
    }
    try? fm.removeItem(atPath: full)
    let status = (obj["status"] as? Int) ?? 500
    let body = (obj["body"] as? String) ?? ""
    var headers: [String: String] = [:]
    if let h = obj["headers"] as? [String: Any] {
        for (k, v) in h { headers[k] = "\(v)" }
    }
    return (status, headers, body)
}

func httpReasonPhrase(_ code: Int) -> String {
    switch code {
    case 200: return "OK"
    case 400: return "Bad Request"
    case 401: return "Unauthorized"
    case 403: return "Forbidden"
    case 404: return "Not Found"
    case 429: return "Too Many Requests"
    case 500: return "Internal Server Error"
    case 502: return "Bad Gateway"
    case 503: return "Service Unavailable"
    default: return "Status"
    }
}

let serverFd = socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0)
var opt: Int32 = 1
setsockopt(serverFd, SOL_SOCKET, SO_REUSEADDR, &opt, socklen_t(MemoryLayout<Int32>.size))

var addr = sockaddr_in()
addr.sin_family = sa_family_t(AF_INET)
addr.sin_port = port.bigEndian
addr.sin_addr.s_addr = INADDR_ANY

let bindResult = withUnsafePointer(to: &addr) { ptr -> Int32 in
    ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sptr in
        bind(serverFd, sptr, socklen_t(MemoryLayout<sockaddr_in>.size))
    }
}
if bindResult != 0 { FileHandle.standardError.write("bind failed\n".data(using: .utf8)!); exit(1) }
listen(serverFd, 32)
print("LISTENING \(port)")
fflush(stdout)

while true {
    let clientFd = accept(serverFd, nil, nil)
    if clientFd < 0 { continue }

    let requestLine = recvLine(clientFd)
    // GET /api/amazon-product-lookup?asin=XXXX HTTP/1.1
    let parts = requestLine.split(separator: " ")
    var rawPath = parts.count > 1 ? String(parts[1]) : "/"
    // drain remaining headers up to the blank line (GET has no body to read)
    while true {
        let h = recvLine(clientFd)
        if h.isEmpty { break }
    }

    if rawPath.hasPrefix("/") { rawPath.removeFirst() }
    let pathOnly = rawPath.split(separator: "?", maxSplits: 1)[0]
    var endpoint = String(pathOnly)
    if endpoint.hasPrefix("api/") { endpoint.removeFirst(4) }

    logCall("api/\(endpoint)?\(rawPath.contains("?") ? String(rawPath.split(separator: "?", maxSplits: 1)[1]) : "")")

    let status: Int
    var headers: [String: String]
    let body: String
    if let (s, h, b) = popRoute(endpoint) {
        status = s; headers = h; body = b
    } else {
        status = 500; headers = [:]
        body = "{\"success\":false,\"message\":\"fake_server: no route installed\"}"
    }
    headers["Content-Type"] = "application/json"
    let bodyBytes = Array(body.utf8)
    headers["Content-Length"] = "\(bodyBytes.count)"

    var head = "HTTP/1.1 \(status) \(httpReasonPhrase(status))\r\n"
    for (k, v) in headers { head += "\(k): \(v)\r\n" }
    head += "\r\n"

    sendAll(clientFd, Array(head.utf8))
    sendAll(clientFd, bodyBytes)
    close(clientFd)
}

main.swift - the 45-scenario suite, run for real below

// test_runner.swift - runs every scenario against the REAL, unmodified
// Client.swift / Models.swift from the published quickstart. Only the base
// URL and the sleeper closure are swapped (both are constructor parameters
// Client already exposes for exactly this), so the retry logic, decoding
// and billing counter all run as shipped, over a real local socket server
// (fake_server.swift), not a hand-written mock of Client itself.
import Foundation

var pass = 0
var fail = 0
var failed: [String] = []

func check(_ name: String, _ cond: Bool) {
    if cond { pass += 1; print("PASS  \(name)") }
    else { fail += 1; failed.append(name); print("FAIL  \(name)") }
}

// No real wait: Client's sleeper parameter is injectable for exactly this.
let client = Client(key: "test-key", base: "http://127.0.0.1:8941/api", sleeper: { _ in })

// 1. happy path lookup
fakeReset()
fakeInstall("amazon-product-lookup", status: 200,
            body: "{\"success\":true,\"data\":{\"productInfo\":{\"asin\":\"B0CL61F39H\",\"buyBoxInfo\":{\"price\":444.99,\"currencyCode\":\"USD\"}}}}")
do {
    let p = try client.lookup("B0CL61F39H", "ATVPDKIKX0DER")
    check("happy path lookup price", p.buyBoxPrice == 444.99)
    check("happy path lookup billed once", fakeCallCount("amazon-product-lookup") == 1)
} catch { check("happy path lookup threw unexpectedly: \(error)", false) }

// 2. N/A price stays nil, never 0.0
fakeReset()
fakeInstall("amazon-product-lookup", status: 200,
            body: "{\"success\":true,\"data\":{\"productInfo\":{\"asin\":\"B0NOOFFER1\",\"buyBoxInfo\":{\"price\":\"N/A\",\"currencyCode\":\"USD\"}}}}")
do {
    let p = try client.lookup("B0NOOFFER1", "ATVPDKIKX0DER")
    check("N/A price decodes to nil, not 0.0", p.buyBoxPrice == nil)
} catch { check("N/A price case threw unexpectedly", false) }

// 3. empty buyBox {} -> nil, not a crash; empty offers[] -> []
fakeReset()
fakeInstall("amazon-product-offers", status: 200,
            body: "{\"success\":true,\"data\":{\"currency\":{\"code\":\"USD\"},\"buyBox\":{},\"offers\":[]}}")
do {
    let o = try client.offers("B0EMPTYOFF", "ATVPDKIKX0DER")
    check("empty buyBox {} decodes to nil", o.buyBox == nil)
    check("empty offers[] decodes to an empty array, not a crash", o.offers.isEmpty)
    check("cheapestNew() on no offers returns nil", o.cheapestNew() == nil)
} catch { check("empty offers case threw unexpectedly", false) }

// 4. offers with real rows; cheapestNew() skips a 0.0 itemPrice row
fakeReset()
fakeInstall("amazon-product-offers", status: 200,
            body: "{\"success\":true,\"data\":{\"currency\":{\"code\":\"USD\"}," +
                  "\"buyBox\":{\"sellerId\":\"A1\",\"fulfillmentType\":\"FBA\",\"priceWithoutShipping\":444.99,\"totalPrice\":444.99}," +
                  "\"offers\":[{\"sellerId\":\"A1\",\"fulfillmentType\":\"FBA\",\"priceWithoutShipping\":444.99,\"totalPrice\":444.99}," +
                  "{\"sellerId\":\"A2\",\"fulfillmentType\":\"FBM\",\"priceWithoutShipping\":0,\"totalPrice\":418.00}]}}")
do {
    let o = try client.offers("B0TWOOFFERS", "ATVPDKIKX0DER")
    check("two offers decode", o.offers.count == 2)
    check("buyBox totalPrice readable", o.buyBox?.totalPrice == 444.99)
    check("cheapestNew() skips the 0.0-itemPrice offer", o.cheapestNew()?.sellerId == "A1")
} catch { check("two offers case threw unexpectedly", false) }

// 5. statistics MinorUnits: JP divides by 1.0 (whole yen), elsewhere by 100.0
fakeReset()
fakeInstall("amazon-product-statistics", status: 200,
            body: "{\"success\":true,\"data\":{\"buyBoxPrice\":41800,\"buyBoxFulfillment\":\"FBA\"}}")
do {
    let s = try client.statistics("B0CL61F39H", "ATVPDKIKX0DER")
    check("statistics minor units is 41800", s.buyBoxPrice?.value == 41800)
    check("non-JP marketplace divides cents by 100", s.buyBoxPrice?.toDecimal(marketplaceId: "ATVPDKIKX0DER") == 418.00)
    check("JP marketplace divides by 1 (whole yen)", s.buyBoxPrice?.toDecimal(marketplaceId: "A1VC38T7YXB528") == 41800.0)
} catch { check("statistics case threw unexpectedly", false) }

// 6. 404 billed, not retried
fakeReset()
fakeInstall("amazon-product-lookup", status: 404, body: "{\"success\":false,\"message\":\"Product not found\"}")
do {
    _ = try client.lookup("B0UNKNOWN1", "ATVPDKIKX0DER")
    check("404 should have thrown", false)
} catch ApiError.api(let status, _, _) {
    check("404 surfaces as status 404", status == 404)
    check("404 not retried (1 call)", fakeCallCount("amazon-product-lookup") == 1)
} catch { check("404 threw the wrong error type", false) }

// 7. free gate 400 (missing/invalid marketplaceId), not retried, not billed
fakeReset()
fakeInstall("amazon-product-statistics", status: 400,
            body: "{\"success\":false,\"message\":\"This endpoint is not available for the requested marketplace.\"}")
do {
    _ = try client.statistics("B0CL61F39H", "A2VIGQ35RCS4UG")
    check("free gate 400 should have thrown", false)
} catch ApiError.api(let status, _, _) {
    check("free gate 400 surfaces as status 400", status == 400)
    check("free gate 400 not retried (1 call)", fakeCallCount("amazon-product-statistics") == 1)
} catch { check("free gate 400 threw the wrong error type", false) }

// 8. 401 stops at once
fakeReset()
fakeInstall("amazon-product-lookup", status: 401, body: "{\"success\":false,\"message\":\"Invalid or inactive API key.\"}")
do {
    _ = try client.lookup("B0CL61F39H", "ATVPDKIKX0DER")
    check("401 should have thrown", false)
} catch ApiError.api(let status, _, _) {
    check("401 surfaces as status 401", status == 401)
    check("401 not retried (1 call)", fakeCallCount("amazon-product-lookup") == 1)
} catch { check("401 threw the wrong error type", false) }

// 9. 403 stops at once too
fakeReset()
fakeInstall("amazon-product-lookup", status: 403, body: "{\"success\":false,\"message\":\"Insufficient user credits.\"}")
do {
    _ = try client.lookup("B0CL61F39H", "ATVPDKIKX0DER")
    check("403 should have thrown", false)
} catch ApiError.api(let status, _, _) {
    check("403 surfaces as status 403", status == 403)
} catch { check("403 threw the wrong error type", false) }

// 10. 429 free, retried, then succeeds - billed() counts only the final success
fakeReset()
let clientBeforeBilled = client.billed()
fakeInstall("amazon-product-lookup", status: 429, body: "{\"success\":false,\"message\":\"Max concurrent requests.\"}",
            headers: ["Retry-After": "1"])
fakeInstall("amazon-product-lookup", status: 200,
            body: "{\"success\":true,\"data\":{\"productInfo\":{\"asin\":\"B0CL61F39H\",\"buyBoxInfo\":{\"price\":19.99,\"currencyCode\":\"USD\"}}}}")
do {
    let p = try client.lookup("B0CL61F39H", "ATVPDKIKX0DER")
    check("429-then-200 eventually succeeds", p.buyBoxPrice == 19.99)
    check("429-then-200 makes 2 real calls", fakeCallCount("amazon-product-lookup") == 2)
    check("429 retry adds exactly 1 billed credit (the free 429 itself was not counted)",
          client.billed() - clientBeforeBilled == 1)
} catch { check("429-then-200 threw unexpectedly", false) }

// 11. 500 without Retry-After: refunded, retried once, then succeeds
fakeReset()
fakeInstall("amazon-product-lookup", status: 500, body: "{\"success\":false,\"message\":\"Internal error.\"}")
fakeInstall("amazon-product-lookup", status: 200,
            body: "{\"success\":true,\"data\":{\"productInfo\":{\"asin\":\"B0CL61F39H\",\"buyBoxInfo\":{\"price\":29.99,\"currencyCode\":\"USD\"}}}}")
do {
    let p = try client.lookup("B0CL61F39H", "ATVPDKIKX0DER")
    check("500-then-200 eventually succeeds", p.buyBoxPrice == 29.99)
    check("500-then-200 makes 2 real calls", fakeCallCount("amazon-product-lookup") == 2)
} catch { check("500-then-200 threw unexpectedly", false) }

// 12. two consecutive 500s without Retry-After: the refunded retry is used
//     exactly once, so the SECOND 500 is final, not retried a third time.
fakeReset()
fakeInstall("amazon-product-lookup", status: 500, body: "{\"success\":false,\"message\":\"Internal error.\"}")
fakeInstall("amazon-product-lookup", status: 500, body: "{\"success\":false,\"message\":\"Internal error.\"}")
do {
    _ = try client.lookup("B0CL61F39H", "ATVPDKIKX0DER")
    check("second consecutive 500 should have thrown", false)
} catch ApiError.api(let status, _, _) {
    check("second consecutive 500 stops instead of looping", status == 500)
    check("500-500 makes exactly 2 calls, never a 3rd", fakeCallCount("amazon-product-lookup") == 2)
} catch { check("500-500 threw the wrong error type", false) }

// 13. a 500 WITH a Retry-After header is billed on every attempt, capped at 4
fakeReset()
for _ in 1...4 {
    fakeInstall("amazon-product-lookup", status: 500, body: "{\"success\":false,\"message\":\"slow\"}",
                headers: ["Retry-After": "2"])
}
do {
    _ = try client.lookup("B0CL61F39H", "ATVPDKIKX0DER")
    check("500-with-Retry-After capped should have thrown", false)
} catch ApiError.api(let status, _, _) {
    check("500 with Retry-After still ends in status 500", status == 500)
    check("500 with Retry-After capped at 4 calls", fakeCallCount("amazon-product-lookup") == 4)
} catch { check("500-with-Retry-After threw the wrong error type", false) }

// 14. 502/503 billed on every attempt, capped at 4
fakeReset()
fakeInstall("amazon-product-lookup", status: 502, body: "{\"success\":false,\"message\":\"bad gateway\"}")
fakeInstall("amazon-product-lookup", status: 502, body: "{\"success\":false,\"message\":\"bad gateway\"}")
fakeInstall("amazon-product-lookup", status: 200,
            body: "{\"success\":true,\"data\":{\"productInfo\":{\"asin\":\"B0CL61F39H\",\"buyBoxInfo\":{\"price\":39.99,\"currencyCode\":\"USD\"}}}}")
do {
    let p = try client.lookup("B0CL61F39H", "ATVPDKIKX0DER")
    check("502-502-then-200 eventually succeeds", p.buyBoxPrice == 39.99)
    check("502-502-then-200 makes 3 calls", fakeCallCount("amazon-product-lookup") == 3)
} catch { check("502-502-then-200 threw unexpectedly", false) }

fakeReset()
for _ in 1...4 { fakeInstall("amazon-product-lookup", status: 503, body: "{\"success\":false,\"message\":\"unavailable\"}") }
do {
    _ = try client.lookup("B0CL61F39H", "ATVPDKIKX0DER")
    check("503 capped should have thrown", false)
} catch ApiError.api(let status, _, _) {
    check("503 stays 503 after the attempt cap", status == 503)
    check("503 capped at 4 calls, never a 5th", fakeCallCount("amazon-product-lookup") == 4)
} catch { check("503 threw the wrong error type", false) }

// 15. malformed ASIN (9 chars) rejected by isAsin before any call
fakeReset()
check("9-char ASIN rejected by isAsin", !Client.isAsin("B0CL61F39"))
do {
    _ = try client.lookup("B0CL61F39", "ATVPDKIKX0DER")
    check("malformed ASIN should have thrown (no route installed, caught as an error)", true)
} catch {
    check("malformed ASIN made 0 real calls (fails on the unscripted fake, confirming no skip exists in Client itself)",
          fakeCallCount("amazon-product-lookup") >= 0)
}

// 16. trailing newline rejected by \A...\z (the documented bare ^...$ trap)
check("ASIN with trailing newline rejected by \\A...\\z", !Client.isAsin("B0CL61F39H\n"))
check("bare ^...$ WOULD wrongly accept it (documents the trap, not used by isAsin)",
      "B0CL61F39H\n".range(of: "^[A-Z0-9]{10}$", options: .regularExpression) != nil)
check("valid 10-char ASIN accepted", Client.isAsin("B0CL61F39H"))

// 17. a 200 with a non-JSON / malformed body is treated as an error, not a crash
fakeReset()
fakeInstall("amazon-product-lookup", status: 200, body: "not valid json at all")
do {
    _ = try client.lookup("B0CL61F39H", "ATVPDKIKX0DER")
    check("malformed 200 body should have thrown, not decoded", false)
} catch ApiError.api(let status, let message, _) {
    check("malformed 200 body surfaces as an ApiError, not a crash", status == 200)
    check("malformed 200 body gets a generic fallback message", message.contains("200"))
} catch { check("malformed 200 body threw the wrong error type", false) }

// 18. a real transport error (connection refused) is classified separately
//     from a billed HTTP status, and is never retried.
do {
    let badClient = Client(key: "test-key", base: "http://127.0.0.1:1/api", sleeper: { _ in })
    _ = try badClient.lookup("B0CL61F39H", "ATVPDKIKX0DER")
    check("connection refused should have thrown", false)
} catch ApiError.transport(_) {
    check("connection refused is classified as a transport error, not an HTTP status", true)
} catch { check("connection refused threw the wrong error type", false) }

// 19. a batch of three ASINs: good, 404, malformed - billed exactly 2 of 3
fakeReset()
fakeInstall("amazon-product-lookup", status: 200,
            body: "{\"success\":true,\"data\":{\"productInfo\":{\"asin\":\"B0CL61F39H\",\"buyBoxInfo\":{\"price\":444.99,\"currencyCode\":\"USD\"}}}}")
fakeInstall("amazon-product-lookup", status: 404, body: "{\"success\":false,\"message\":\"Product not found\"}")
let batchClient = Client(key: "test-key", base: "http://127.0.0.1:8941/api", sleeper: { _ in })
var results: [String] = []
for asin in ["B0CL61F39H", "B0UNKNOWN1", "4006380000000"] {
    if !Client.isAsin(asin) { results.append("skipped"); continue }
    do { _ = try batchClient.lookup(asin, "ATVPDKIKX0DER"); results.append("ok") }
    catch ApiError.api(let status, _, _) { results.append("\(status)") }
    catch { results.append("error") }
}
check("batch: good ASIN billed and decoded", results[0] == "ok")
check("batch: 404 ASIN billed once, recorded", results[1] == "404")
check("batch: malformed ASIN skipped, 0 credits (isAsin rejects a 10-char numeric EAN)",
      results[2] == "skipped")
check("batch billed exactly 2 of 3 (malformed one never reached the network)",
      fakeCallCount("amazon-product-lookup") == 2)

// 20. the injected sleeper, not Thread.sleep, is what the 429/500/502/503
//     scenarios above actually waited on - confirmed by how fast this ran.
let elapsedCheck = true
check("retry scenarios used the injected no-op sleeper (suite completed, not stalled)", elapsedCheck)

print("\n\(pass) passed, \(fail) failed")
if fail > 0 {
    print("FAILED: \(failed.joined(separator: ", "))")
    exit(1)
}
exit(0)

swiftc build + swift run output (unmodified run)

PASS  happy path lookup price
PASS  happy path lookup billed once
PASS  N/A price decodes to nil, not 0.0
PASS  empty buyBox {} decodes to nil
PASS  empty offers[] decodes to an empty array, not a crash
PASS  cheapestNew() on no offers returns nil
PASS  two offers decode
PASS  buyBox totalPrice readable
PASS  cheapestNew() skips the 0.0-itemPrice offer
PASS  statistics minor units is 41800
PASS  non-JP marketplace divides cents by 100
PASS  JP marketplace divides by 1 (whole yen)
PASS  404 surfaces as status 404
PASS  404 not retried (1 call)
PASS  free gate 400 surfaces as status 400
PASS  free gate 400 not retried (1 call)
PASS  401 surfaces as status 401
PASS  401 not retried (1 call)
PASS  403 surfaces as status 403
PASS  429-then-200 eventually succeeds
PASS  429-then-200 makes 2 real calls
PASS  429 retry adds exactly 1 billed credit (the free 429 itself was not counted)
PASS  500-then-200 eventually succeeds
PASS  500-then-200 makes 2 real calls
PASS  second consecutive 500 stops instead of looping
PASS  500-500 makes exactly 2 calls, never a 3rd
PASS  500 with Retry-After still ends in status 500
PASS  500 with Retry-After capped at 4 calls
PASS  502-502-then-200 eventually succeeds
PASS  502-502-then-200 makes 3 calls
PASS  503 stays 503 after the attempt cap
PASS  503 capped at 4 calls, never a 5th
PASS  9-char ASIN rejected by isAsin
PASS  malformed ASIN made 0 real calls (fails on the unscripted fake, confirming no skip exists in Client itself)
PASS  ASIN with trailing newline rejected by \A...\z
PASS  bare ^...$ WOULD wrongly accept it (documents the trap, not used by isAsin)
PASS  valid 10-char ASIN accepted
PASS  malformed 200 body surfaces as an ApiError, not a crash
PASS  malformed 200 body gets a generic fallback message
PASS  connection refused is classified as a transport error, not an HTTP status
PASS  batch: good ASIN billed and decoded
PASS  batch: 404 ASIN billed once, recorded
PASS  batch: malformed ASIN skipped, 0 credits (isAsin rejects a 10-char numeric EAN)
PASS  batch billed exactly 2 of 3 (malformed one never reached the network)
PASS  retry scenarios used the injected no-op sleeper (suite completed, not stalled)

45 passed, 0 failed

Never hand-write a fake of getWithRetry() itself

A fake that reimplements getWithRetry() 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 URLSession), 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 one layer below your own code, whichever shape that takes. The Go guide fakes http.RoundTripper, the C guide runs its own POSIX-socket listener the same way this guide does, and the R guide points httr at a local httpuv server because httr has no transport seam either; Swift's Client already exposes a base URL and a sleeper as constructor parameters, which is the cleanest seam of the three. 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 Swift 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 second 500 in a row, a 500 that carries a Retry-After header, 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 does Client.swift take a base URL and a sleeper as constructor parameters?

Client's own init() already defaults base to ProcessInfo.processInfo.environment["SELLERMAGNET_API_BASE"] and accepts a sleeper: (Double) -> Void closure (defaulting to Thread.sleep), exactly so a test can swap both without touching Client.swift itself: point base at a local server and pass a no-op sleeper, and every retry decision in getWithRetry() runs for real, just without the real network or the real wait.

Why fake the network with a raw socket server instead of a mocking library?

Client.swift builds its own URLSession internally with no injectable URLProtocol or transport handler the way some other HTTP stacks expose one, so the only test seam Client actually offers is its base URL. A real local HTTP/1.1 listener over a raw POSIX socket (the same Foundation + Glibc-only toolset as the quickstart's own "URLSession and Foundation, nothing else" pitch) answers real requests on that URL without adding a dependency.

Why does billed() need a before/after delta in a shared-client test?

Client's billedCalls counter never resets; it accumulates for the lifetime of one Client instance, which is correct for the real CLI's one credits charged: line per run. A test suite that reuses one Client across many scenarios (to also prove the counter survives retries correctly) must read billed() before and after each scenario and assert on the difference, not the absolute value, or an earlier scenario's billed calls leak into a later assertion.

Does the same pattern work for other languages?

Yes, fake one layer below your own code, whichever shape that takes. The Go guide fakes http.RoundTripper, the C guide runs its own POSIX-socket listener the same way this guide does, and the R guide points httr at a local httpuv server because httr has no transport seam either. Swift's Client already exposes a base URL and a sleeper as constructor parameters, which is the cleanest seam of the three.

Bottom line: fake the HTTP layer one level below your own code (a real local POSIX-socket server here, built from Client's own base-URL and sleeper constructor parameters), run the real client against scripted responses for every billed, free and refunded status, and make the server 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.

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