Building and Unit Testing a FastAPI REST Endpoint Around Python Logic

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

Suppose you have a pure Python calculation—such as computing the arithmetic mean of daily settlement prices for a traded symbol across an inclusive date window (for instance, "CORN" from 2025-03-10 through 2025-03-12, where daily prices 250.0, 253.0, and 259.0 yield 254.0)—and internal services or analytics dashboards need to invoke it over HTTP.

Address both parts below:

  1. Exposing Python logic as a REST API endpoint:
    • Explain how you have designed (or would design) a REST endpoint around this calculation.
    • Answer directly whether FastAPI itself counts as a REST endpoint.
    • Walk through how an endpoint translates an incoming HTTP request into a Python function call and turns the result (or failure) back into an HTTP response.
  2. Unit testing the calculation and the service layer:
    • Describe your everyday workflow for unit testing this kind of code, including how you isolate external systems such as databases and where unit tests hand off to integration tests.
    • Write concrete unit tests covering happy paths, boundary windows, and error cases.

Scope & Expectations

  • Separating REST principles (resource URLs, HTTP verb semantics, status codes, statelessness), individual endpoints, web frameworks like FastAPI, and ASGI servers.
  • Tracing the end-to-end request lifecycle: routing, input parsing and validation, dependency injection, pure domain execution, JSON serialization, and error mapping.
  • Writing clear pytest unit tests structured with Arrange–Act–Assert and parameterized edge cases rather than only happy-path inputs.
  • Isolating database or network collaborators with fakes or mocks, articulating what those substitutes hide, and defining the boundary with integration tests.

Step-by-step walkthrough

  1. Separate REST, the endpoint, and the framework

    Candidates often blur three distinct concepts together in this question, so start by defining each one crisply:

    • REST (Representational State Transfer): An architectural style for designing HTTP APIs around named resources (nouns with URLs, like /instruments/CORN/average-price). Clients act on resources using standard HTTP methods with standard guarantees:
      • GET reads data and is safe (changes nothing on the server) and idempotent (sending the exact same request five times leaves the server in the same state as sending it once).
      • PUT and DELETE modify state and are idempotent; POST creates or triggers an action and is generally not idempotent.
      • HTTP status codes communicate the outcome category (2xx success, 4xx client error, 5xx server error).
      • Requests are stateless: every request carries all parameters and credentials needed to fulfill it, so any server replica behind a load balancer can handle any call.
    • An endpoint: One specific HTTP method paired with one URL route that clients call, such as GET /instruments/{symbol}/average-price.
    • FastAPI: A Python web framework—a toolkit you use to declare endpoints, parse and validate inputs (via Pydantic, a data-validation library driven by Python type hints), serialize JSON responses, and generate interactive OpenAPI documentation. FastAPI builds an ASGI (Asynchronous Server Gateway Interface) application object, while a separate ASGI server such as Uvicorn actually opens the network port and translates raw TCP/HTTP bytes.
    Caller (dashboard / script)
       |   HTTP GET /instruments/CORN/average-price?start=2025-03-10&end=2025-03-12
       v
    Uvicorn (ASGI web server listening on TCP port 8000)
       v
    FastAPI app (framework: routing, Pydantic validation, dependency injection, JSON)
       v
    Endpoint handler (@app.get("/instruments/{symbol}/average-price"))
       v
    average_price(...)  <-- pure Python domain function (no HTTP, no SQL)
    

    So "Does FastAPI count as a REST endpoint?" has a direct answer: No. FastAPI is the framework used to build endpoints, not an endpoint itself—and merely importing FastAPI does not make an API RESTful (writing POST /doEverything in FastAPI is RPC over HTTP, not REST).

  2. Write the core calculation as a pure function

    Before touching any web framework, write the calculation as a pure function—a function whose return value depends strictly on its arguments and has zero side effects (no database queries, no global state, no HTTP objects). Keeping math pure makes unit tests trivial and keeps the web route thin.

    from datetime import date
    
    
    class NoPricesInRange(ValueError):
        """Raised when a valid date window contains zero price observations."""
    
    
    def average_price(prices: dict[date, float], start: date, end: date) -> float:
        """Compute the arithmetic mean of prices on dates in [start, end] inclusive."""
        if start > end:
            raise ValueError(f"start date ({start}) cannot be after end date ({end})")
    
        total = 0.0
        count = 0
        for day, price in prices.items():
            # Both start and end boundaries are included in the window
            if start <= day <= end:
                total += price
                count += 1
    
        if count == 0:
            raise NoPricesInRange(f"no prices recorded between {start} and {end}")
        return total / count
    

    Walk through four daily prices to see both the happy path and the two distinct failure modes:

    Daily prices for symbol CORN:
      2025-03-09 -> 248.0
      2025-03-10 -> 250.0
      2025-03-11 -> 253.0
      2025-03-12 -> 259.0
    
    1. Window 2025-03-10 .. 2025-03-12  -->  (250.0 + 253.0 + 259.0) / 3 = 762.0 / 3 = 254.0
    2. Window 2025-03-15 .. 2025-03-16  -->  raises NoPricesInRange (weekend, 0 matching days)
    3. Window 2025-03-12 .. 2025-03-10  -->  raises ValueError      (reversed date bounds)
    

    Using a dedicated NoPricesInRange subclass lets the HTTP layer distinguish "valid query, no data found" from "contradictory request parameters" without string-matching error messages.

  3. Design the HTTP URL, method, and status codes

    Before writing FastAPI code, specify the exact HTTP contract callers can rely on:

    Request:
      GET /instruments/CORN/average-price?start=2025-03-10&end=2025-03-12
    
    Possible responses:
      200 OK                   {"symbol": "CORN", "start": "2025-03-10", "end": "2025-03-12", "average": 254.0}
      400 Bad Request          start > end (syntactically valid dates, logically invalid range)
      404 Not Found            unknown symbol, or zero prices recorded inside [start, end]
      422 Unprocessable Entity malformed query string like start=2025-15-99 (rejected before route runs)
      500 Internal Server Err  unexpected server failure (e.g., database connection dropped)
    

    Every part of this contract has a clear engineering reason: - Why GET: Computing a historical average has no side effects, so callers, dashboards, and HTTP proxies know they can safely retry or cache responses. - Path parameter vs query parameters: symbol identifies which financial instrument resource you are addressing (/instruments/{symbol}/average-price), while start and end filter the slice of data read from it. - Real HTTP status codes instead of 200 with {"error": ...}: Dashboards, retry middleware, and alerting dashboards inspect status codes directly without parsing JSON bodies. - Authentication: If callers are internal services or analysts' scripts, enforce an Authorization: Bearer <token> JWT or X-API-Key header over HTTPS via a reusable FastAPI security dependency.

  4. Wire up the FastAPI endpoint and trace one request

    The endpoint's job is purely translation: extract inputs from HTTP, fetch data via an injected store, call average_price, and serialize (convert Python objects like date and float into standard JSON text) the response.

    Putting database access behind a small PriceStore object passed via dependency injection (Depends(get_store), meaning the framework supplies the collaborator rather than the route hardcoding sqlite3.connect(...)) makes testing without a real database effortless.

    import sqlite3
    from datetime import date
    from fastapi import Depends, FastAPI, HTTPException
    from pydantic import BaseModel
    
    
    class PriceStore:
        """Thin data-access wrapper reading daily prices for an instrument."""
    
        def __init__(self, connection: sqlite3.Connection):
            self.connection = connection
    
        def get_prices(self, symbol: str) -> dict[date, float]:
            # In large tables with years of ticks, also filter day BETWEEN ? AND ? in SQL
            rows = self.connection.execute(
                "SELECT day, price FROM daily_prices WHERE symbol = ?", (symbol,)
            )
            return {date.fromisoformat(day): float(price) for day, price in rows}
    
    
    def get_store():
        # check_same_thread=False allows FastAPI's worker threads to use the connection safely
        connection = sqlite3.connect("prices.db", check_same_thread=False)
        try:
            yield PriceStore(connection)
        finally:
            connection.close()
    
    
    class AverageResponse(BaseModel):
        symbol: str
        start: date
        end: date
        average: float
    
    
    app = FastAPI()
    
    
    @app.get("/instruments/{symbol}/average-price", response_model=AverageResponse)
    def get_average_price(
        symbol: str,
        start: date,
        end: date,
        store: PriceStore = Depends(get_store),
    ) -> AverageResponse:
        # Reject reversed dates before spending a database round-trip
        if start > end:
            raise HTTPException(status_code=400, detail=f"start ({start}) is after end ({end})")
    
        prices = store.get_prices(symbol)
        if not prices:
            raise HTTPException(status_code=404, detail=f"unknown symbol {symbol}")
    
        try:
            avg = average_price(prices, start, end)
        except NoPricesInRange as err:
            # Catch subclass NoPricesInRange BEFORE parent ValueError!
            raise HTTPException(status_code=404, detail=str(err))
        except ValueError as err:
            raise HTTPException(status_code=400, detail=str(err))
    
        return AverageResponse(symbol=symbol, start=start, end=end, average=avg)
    

    Trace one incoming request (GET /instruments/CORN/average-price?start=2025-03-10&end=2025-03-12) through all six stages:

    1. Uvicorn      Parses raw HTTP bytes and invokes FastAPI's ASGI entry point.
    2. Routing      Matches GET + "/instruments/{symbol}/average-price" -> symbol = "CORN".
    3. Validation   Reads query strings "2025-03-10" & "2025-03-12"; Pydantic parses them into
                    datetime.date objects (or stops immediately with HTTP 422 if malformed).
    4. Dependency   Calls get_store() up to yield, handing a PriceStore to get_average_price.
    5. Execution    Validates start <= end, fetches prices, calls pure average_price -> 254.0.
    6. Serialize    Validates AverageResponse, serializes dates to ISO strings ("2025-03-10"),
                    returns HTTP 200 JSON, and runs get_store()'s finally block to close SQLite.
    

    Notice we wrote def get_average_price(...) rather than async def: because sqlite3 is a blocking synchronous driver, declaring a plain def tells FastAPI to run the handler inside a worker thread pool so one slow query never freezes the main async event loop.

  5. Unit test the pure function with pytest

    In Python, standard unit testing uses pytest. Structure every test with Arrange–Act–Assert (set up inputs, call the unit under test once, verify the output or exception), use @pytest.mark.parametrize to cover boundary tables without copy-pasting boilerplate, and compare floating-point results with pytest.approx (because binary floating-point arithmetic makes expressions like 0.1 + 0.2 == 0.3 evaluate to False).

    from datetime import date
    import pytest
    
    SAMPLE_PRICES = {
        date(2025, 3, 9): 248.0,
        date(2025, 3, 10): 250.0,
        date(2025, 3, 11): 253.0,
        date(2025, 3, 12): 259.0,
    }
    
    
    def test_average_price_inner_window():
        """Happy path: mean of Mar 10..Mar 12 is (250 + 253 + 259) / 3 = 254.0."""
        # Arrange
        start, end = date(2025, 3, 10), date(2025, 3, 12)
        # Act
        result = average_price(SAMPLE_PRICES, start, end)
        # Assert
        assert result == pytest.approx(254.0)
    
    
    @pytest.mark.parametrize(
        "start, end, expected",
        [
            (date(2025, 3, 9), date(2025, 3, 10), 249.0),  # proves both endpoints are inclusive
            (date(2025, 3, 11), date(2025, 3, 11), 253.0), # single-day range (start == end)
            (date(2025, 2, 1), date(2025, 3, 9), 248.0),   # window starts before earliest data
            (date(2025, 3, 9), date(2025, 3, 12), 252.5),  # full series: 1010.0 / 4 = 252.5
        ],
    )
    def test_average_price_boundaries(start, end, expected):
        """Boundary checks catch off-by-one (< vs <=) date-comparison bugs."""
        assert average_price(SAMPLE_PRICES, start, end) == pytest.approx(expected)
    
    
    def test_reversed_dates_raise_value_error():
        """Logical error path: start after end raises ValueError."""
        with pytest.raises(ValueError):
            average_price(SAMPLE_PRICES, date(2025, 3, 12), date(2025, 3, 10))
    
    
    def test_empty_window_raises_no_prices_in_range():
        """Missing-data path: a weekend with zero observations raises NoPricesInRange."""
        with pytest.raises(NoPricesInRange):
            average_price(SAMPLE_PRICES, date(2025, 3, 15), date(2025, 3, 16))
    

    Notice how each test case targets a specific bug mode: if someone accidentally wrote start <= day < end (exclusive end), test_average_price_boundaries immediately fails (248.0 instead of 249.0).

  6. Unit test the HTTP layer with TestClient and a fake store

    Testing average_price alone does not verify URL routing, query-string parsing, JSON serialization, or HTTP status codes (200 vs 400 vs 404 vs 422). FastAPI provides TestClient (powered under the hood by httpx), which sends simulated HTTP requests straight into the ASGI app in memory—no open TCP port, no running Uvicorn process, and sub-millisecond execution.

    To isolate the HTTP layer from SQLite, swap get_store using app.dependency_overrides. Prefer a fake (a tiny working in-memory implementation backed by a Python dict) over a mock (a spy object recording method calls) whenever possible, because fakes test observable input-to-output behavior rather than brittle internal call sequences:

    from datetime import date
    import pytest
    from fastapi.testclient import TestClient
    
    
    class FakePriceStore:
        """In-memory replacement for PriceStore during fast HTTP unit tests."""
    
        def __init__(self, data: dict[str, dict[date, float]]):
            self.data = data
    
        def get_prices(self, symbol: str) -> dict[date, float]:
            return self.data.get(symbol, {})
    
    
    @pytest.fixture
    def client():
        fake_store = FakePriceStore({
            "CORN": {
                date(2025, 3, 10): 250.0,
                date(2025, 3, 11): 253.0,
                date(2025, 3, 12): 259.0,
            }
        })
        app.dependency_overrides[get_store] = lambda: fake_store
        try:
            with TestClient(app) as test_client:
                yield test_client
        finally:
            # Always clear overrides so test state never leaks into later tests!
            app.dependency_overrides.clear()
    
    
    def test_endpoint_happy_path_200(client):
        resp = client.get(
            "/instruments/CORN/average-price",
            params={"start": "2025-03-10", "end": "2025-03-12"},
        )
        assert resp.status_code == 200
        assert resp.json() == {
            "symbol": "CORN",
            "start": "2025-03-10",
            "end": "2025-03-12",
            "average": pytest.approx(254.0),
        }
    
    
    def test_endpoint_malformed_date_returns_422(client):
        resp = client.get(
            "/instruments/CORN/average-price",
            params={"start": "2025-15-99", "end": "2025-03-12"},
        )
        assert resp.status_code == 422
        assert resp.json()["detail"][0]["loc"] == ["query", "start"]
    
    
    def test_endpoint_reversed_dates_returns_400(client):
        resp = client.get(
            "/instruments/CORN/average-price",
            params={"start": "2025-03-12", "end": "2025-03-10"},
        )
        assert resp.status_code == 400
    
    
    def test_endpoint_unknown_symbol_returns_404(client):
        resp = client.get(
            "/instruments/SOYB/average-price",
            params={"start": "2025-03-10", "end": "2025-03-12"},
        )
        assert resp.status_code == 404
    
  7. Draw the line between unit tests and integration tests

    Replacing PriceStore with FakePriceStore makes HTTP tests fast and deterministic, but it blinds you to bugs inside PriceStore itself! Specifically, a fake hides: - Typos in SQL table or column names (daily_prices, symbol, day, price) or wrong SQL BETWEEN boundary logic. - Database driver type surprises (dates stored in unexpected formats, Decimal vs float, or NULL prices causing TypeError during addition). - Missing composite indexes on (symbol, day) turning a 2 ms lookup into a 4-second table scan. - Connection leaks, lock contention, and network timeouts.

    Balance speed and realism with a testing pyramid:

              /  E2E  \          Fewest: real Uvicorn socket + real DB + auth headers
             /---------\
            /Integration\        Moderate: real PriceStore against temp SQLite / Docker Postgres
           /-------------\
          /  Unit Tests   \      Most: pure average_price() + TestClient with FakePriceStore
         /-----------------\
    

    A great senior-engineer habit is running a shared contract test suite against both FakePriceStore and the real PriceStore (seeded on a temporary SQLite database via pytest's tmp_path fixture), guaranteeing your test fake can never silently drift away from real database behavior.

Intuition & how it works

Think of exposing a Python function over HTTP like running a café with a strict separation between the chef and the front counter. Your pure calculation (average_price) is the chef in the kitchen: given pre-measured ingredients (prices, start, end), the chef computes a number without knowing whether the order came from a phone app, a dashboard, or a test script. An endpoint (GET /instruments/{symbol}/average-price) is one specific order window on the counter, FastAPI is the counter system that checks the order slip for typos before handing clean ingredients to the chef, and Uvicorn is the front door letting customers into the building.

The naive beginner approach—writing SQL queries, string date parsing, averaging math, and JSON formatting inside one giant route function—hurts in two ways. Every tiny edge-case test (like checking a 1-day date window or reversed dates) now requires spinning up a database and mocking HTTP requests, making tests slow and fragile. Worse, mixing up framework vs endpoint concepts leads to sloppy APIs like POST /calcAvg returning HTTP 200 OK with {"error": "bad date"}, breaking HTTP caches, retries, and monitoring.

Follow one tiny 3-day example (2025-03-10: 250.0, 2025-03-11: 253.0, 2025-03-12: 259.0) across the clean design: - Request path: A dashboard calls GET /instruments/CORN/average-price?start=2025-03-10&end=2025-03-12. FastAPI parses "CORN" from the path and validates both query strings into Python datetime.date objects (automatically returning 422 if a date string is malformed like "2025-15-99"), injects PriceStore, calls average_price(prices, start, end) to get (250 + 253 + 259) / 3 = 254.0, and serializes {"symbol": "CORN", "start": "2025-03-10", "end": "2025-03-12", "average": 254.0} with status 200. - Two-layer unit testing: Direct pytest calls test average_price on plain dictionaries in microseconds (checking inclusive bounds, single-day windows, empty weekends → NoPricesInRange, and start > end → ValueError), while FastAPI's TestClient with an in-memory FakePriceStore tests routing and status codes (200, 400, 404, 422) without touching SQLite.

Key points

  • FastAPI is a web framework, not an endpoint: An endpoint is one HTTP verb + URL path (GET /instruments/{symbol}/average-price). FastAPI is the Python library used to declare endpoints, validate inputs (via Pydantic), and serialize JSON; Uvicorn is the ASGI (Asynchronous Server Gateway Interface) server listening on the network socket.
  • What makes an API RESTful: Modeling nouns as URL resources, honoring HTTP method semantics (GET is read-only and idempotent—repeating it has the exact same server effect as calling it once), using semantic HTTP status codes (200, 400, 404, 422, 500), and keeping requests stateless (each request carries all required context).
  • Keep domain logic pure and routes thin: A pure function (output determined solely by inputs, zero I/O or side effects) is trivial to test and reuse across CLI scripts, batch jobs, and REST endpoints alike.
  • Trace the 6-step request lifecycle: Route matching → query/path parsing & Pydantic validation (422 on type errors) → dependency injection (Depends(get_store)) → domain function call → response model serialization (Python date/float → JSON) → exception-to-status mapping + finally resource cleanup.
  • Test boundaries and failure paths with pytest: Follow Arrange–Act–Assert, group boundary tables with @pytest.mark.parametrize (inclusive endpoints, 1-day range, partial overlap), check exceptions with pytest.raises, and compare floats with pytest.approx.
  • Isolate I/O with fakes, then verify boundaries with integration tests: Override get_store via app.dependency_overrides with an in-memory fake (a lightweight working implementation) in TestClient tests, and pair those with integration tests running the real PriceStore against a seeded temporary database.

Common mistakes

  • Calling FastAPI or Flask "the REST endpoint," or claiming any JSON-over-HTTP function call (POST /runPythonFunc) is RESTful.
  • Using POST for read-only calculations or returning 200 OK on errors: POST defeats HTTP caching and safe retries, while 200 with {"status": "failed"} fools load balancers and monitoring into thinking broken endpoints are healthy.
  • Catching parent exceptions before subclasses: Because NoPricesInRange inherits from ValueError, writing except ValueError: above except NoPricesInRange: intercepts every empty range and misreports 404 Not Found as 400 Bad Request.
  • Blocking the async event loop: Writing async def on an endpoint that calls synchronous sqlite3 or heavy CPU loops freezes every concurrent request on that worker; use plain def (so FastAPI dispatches to a thread pool) or an async DB driver.
  • Forgetting app.dependency_overrides.clear() after a test: Leaking a fake store into subsequent tests causes unrelated tests to pass (or fail) against stale test data.
  • Expecting TestClient to return status 500 by default: TestClient(app) defaults to raise_server_exceptions=True, re-raising uncaught Python exceptions directly inside pytest; pass TestClient(app, raise_server_exceptions=False) when explicitly testing 500 responses.

Follow-up questions

  • If a client passes an unparseable date query parameter such as start=2025-15-99, which layer catches the error and what HTTP status code comes back? Because start: date and end: date are annotated in the route signature, FastAPI delegates parsing to Pydantic before your get_average_price function ever executes. Sending start=2025-15-99 stops at the validation layer and immediately returns HTTP 422 Unprocessable Entity with a structured JSON error pinpointing ["query", "start"]. Cross-field logical checks that require two valid dates—such as start <= end—happen next inside your validation/domain code and map to 400 Bad Request (and if your company API style mandates 400 for all bad client inputs, you can register a custom FastAPI exception handler on RequestValidationError).

  • Suppose historical prices live in a relational database—how do you keep unit tests independent of that database, and which failure modes remain untested? Decouple data fetching from math: test average_price directly with Python dict inputs, and inject a PriceStore interface into the route via Depends(get_store) so TestClient tests swap in an in-memory FakePriceStore (or unittest.mock.create_autospec(PriceStore) when testing retry/error interactions). The remaining risk is assumption drift between your fake and reality: SQL typos, exclusive vs inclusive SQL date filters, NULL or Decimal column types, missing (symbol, day) indexes, and connection timeouts are completely invisible to unit tests. Close that gap by running integration tests (and shared contract tests) against the real PriceStore backed by a seeded temporary database.

  • Beyond calling the pure Python calculation directly, how do you verify routing, serialization, and status codes in the FastAPI route layer? Use FastAPI's TestClient (backed by httpx) with app.dependency_overrides[get_store] inside a pytest fixture that cleans up in a finally block. Write dedicated tests asserting both status codes and JSON payloads across every branch of your HTTP contract: 200 happy path, 422 malformed date string, 400 reversed range (start > end), and 404 unknown symbol or empty window. Above TestClient, add a lightweight smoke/end-to-end test that boots Uvicorn against a test database over a real localhost socket to verify ASGI startup hooks, middleware, and authentication headers.

  • If dashboards hammer the endpoint with identical slow queries dozens of times per minute, how would you design and unit test a caching layer? You can cache at three layers depending on deployment: (1) HTTP Cache-Control headers (max-age=60, or long caching for purely historical windows whose closing prices never change) so browsers, CDNs, or reverse proxies skip Python altogether; (2) a shared Redis cache keyed by (symbol, start, end) with a TTL (time-to-live, the number of seconds before a cached entry expires) so multiple Uvicorn worker processes share results; or (3) a bounded in-process TTL cache for single-worker services. Always include every query input (symbol, start, end) in the cache key, keep short TTLs (or event-driven invalidation) whenever end >= today, and unit test the cache deterministically by injecting a monotonic clock (a clock that only moves forward, swapped for a controllable fake clock in tests so you never call time.sleep):

```python import time from datetime import date

class AveragePriceCache: """Bounded-TTL cache keyed by (symbol, start, end) with an injectable clock."""

  def __init__(self, compute_fn, ttl_seconds: float, clock=time.monotonic):
      self.compute_fn = compute_fn
      self.ttl_seconds = ttl_seconds
      self.clock = clock
      # entries maps (symbol, start, end) -> (cached_value, timestamp_stored)
      self.entries: dict[tuple[str, date, date], tuple[float, float]] = {}

  def get(self, symbol: str, start: date, end: date) -> float:
      key = (symbol, start, end)
      now = self.clock()
      if key in self.entries:
          cached_value, stored_at = self.entries[key]
          if now - stored_at < self.ttl_seconds:
              return cached_value
      fresh_value = self.compute_fn(symbol, start, end)
      self.entries[key] = (fresh_value, now)
      return fresh_value

def test_cache_hit_key_isolation_and_ttl_expiry(): calls = [] fake_now = [0.0]

  def fake_compute(symbol, start, end):
      calls.append((symbol, start, end))
      return 254.0

  cache = AveragePriceCache(fake_compute, ttl_seconds=60.0, clock=lambda: fake_now[0])
  d1, d2 = date(2025, 3, 10), date(2025, 3, 12)

  assert cache.get("CORN", d1, d2) == 254.0
  assert cache.get("CORN", d1, d2) == 254.0
  assert len(calls) == 1            # second identical call served from cache

  cache.get("SOYB", d1, d2)
  assert len(calls) == 2            # different symbol misses cache cleanly

  fake_now[0] = 61.0                # advance fake clock past 60s TTL instantly
  cache.get("CORN", d1, d2)
  assert len(calls) == 3            # expired entry recomputes

```

Follow-up questions

Similar questions

More Engelhart interview questions

All 8 Engelhart questions →