Developer Tools
Make Tests for Time-, Random-, and Environment-Dependent Code Deterministic by Injecting Each Hidden Input
You are helping me write deterministic tests for code that depends on hidden inputs: the current time, random numbers, generated IDs, environment variables, the local timezone or locale, or the machine it runs on. Tests for such code pass most of the time and fail on certain days, in certain timezones, or on CI. I want to find every hidden input first, then make each one explicit. Inputs I will give you: - The function or module under test, and any existing tests for it. - How it is called in production, and which language and test framework we use. Steps: 1. Inventory the hidden inputs. List every call that reads ambient state: clock reads (now, today, monotonic timers), random generators and UUID creation, environment variables and config files, the system timezone and locale, file system paths, and hostname or CPU count. For each, give the line and what the code does with the value. 2. For each input, choose an injection point: a parameter with a production default, a clock or RNG object passed in, or, as a last resort, a patch in the test. Prefer injection over global patching, and say why when patching is the only option. 3. Design test cases that pin each input to values that matter: date boundaries (end of month, Feb 29, the daylight-saving switch in a named timezone, New Year in UTC versus local time), a fixed random seed plus a case where the random draw hits an edge value, empty and missing environment variables, and a non-default locale. 4. Write the tests. Each test sets every hidden input it relies on explicitly and asserts an exact value, never "roughly now" unless a tolerance is part of the specification. 5. Add one guard test that runs the code under a different timezone or locale than the developer's default, to catch new hidden inputs later. Output: the inventory table, the proposed signature changes, and the test code, with a sentence on each test explaining which failure it catches. When to use it: flaky tests that fail near midnight or month-end, code about to handle billing periods, expiry or scheduling, and before refactoring anything time-based. How to adapt it: name your language so the answer uses its standard tools (for example, an injectable clock object in Java, or a seeded random.Random instance in Python). If you can't change signatures, ask for a patching-based version and accept the trade-off that it is coupled to implementation details. Example input: a Python function is_trial_expired(user) that calls datetime.now() and compares it to user.trial_end. Good output flags the naive datetime.now() as both a hidden input and a timezone bug, proposes is_trial_expired(user, now) with a default, and tests the exact expiry instant, one second before and after it, and a trial ending during a daylight-saving change.
Sign in to upvote this prompt.