How-to › Ship an SDK

How to inject a fake clock into an SDK to test timeouts#

Pass a clock to the SDK's constructor so a test of a 30-second deadline runs on virtual time and still raises the timeout error, in TypeScript, Go, and Python.

Audience
Library maintainer
Level
intermediate
Topic
Compose runtime features in an SDK
Languages
TypeScript, Go and Python
Verified

Read first: Wrap an SDK transport in a middleware chain

Your SDK gives up after 30 seconds, so the test that proves it also takes 30 seconds. The client calls setTimeout, time.Now, or time.monotonic directly, so the only way to reach the deadline in a test is to wait for it. The slow test gets skipped, and the timeout path ships untested.

What you get

You will end up with a client whose deadline, attempt limit, and backoff all read one injected clock. Its tests cross a 30-second deadline on virtual time in TypeScript, Go, and Python. This is for you if you maintain an SDK with a timeout.

Short answer

Give the SDK a clock with now() and sleep() in its constructor, and route every deadline, attempt limit, and backoff through it. In tests, pass a manual clock that jumps to the next pending sleep and a fake transport with no socket. A 30-second deadline then raises its error on virtual time. Go’s testing/synctest reaches the same result without the parameter, inside a bubble of fake time, and Python’s freezegun by patching the time module.

You will need

An SDK with a timeout or deadline, and the runtimes for the languages you test. The TypeScript files run with Node’s type stripping, which needs Node 22.18 or later. The Go tests run on Go 1.24 or later, and the synctest test needs 1.25. The Python samples ran on 3.12. The transport is already a function the client calls, as in wrapping an SDK transport with middleware, so a test can hand it a fake.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
@sinonjs/fake-timers or Jest fake timersYou cannot change the SDK, and it reads setTimeout and performance.nowPatches the whole process; the default install hung a real node:http request hereThe test also talks to a real socket, or you own the SDK
constructor-injected clock interfaceYou own the SDK and test it in several runtimes or frameworksOne more constructor option, and every wait in the SDK must use it, transports includedThe SDK is someone else’s, or Go’s bubble already covers it
Go testing/synctest or jonboulle/clockworkGo 1.25 for synctest with no SDK change; clockwork for an injected clock, which also runs on Go 1.24synctest needs every goroutine inside the bubble; clockwork needs a loop that advances the clockThe code waits on real network I/O, which no bubble controls
Python freezegun or time-machineA Python SDK you cannot change, which reads the time moduleNeither replaces time.sleep, and time-machine left time.monotonic unmoved with tick on or offThe SDK computes deadlines on time.monotonic and you picked time-machine

An injected clock costs a constructor option and the discipline to send every wait through it, and in exchange it works in any runtime and any test framework. Global fake timers need no change to the SDK, but they patch everything underneath it too. Go’s synctest is the exception, because its fake clock applies only inside its bubble.

Put the clock in the constructor

The interface is two methods: a monotonic reading in milliseconds, and a sleep that a signal can cancel.

export interface Clock {
  /** Milliseconds on a monotonic scale. Only differences mean anything. */
  now(): number
  /** Resolves after ms; rejects with signal.reason if the signal aborts first. */
  sleep(ms: number, signal?: AbortSignal): Promise<void>
}

Each attempt races the transport against a sleep on that clock, and cancels whichever side lost.

  async function attemptOnce(path: string, budgetMs: number): Promise<string> {
    const request = new AbortController()
    const timer = new AbortController()
    try {
      return await Promise.race([
        transport(path, request.signal),
        clock.sleep(budgetMs, timer.signal).then(() => {
          throw new AttemptTimeout()
        }),
      ])
    } finally {
      // Whichever side lost is cancelled: the request on a timeout, the timer on an answer.
      request.abort(new AttemptTimeout())
      timer.abort(new Error('attempt settled'))
    }
  }

The production default is systemClock, built on setTimeout and performance.now, so callers who never pass a clock see no change.

Drive a manual clock in the test

The test clock never advances on its own. run() lets pending callbacks finish, then jumps to the earliest sleep, and repeats until the work settles.

  async run<T>(work: Promise<T>, maxJumps = 1_000): Promise<T> {
    let settled = false
    work.then(
      () => (settled = true),
      () => (settled = true),
    )
    for (let jump = 0; jump <= maxJumps; jump++) {
      // Let every pending callback run before deciding the work is waiting on the clock.
      await new Promise((resolve) => setImmediate(resolve))
      if (settled) return work
      this.#sleepers.sort((a, b) => a.at - b.at || a.seq - b.seq)
      const next = this.#sleepers.shift()
      if (!next) throw new Error('the work is waiting on something other than this clock')
      this.#now = next.at
      next.resolve()
    }
    throw new Error(`still running after ${maxJumps} jumps`)
  }

Run the client against a fake transport that never answers:

node demo.ts
attempt 1   5000 ms  attempt timed out
attempt 2  11000 ms  attempt timed out
attempt 3  18000 ms  attempt timed out
attempt 4  27000 ms  attempt timed out
DeadlineExceededError: deadline exceeded after 4 attempts and 30000 ms
virtual time 30000 ms; real time under 5 s: true

Each attempt gets five seconds, and the backoffs between them are one, two, and four seconds. The fourth backoff, eight seconds, is cut to the three seconds left, so the deadline lands at exactly 30000 virtual milliseconds.

Check it worked

The first test asserts the error, four attempts, 30000 ms on the clock, a cancellation of every attempt, and less than five seconds of real time. The bound is deliberately loose, because the claim is that 30 seconds did not pass, not that this machine is fast.

node --test clock.test.ts
1..6
# tests 6
# suites 0
# pass 6
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 276.903589

Swap clock.sleep for systemClock.sleep in attemptOnce and the first test fails.

Patch time globally instead

With no clock passed, the client falls back to setTimeout and performance.now, and @sinonjs/fake-timers can replace both. The second half of the script sends a plain node:http request to a local server under three installs.

node sinon.ts
toFake setTimeout, clearTimeout, performance
  deadline exceeded after 4 attempts and 30000 ms; real time under 5 s: true
default install (fakes every method)
  node:http GET to 127.0.0.1: no answer within 5 s of real time
toFake ['nextTick']
  node:http GET to 127.0.0.1: no answer within 5 s of real time
toFake ['setTimeout', 'clearTimeout', 'performance']
  node:http GET to 127.0.0.1: answered

The README says an install with no toFake list fakes every method it supports, and faking nextTick alone was enough to stall the request. Jest’s doNotFake option makes the same choice from the other side, and its documentation says its default fakes every API.

In Go, one test injects a clockwork FakeClock and advances it whenever the client waits on it. The other passes no clock at all and runs inside synctest.Test.

node go-tests.mjs
PASS  TestDeadlineInjectedClockwork
      sdk_test.go:51: deadline exceeded after 4 attempts and 30s; clock elapsed 30s
PASS  TestPermanentErrorIsNotRetried
PASS  TestDeadlineSynctest
      synctest_test.go:19: deadline exceeded after 4 attempts and 30s; clock elapsed 30s

synctest.Test arrived in Go 1.25, so its test sits in a file marked //go:build go1.25. Go 1.24 leaves that file out and runs the two clockwork tests, which is the route for a toolchain without synctest.

In Python, the same client runs under an injected ManualClock, under freezegun with time.sleep patched to tick, and under time-machine with time.sleep patched to shift:

python3 -I python/compare.py
injected ManualClock               DeadlineExceeded: deadline exceeded after 4 attempts and 30 s; real time under 5 s: True
freezegun 1.5.5, sleep -> tick     DeadlineExceeded: deadline exceeded after 4 attempts and 30 s; real time under 5 s: True
time-machine 3.6.0, SystemClock    RuntimeError: stopped by the guard after 100 attempts; real time under 5 s: True
time-machine 3.6.0, WallClock      DeadlineExceeded: deadline exceeded after 4 attempts and 30 s; real time under 5 s: True

Time-machine moved time.time and left time.monotonic where it was, so a deadline measured on the monotonic clock never arrived until the guard stopped it. Its usage page lists the functions it mocks, and time.monotonic is not among them; time.clock_gettime is mocked for CLOCK_REALTIME only. A wall-clock reading works under it, at the price of a deadline that jumps whenever the system clock is set.

The Python tests pin each of those findings, with tick on and off, and also that neither library replaces time.sleep under any option the test tries:

python3 -I python/test_sdk.py
ok   test_a_transient_failure_is_retried_after_the_backoff
ok   test_bad_limits_are_refused
ok   test_freezegun_moves_monotonic_and_rewrites_module_attributes
ok   test_injected_clock_reaches_the_deadline_without_real_waiting
ok   test_neither_library_replaces_sleep
ok   test_time_machine_leaves_monotonic_alone

When it goes wrong

The test with a fake clock still takes the real time. The timeout lives on the socket, where no fake clock reaches, so pair the fake clock with a fake transport. The same 1500 ms timeout, once on a socket and once on the manual clock:

node pitfall.ts
socket timeout 1500 ms  clock moved to 60000 ms; call settled: false
                        TransientError: socket idle for 1500 ms; waited at least 1.4 s of real time: true
clock timeout 1500 ms   clock moved to 1500 ms
                        TransientError: no answer within 1500 ms on the clock; waited at least 1.4 s of real time: false

Sixty virtual seconds passed while the socket call stayed pending.

run() throws the work is waiting on something other than this clock. Some wait in the SDK skipped the injected clock, or the transport is real; the last test in clock.test.ts shows the message. Send that wait through clock.sleep.

A timing measured inside a freezegun block reads the frozen time. freezegun replaces time.perf_counter as well as time.monotonic, and it rewrites module attributes that hold the real functions.1 The Python test asserts both, and compare.py keeps its real timer inside a dict for that reason.

When not to do this

Do not add a clock parameter to an SDK whose only timeout is the socket’s own. A clock cannot shorten a timer it does not own, and the test still needs a fake transport. Test the socket timeout once, with a short limit, against a server that never answers.

Keep global fake timers out of integration tests. The default install stalled a plain HTTP request here, and the same patch reaches every library in the process.

Do not use time-machine for a Python SDK that measures deadlines on time.monotonic. Inject a clock, or use freezegun, which moved the monotonic clock in the same run.2

Last verified

Verified 2026-11-30 against Node 22.23.5, Go 1.25.14, Python 3.12.3, @sinonjs/fake-timers 15.5.0, clockwork v0.5.0, freezegun 1.5.5, time-machine 3.6.0, and python-dateutil 4.0.0. The clockwork tests also ran on Go 1.24.7. Every output block is what the command preceding it printed. Jest was not run; its default and doNotFake are read from its documentation.

Footnotes

  1. The rewrite is in freezegun’s api.py: on entry it walks sys.modules and, for each module attribute outside its ignore list that holds a real time function, sets the fake in its place. That is how a module that ran from time import monotonic sees frozen time. It also means a helper that saved the real function at import time to measure the test is holding the fake. ↩︎ Back to text

  2. freezegun’s README offers a real_asyncio parameter, which lets asyncio event loops see real monotonic time while time.monotonic() itself stays frozen. The README gives the reason: without it, asyncio.sleep() and the other asyncio functions that rely on monotonic time break. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.