How to Test Currency Conversion Code Without Live Exchange Rates

5 min read

How to Test Currency Conversion Code Without Live Exchange Rates

To test currency conversion code, take the live rate out of the test. Pass the rate in as an input, fake the HTTP call with saved responses, and keep one small live check outside your normal test run. That gives you tests that are deterministic, fast, and still catch the failures that matter in production.

The usual mistake is a test like assert convert("USD", "EUR", 100) == 92.1. It passes today, fails tomorrow when the market moves, and hides the real bugs: float drift, wrong rounding, and unhandled error responses. This article shows a layered approach with Python and pytest. The same structure works in any language.

Why currency code is hard to test

Three things make conversion tests flaky or misleading:

  • The input moves. A live rate is different every minute, so exact expected values cannot be hard-coded.
  • The network is a dependency. Tests that call an API are slow, can hit rate limits, and consume your quota.
  • The interesting failures are rare. Stale rates, unsupported pairs, and 429 responses almost never happen on demand, so they go untested until they happen in production.

The fix is to separate the code into layers and test each one with the right tool:

LayerWhat it doesHow to test it
Money mathMultiply, round, formatPure unit tests with fixed rates
API clientCall the API, parse the JSONFake HTTP responses (fixtures)
PolicyDecide what to do with stale or failed ratesFixtures for each status and error code
IntegrationProve the real API still matches your assumptionsOne small live smoke test, run on a schedule

Layer 1: test the money math with fixed rates

Make the conversion a pure function. It takes an amount, a rate, and the number of decimal places of the target currency. It does no I/O.

from decimal import Decimal, ROUND_HALF_UP

def convert(amount: Decimal, rate: Decimal, minor_units: int) -> Decimal:
    quantum = Decimal(1).scaleb(-minor_units)
    return (amount * rate).quantize(quantum, rounding=ROUND_HALF_UP)

Now you can pin exact answers, because the rate is an input you control. These numbers are examples, not market data:

import pytest
from decimal import Decimal
from money import convert

@pytest.mark.parametrize("amount, rate, digits, expected", [
    ("125.50", "1.0842", 2, "136.07"),    # 136.0671 rounds down
    ("1.00",   "0.125",  2, "0.13"),      # exact half rounds up, not to even
    ("19.99",  "150.25", 0, "3003"),      # JPY has no minor unit: 3003.4975
    ("0.00",   "1.0842", 2, "0.00"),      # zero stays zero
])
def test_convert(amount, rate, digits, expected):
    result = convert(Decimal(amount), Decimal(rate), digits)
    assert result == Decimal(expected)

Notice the cases. Each one targets a specific bug: an exact half, a zero-decimal currency, a long fractional result. If you want a deeper look at why these matter, see currency conversion rounding without floating-point errors.

Always build expected values from strings. Decimal(0.1) captures the float's error; Decimal("0.1") does not. A test that constructs Decimals from floats can pass while the real code is wrong.

Add invariants, not just examples

A few properties hold for any rate, and they catch bugs that hand-picked examples miss:

  • Converting zero always yields zero.
  • A larger amount never produces a smaller result for the same positive rate.
  • The result always has exactly the target currency's number of decimal places.

With a property-testing library such as Hypothesis, you generate random amounts and rates and assert these hold. Even a loop over a few hundred values works.

Be careful with round-trip tests (USD to EUR and back). Rounding means you will not get the original amount, so assert that the difference is within one minor unit, never exact equality. Our post on the inverse exchange rate explains why the reverse rate is not simply a second quote.

Layer 2: fake the HTTP boundary with saved responses

The client layer should do one job: call the API and return typed values. Inject the HTTP session so tests can replace it.

import os
from decimal import Decimal

class RateUnavailable(Exception):
    def __init__(self, code):
        super().__init__(code)
        self.code = code

def fetch_rate(base, quote, session):
    resp = session.get(
        f"https://api.getratesapi.com/v1/rates/{base}/{quote}",
        headers={"Authorization": f"ApiKey {os.environ['GETRATES_API_KEY']}"},
        timeout=5,
    )
    body = resp.json()
    if resp.status_code != 200:
        raise RateUnavailable(body["code"])
    return {
        "rate": Decimal(body["rate"]),
        "as_of": body["as_of"],
        "status": body["status"],
        "type": body["type"],
    }

A fake session is about ten lines:

class FakeResponse:
    def __init__(self, status_code, body):
        self.status_code = status_code
        self._body = body
    def json(self):
        return self._body

class FakeSession:
    def __init__(self, response):
        self.response = response
        self.calls = []
    def get(self, url, **kwargs):
        self.calls.append((url, kwargs))
        return self.response

Then a fixture per response shape. The success body follows the documented format:

FRESH_DIRECT = {
    "base": "EUR", "quote": "USD", "rate": "1.0842",
    "as_of": "2026-01-02T10:00:00Z", "status": "fresh", "type": "direct",
}

def test_parses_rate_as_decimal(monkeypatch):
    monkeypatch.setenv("GETRATES_API_KEY", "test-key")
    session = FakeSession(FakeResponse(200, FRESH_DIRECT))
    result = fetch_rate("EUR", "USD", session)
    assert result["rate"] == Decimal("1.0842")
    assert isinstance(result["rate"], Decimal)

def test_sends_api_key_header(monkeypatch):
    monkeypatch.setenv("GETRATES_API_KEY", "test-key")
    session = FakeSession(FakeResponse(200, FRESH_DIRECT))
    fetch_rate("EUR", "USD", session)
    _, kwargs = session.calls[0]
    assert kwargs["headers"]["Authorization"] == "ApiKey test-key"

The second test is cheap and prevents a classic regression: someone changes the header name and every request returns unauthorized.

Layer 3: write a fixture for every case your policy handles

The API returns more than the happy path. Rates carry a status (fresh or stale) and a type (direct or derived), and errors come back as JSON with a code. Each of these should have a fixture and a test that proves your code reacts correctly.

Fixtures worth keeping:

  • Fresh direct rate. The baseline.
  • Fresh derived rate. Confirms nothing assumes every pair is quoted directly. For a derived rate, as_of is the oldest input, so do not compare it to "now" with an overly tight tolerance.
  • Stale rate. Stale rates are flagged, not withheld, so your code must read status and apply your policy. See stale exchange rates: how to detect them.
  • Errors by code: invalid_asset_symbol, unsupported_pair, rate_limit_exceeded (with retry_after_seconds), quota_exceeded, temporarily_unavailable.
def test_stale_rate_is_flagged_not_hidden(monkeypatch):
    monkeypatch.setenv("GETRATES_API_KEY", "test-key")
    stale = {**FRESH_DIRECT, "status": "stale"}
    result = fetch_rate("EUR", "USD", FakeSession(FakeResponse(200, stale)))
    assert result["status"] == "stale"

@pytest.mark.parametrize("http_status, code", [
    (400, "invalid_asset_symbol"),
    (404, "unsupported_pair"),
    (429, "rate_limit_exceeded"),
    (503, "temporarily_unavailable"),
])
def test_errors_surface_the_code(monkeypatch, http_status, code):
    monkeypatch.setenv("GETRATES_API_KEY", "test-key")
    body = {"code": code, "message": "ignored", "request_id": "req_test"}
    with pytest.raises(RateUnavailable) as exc:
        fetch_rate("EUR", "USD", FakeSession(FakeResponse(http_status, body)))
    assert exc.value.code == code

Match on code, never on message. Message text is for humans and can change; the code is the stable contract. The error handling guide and the error reference list what to do for each one, and those decisions (retry, show a fallback, fail the checkout) are exactly what these tests should lock in.

Also test the retry logic with a fake clock or an injected sleep function, so a test for retry_after_seconds does not actually wait.

Layer 4: one small live smoke test

Fakes can drift from reality. A live test closes that gap, as long as it stays small and separate from your normal test run.

  • Mark it so it only runs on demand or on a nightly schedule, not on every commit.
  • Use a dedicated API key kept in your CI secret store, so you can rotate or revoke it independently.
  • Assert on shape, never on value: the rate parses as a positive Decimal, status is fresh or stale, type is direct or derived.
  • Keep it to a handful of calls. Single-rate and conversion requests cost 1 request unit each, so a three-call smoke test is cheap. Catalog calls such as /v1/assets are free, which makes them ideal for checking that the currency codes your fixtures use are still supported.
import os, requests, pytest
from decimal import Decimal

@pytest.mark.live
def test_live_rate_shape():
    resp = requests.get(
        "https://api.getratesapi.com/v1/rates/EUR/USD",
        headers={"Authorization": f"ApiKey {os.environ['GETRATES_API_KEY']}"},
        timeout=10,
    )
    assert resp.status_code == 200
    body = resp.json()
    assert Decimal(body["rate"]) > 0
    assert body["status"] in ("fresh", "stale")
    assert body["type"] in ("direct", "derived")

Register the live marker in your pytest config and skip it by default with -m "not live".

What not to assert

A short list of things that make suites brittle:

  • A specific live rate or converted amount.
  • That as_of equals the current minute.
  • The exact text of an error message.
  • A specific number of decimal places in the rate string. Rates are returned unrounded, so your code should round, and your tests should check your rounding, not the API's formatting.

Try it with a free key

You can run the smoke test above on the free plan, with no credit card. Create a free account, try each endpoint in the dashboard playground, and copy real responses into your fixtures. The current rate documentation shows the full response format. When your suite covers money math, fixtures, and one live check, a bad deploy shows up in CI, not in an invoice.

All articles →
Test Currency Conversion Code: Mock Exchange Rates — GetRatesAPI