Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/tests/test_money_conversion.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
test_money_conversion.py · 8.9 KB · 189 lines
1"""Conversion between denominations (plan/value-accounts-and-denominations-
2spec.md §7): stored rates, and the rules for applying them.
3
4The two that matter: a rate dated after the moment being valued is never
5used (valuing yesterday with today's price silently restates history), and
6a conversion returns its rate alongside its result so the caller can stamp
7it -- a conversion nobody stamped is one that can quietly change later.
8"""
9
10import json
11import pathlib
12from decimal import Decimal
13
14import pytest
15
16import object_money
17import object_records
18
19REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
20FINANCE = REPO_ROOT / "packages" / "app-finance"
21
22
23def setup_env(tmp_path, monkeypatch):
24 data_dir = tmp_path / "data"
25 schema_dir = data_dir / "schemas"
26 schema_dir.mkdir(parents=True)
27 for name in ("denominations", "rates"):
28 (schema_dir / f"{name}.json").write_text(
29 (FINANCE / "schemas" / f"{name}.json").read_text())
30 coll = data_dir / "collections" / name
31 coll.mkdir(parents=True)
32 (coll / "records.tsv").write_text(
33 (FINANCE / "seed" / f"{name}.tsv").read_text())
34 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
35 return data_dir
36
37
38_COUNTER = iter(range(1, 10_000))
39
40
41def add_rate(data_dir, base, quote, rate, as_of, *, kind="spot", source="test",
42 rid=None, period=""):
43 return object_records.create_collection_record(
44 "rates",
45 {"id": rid or f"r-{base}-{quote}-{kind}-{next(_COUNTER)}", "base_code": base,
46 "quote_code": quote, "rate": rate, "as_of": as_of, "kind": kind,
47 "period": period, "source": source, "owner_id": "dan"},
48 base_dir=data_dir)
49
50
51# --- applying a rate ----------------------------------------------------------
52
53def test_convert_produces_exact_minor_units_of_the_target(tmp_path, monkeypatch):
54 data_dir = setup_env(tmp_path, monkeypatch)
55 # 0.05 BTC at 67,432.10 USD/BTC = 3,371.605 USD -> 337161 cents (half-up)
56 assert object_money.convert(5000000, "BTC", "USD", "67432.10",
57 base_dir=data_dir) == 337161
58 # USD -> JPY, and JPY has no minor unit at all
59 assert object_money.convert(150000, "USD", "JPY", "157.25",
60 base_dir=data_dir) == 235875
61 # An amount of the same denomination is unchanged at rate 1.
62 assert object_money.convert(150000, "USD", "USD", "1", base_dir=data_dir) == 150000
63
64
65def test_conversion_refuses_a_nonsense_rate(tmp_path, monkeypatch):
66 data_dir = setup_env(tmp_path, monkeypatch)
67 for bad in ("0", "-1", "not a rate"):
68 with pytest.raises(object_money.MoneyError):
69 object_money.convert(150000, "USD", "EUR", bad, base_dir=data_dir)
70
71
72def test_rounding_happens_once_at_the_end(tmp_path, monkeypatch):
73 """Converting then rounding per line is how a total stops matching the
74 sum of its parts; the rounding here is a single deliberate step."""
75 data_dir = setup_env(tmp_path, monkeypatch)
76 rate = "0.911"
77 lines = [3333, 3333, 3334] # 100.00 USD in three parts
78 converted = [object_money.convert(c, "USD", "EUR", rate, base_dir=data_dir)
79 for c in lines]
80 total_converted = object_money.convert(sum(lines), "USD", "EUR", rate,
81 base_dir=data_dir)
82 # Per-line rounding may differ from the whole by at most a minor unit,
83 # and the test states which number is authoritative: the one the books use.
84 assert abs(sum(converted) - total_converted) <= 1
85
86
87# --- finding the right rate ---------------------------------------------------
88
89def test_lookup_never_uses_a_rate_from_the_future(tmp_path, monkeypatch):
90 """The rule that keeps history from being restated: valuing a July
91 transaction with an August price is time travel."""
92 data_dir = setup_env(tmp_path, monkeypatch)
93 add_rate(data_dir, "BTC", "USD", "60000.00", "2026-07-01T00:00:00Z")
94 add_rate(data_dir, "BTC", "USD", "67432.10", "2026-07-20T00:00:00Z")
95 add_rate(data_dir, "BTC", "USD", "99999.00", "2026-08-01T00:00:00Z")
96
97 found = object_money.find_rate("BTC", "USD", base_dir=data_dir,
98 as_of="2026-07-24T00:00:00Z")
99 assert found["rate"] == "67432.10" # newest at-or-before, not the August one
100
101 early = object_money.find_rate("BTC", "USD", base_dir=data_dir,
102 as_of="2026-06-01T00:00:00Z")
103 assert early is None # nothing yet: say so, do not guess
104
105
106def test_kind_and_source_narrow_the_lookup(tmp_path, monkeypatch):
107 data_dir = setup_env(tmp_path, monkeypatch)
108 add_rate(data_dir, "EUR", "USD", "1.0850", "2026-07-31T23:59:59Z",
109 kind="spot", source="coinbase")
110 add_rate(data_dir, "EUR", "USD", "1.0902", "2026-07-31T23:59:59Z",
111 kind="close", period="2026-07", source="ecb", rid="r-eur-close")
112 add_rate(data_dir, "EUR", "USD", "1.0788", "2026-07-31T23:59:59Z",
113 kind="average", period="2026-07", source="ecb", rid="r-eur-avg")
114
115 close = object_money.find_rate("EUR", "USD", base_dir=data_dir, kind="close")
116 assert close["rate"] == "1.0902" # revaluation uses the close
117 average = object_money.find_rate("EUR", "USD", base_dir=data_dir, kind="average")
118 assert average["rate"] == "1.0788" # translating a period uses the average
119 by_source = object_money.find_rate("EUR", "USD", base_dir=data_dir, source="coinbase")
120 assert by_source["rate"] == "1.0850" # sources disagree; never silently averaged
121
122
123def test_the_inverse_pair_is_derived_and_marked(tmp_path, monkeypatch):
124 data_dir = setup_env(tmp_path, monkeypatch)
125 add_rate(data_dir, "BTC", "USD", "50000.00", "2026-07-01T00:00:00Z")
126 inverse = object_money.find_rate("USD", "BTC", base_dir=data_dir)
127 assert inverse["inverted"] is True # computed, not quoted
128 assert Decimal(inverse["rate"]) == Decimal(1) / Decimal("50000.00")
129 assert object_money.find_rate("USD", "BTC", base_dir=data_dir,
130 allow_inverse=False) is None
131
132
133def test_identity_and_corrupt_rows_are_handled(tmp_path, monkeypatch):
134 data_dir = setup_env(tmp_path, monkeypatch)
135 same = object_money.find_rate("USD", "USD", base_dir=data_dir)
136 assert same["rate"] == "1" and same["source"] == "identity"
137 add_rate(data_dir, "XAU", "USD", "0", "2026-07-01T00:00:00Z") # corrupt
138 add_rate(data_dir, "XAU", "USD", "abc", "2026-07-02T00:00:00Z",
139 rid="r-bad-2") # corrupt
140 add_rate(data_dir, "XAU", "USD", "2400.00", "2026-07-03T00:00:00Z",
141 rid="r-good")
142 good = object_money.find_rate("XAU", "USD", base_dir=data_dir)
143 assert good["rate"] == "2400.00" # unusable rows skipped, not fatal
144
145
146# --- convert_at: the stamping contract ----------------------------------------
147
148def test_convert_at_returns_the_rate_so_the_caller_can_stamp_it(tmp_path, monkeypatch):
149 data_dir = setup_env(tmp_path, monkeypatch)
150 add_rate(data_dir, "BTC", "USD", "67432.10", "2026-07-20T00:00:00Z",
151 source="coinbase")
152 result = object_money.convert_at(5000000, "BTC", "USD", base_dir=data_dir,
153 as_of="2026-07-24T00:00:00Z")
154 assert result["amount_minor"] == 337161
155 # The rate travels with the result precisely so the record that lands
156 # carries the number it was valued at (docs/logic-decisions.md #1).
157 assert result["rate"] == "67432.10"
158 assert result["source"] == "coinbase"
159 assert result["as_of"] == "2026-07-20T00:00:00Z"
160 assert result["inverted"] is False
161
162
163def test_a_conversion_with_no_rate_behind_it_refuses(tmp_path, monkeypatch):
164 """Better to fail than to invent a number nobody can defend later."""
165 data_dir = setup_env(tmp_path, monkeypatch)
166 with pytest.raises(object_money.RateNotFound):
167 object_money.convert_at(5000000, "BTC", "USD", base_dir=data_dir,
168 as_of="2026-07-24T00:00:00Z")
169
170
171def test_a_later_restatement_does_not_erase_what_we_recorded(tmp_path, monkeypatch):
172 """Rates are append-only observations: a source correcting itself is a
173 new row, and the earlier observation stays visible."""
174 data_dir = setup_env(tmp_path, monkeypatch)
175 add_rate(data_dir, "EUR", "USD", "1.0850", "2026-07-20T00:00:00Z",
176 source="ecb", rid="r-first")
177 add_rate(data_dir, "EUR", "USD", "1.0855", "2026-07-20T00:00:00Z",
178 source="ecb", rid="r-restated")
179 rows = object_money.rate_records("EUR", "USD", base_dir=data_dir)
180 assert len(rows) == 2
181 assert {r["rate"] for r in rows} == {"1.0850", "1.0855"}
182
183
184def test_rates_schema_is_append_only_and_seed_is_header_only():
185 schema = json.loads((FINANCE / "schemas" / "rates.json").read_text())
186 assert schema["storage"] == "append"
187 lines = (FINANCE / "seed" / "rates.tsv").read_text().splitlines()
188 assert len(lines) == 1
189 assert lines[0].split("\t") == [f["name"] for f in schema["fields"]]