299 lines
12 KiB
Python
299 lines
12 KiB
Python
"""Unit tests for the lot ledger of docs/spec.md section 5.
|
||
|
||
Run with: python3 -m unittest discover -s tests -v
|
||
Every test makes its own database in a temporary directory, so the tests never
|
||
touch the development database.
|
||
"""
|
||
|
||
import os
|
||
import tempfile
|
||
import unittest
|
||
|
||
import database
|
||
import ledger
|
||
|
||
TRANSACTION_DEFAULTS = {
|
||
"market_id": None,
|
||
"date": "2024-01-01",
|
||
"type": "trade",
|
||
"taxable": 1,
|
||
"note": "",
|
||
"leg_in_sats": None,
|
||
"leg_in_ore": None,
|
||
"leg_out_sats": None,
|
||
"leg_out_ore": None,
|
||
"value_ore": None,
|
||
"fee_sats": 0,
|
||
"to_market_id": None,
|
||
"transfer_group": None,
|
||
"generated": 0,
|
||
}
|
||
|
||
|
||
def create_market(name, kind="exchange", taxable=1, custody_market_id=None):
|
||
conn = database.connect()
|
||
try:
|
||
with conn:
|
||
cursor = conn.execute(
|
||
"INSERT INTO markets (name, kind, taxable, custody_market_id)"
|
||
" VALUES (?, ?, ?, ?)",
|
||
(name, kind, taxable, custody_market_id),
|
||
)
|
||
return cursor.lastrowid
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def create_transaction(**fields):
|
||
"""Insert one transaction row. Columns not given keep their default."""
|
||
values = dict(TRANSACTION_DEFAULTS)
|
||
unknown = set(fields) - set(values)
|
||
if unknown:
|
||
raise AssertionError("unknown transaction field(s): %s" % sorted(unknown))
|
||
values.update(fields)
|
||
columns = ", ".join(values)
|
||
placeholders = ", ".join("?" for _ in values)
|
||
conn = database.connect()
|
||
try:
|
||
with conn:
|
||
cursor = conn.execute(
|
||
"INSERT INTO transactions (%s, created_at, updated_at)"
|
||
" VALUES (%s, '2024-01-01T00:00:00+00:00', '2024-01-01T00:00:00+00:00')"
|
||
% (columns, placeholders),
|
||
tuple(values.values()),
|
||
)
|
||
return cursor.lastrowid
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def golden_market():
|
||
"""The four transactions of docs/spec.md section 6.4 on one account.
|
||
|
||
A leg carries one currency only: a buy receives sats on leg_in and gives NOK
|
||
on leg_out, a sell receives NOK on leg_in and gives sats on leg_out.
|
||
"""
|
||
market_id = create_market("Børs_01")
|
||
create_transaction(market_id=market_id, date="2024-01-10",
|
||
leg_in_sats=100000000, leg_out_ore=20000000)
|
||
create_transaction(market_id=market_id, date="2024-04-10",
|
||
leg_in_sats=100000000, leg_out_ore=50000000)
|
||
create_transaction(market_id=market_id, date="2024-08-10",
|
||
leg_in_sats=50000000, leg_out_ore=20000000)
|
||
# The 5 000 kr fee of docs/spec.md section 6.4 is folded into the amount the
|
||
# owner types: 500 000 − 5 000 = 495 000 kr (section 3.2).
|
||
create_transaction(market_id=market_id, date="2024-11-10",
|
||
leg_in_ore=49500000, leg_out_sats=100000000)
|
||
return market_id
|
||
|
||
|
||
def lots_of(market_id):
|
||
conn = database.connect()
|
||
try:
|
||
return [dict(row) for row in conn.execute(
|
||
"SELECT * FROM lots WHERE market_id = ? ORDER BY id", (market_id,)
|
||
).fetchall()]
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def consumptions(tx_id):
|
||
conn = database.connect()
|
||
try:
|
||
return [dict(row) for row in conn.execute(
|
||
"SELECT * FROM lot_consumptions WHERE tx_id = ? ORDER BY id", (tx_id,)
|
||
).fetchall()]
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def snapshot():
|
||
conn = database.connect()
|
||
try:
|
||
lots = [tuple(row) for row in conn.execute(
|
||
"SELECT * FROM lots ORDER BY id").fetchall()]
|
||
consumed = [tuple(row) for row in conn.execute(
|
||
"SELECT * FROM lot_consumptions ORDER BY id").fetchall()]
|
||
finally:
|
||
conn.close()
|
||
return lots, consumed
|
||
|
||
|
||
class LedgerTestCase(unittest.TestCase):
|
||
def setUp(self):
|
||
self._directory = tempfile.TemporaryDirectory()
|
||
os.environ["DATABASE_PATH"] = os.path.join(self._directory.name, "test.sqlite3")
|
||
|
||
def tearDown(self):
|
||
os.environ.pop("DATABASE_PATH", None)
|
||
self._directory.cleanup()
|
||
|
||
def test_golden_example_consumes_by_method(self):
|
||
market_id = golden_market()
|
||
expected = {"FIFO": 20000000, "LIFO": 45000000, "HIFO": 50000000}
|
||
for method, cost_ore in expected.items():
|
||
database.set_setting("lot_method", method)
|
||
ledger.rebuild()
|
||
rows = consumptions(4)
|
||
self.assertEqual(sum(row["sats"] for row in rows), 100000000, method)
|
||
self.assertEqual(sum(row["cost_ore"] for row in rows), cost_ore, method)
|
||
self.assertEqual(
|
||
sum(lot["sats_remaining"] for lot in lots_of(market_id)), 150000000, method
|
||
)
|
||
|
||
def test_partial_consumption_rounds_and_keeps_every_ore(self):
|
||
market_id = create_market("Lommebok", kind="wallet")
|
||
create_transaction(market_id=market_id, date="2024-01-01",
|
||
leg_in_sats=3, leg_out_ore=100)
|
||
first = create_transaction(market_id=market_id, date="2024-02-01",
|
||
leg_in_ore=50, leg_out_sats=1)
|
||
second = create_transaction(market_id=market_id, date="2024-03-01",
|
||
leg_in_ore=50, leg_out_sats=1)
|
||
third = create_transaction(market_id=market_id, date="2024-04-01",
|
||
leg_in_ore=50, leg_out_sats=1)
|
||
ledger.rebuild()
|
||
self.assertEqual([row["cost_ore"] for row in consumptions(first)], [33])
|
||
self.assertEqual([row["cost_ore"] for row in consumptions(second)], [34])
|
||
self.assertEqual([row["cost_ore"] for row in consumptions(third)], [33])
|
||
lot = lots_of(market_id)[0]
|
||
self.assertEqual((lot["sats_remaining"], lot["cost_ore_remaining"]), (0, 0))
|
||
|
||
def test_consuming_across_three_lots(self):
|
||
market_id = create_market("Børs_01")
|
||
for day, ore in (("2024-01-01", 100), ("2024-02-01", 200), ("2024-03-01", 300)):
|
||
create_transaction(market_id=market_id, date=day, leg_in_sats=1, leg_out_ore=ore)
|
||
sale = create_transaction(market_id=market_id, date="2024-04-01",
|
||
leg_in_ore=1000, leg_out_sats=3)
|
||
ledger.rebuild()
|
||
rows = consumptions(sale)
|
||
self.assertEqual([row["sats"] for row in rows], [1, 1, 1])
|
||
self.assertEqual([row["cost_ore"] for row in rows], [100, 200, 300])
|
||
self.assertEqual([row["auto"] for row in rows], [1, 1, 1])
|
||
|
||
def test_hand_picked_lot_overrides_the_method(self):
|
||
market_id = create_market("Børs_01")
|
||
bought = [
|
||
create_transaction(market_id=market_id, date=day, leg_in_sats=1, leg_out_ore=ore)
|
||
for day, ore in (("2024-01-01", 100), ("2024-02-01", 200), ("2024-03-01", 300))
|
||
]
|
||
sale = create_transaction(market_id=market_id, date="2024-04-01",
|
||
leg_in_ore=1000, leg_out_sats=2)
|
||
conn = database.connect()
|
||
try:
|
||
with conn:
|
||
conn.execute(
|
||
"INSERT INTO lot_picks (tx_id, origin_tx_id, origin_seq, sats)"
|
||
" VALUES (?, ?, 0, 1)",
|
||
(sale, bought[1]),
|
||
)
|
||
finally:
|
||
conn.close()
|
||
ledger.rebuild()
|
||
rows = consumptions(sale)
|
||
self.assertEqual([row["auto"] for row in rows], [0, 1])
|
||
self.assertEqual([row["cost_ore"] for row in rows], [200, 100])
|
||
|
||
def test_shortfall_names_the_missing_sats(self):
|
||
market_id = create_market("Lommebok", kind="wallet")
|
||
create_transaction(market_id=market_id, date="2024-01-01",
|
||
leg_in_sats=1, leg_out_ore=100)
|
||
create_transaction(market_id=market_id, date="2024-02-01",
|
||
leg_in_ore=100, leg_out_sats=2)
|
||
with self.assertRaises(ledger.LedgerError) as caught:
|
||
ledger.rebuild()
|
||
self.assertIn("1 sats", str(caught.exception))
|
||
|
||
def test_transfer_mirrors_date_and_cost(self):
|
||
source = create_market("Børs_01")
|
||
destination = create_market("Lommebok", kind="wallet")
|
||
# 2,0 BTC for 400 000 kr: 0,2 ore per sat.
|
||
create_transaction(market_id=source, date="2024-01-10",
|
||
leg_in_sats=200000000, leg_out_ore=40000000)
|
||
transfer = create_transaction(market_id=source, date="2024-06-01",
|
||
type="transfer_out", leg_out_sats=100000000,
|
||
fee_sats=1000,
|
||
to_market_id=destination, transfer_group="group-1")
|
||
# The API writes the generated transfer_in row together with the transfer_out:
|
||
# the sent sats arrive in full and it carries no fee of its own.
|
||
create_transaction(market_id=destination, date="2024-06-01", type="transfer_in",
|
||
leg_in_sats=100000000, fee_sats=0,
|
||
to_market_id=source, transfer_group="group-1", generated=1)
|
||
ledger.rebuild()
|
||
|
||
# The source gives up the sent sats plus the fee, at the same cost per sat.
|
||
self.assertEqual(sum(row["sats"] for row in consumptions(transfer)), 100001000)
|
||
self.assertEqual(sum(row["cost_ore"] for row in consumptions(transfer)), 20000200)
|
||
self.assertEqual(ledger.sats_in_market(source, "2024-12-31"), 99999000)
|
||
self.assertEqual(ledger.sats_in_market(destination, "2024-12-31"), 100000000)
|
||
|
||
source_lot = lots_of(source)[0]
|
||
mirror = lots_of(destination)[0]
|
||
self.assertEqual(source_lot["sats_remaining"], 99999000)
|
||
self.assertEqual(source_lot["cost_ore_remaining"], 19999800)
|
||
self.assertEqual(mirror["acquired_date"], "2024-01-10")
|
||
self.assertEqual(mirror["source_lot_id"], source_lot["id"])
|
||
self.assertEqual(mirror["sats_original"], 100000000)
|
||
# The cost share of the 1 000 fee sats (200 ore) is not mirrored.
|
||
self.assertEqual(mirror["cost_ore_original"], 20000000)
|
||
|
||
# Both sides keep the price of the source lot: 200 000 kr per BTC.
|
||
self.assertEqual(
|
||
[lot["btc_price_ore"] for lot in ledger.candidate_lots(source, "2024-12-31")],
|
||
[20000000],
|
||
)
|
||
self.assertEqual(
|
||
[lot["btc_price_ore"]
|
||
for lot in ledger.candidate_lots(destination, "2024-12-31")],
|
||
[20000000],
|
||
)
|
||
|
||
def test_rebuild_twice_gives_the_same_ledger(self):
|
||
golden_market()
|
||
ledger.rebuild()
|
||
first = snapshot()
|
||
ledger.rebuild()
|
||
self.assertEqual(snapshot(), first)
|
||
|
||
def test_holdings_before_and_after_the_sale(self):
|
||
market_id = golden_market()
|
||
ledger.rebuild()
|
||
self.assertEqual(ledger.sats_in_market(market_id, "2024-11-09"), 250000000)
|
||
self.assertEqual(ledger.sats_in_market(market_id, "2024-11-10"), 150000000)
|
||
self.assertEqual(ledger.holdings_at("2024-12-31"), {market_id: 150000000})
|
||
self.assertEqual(ledger.sats_on_hand(), {market_id: 150000000})
|
||
|
||
def test_candidate_lots_carry_the_bitcoin_price(self):
|
||
market_id = golden_market()
|
||
ledger.rebuild()
|
||
lots = ledger.candidate_lots(market_id, "2024-12-31")
|
||
# April: 500 000 kr for 1,0 BTC. August: 200 000 kr for 0,5 BTC.
|
||
self.assertEqual(
|
||
[lot["btc_price_ore"] for lot in lots], [50000000, 40000000]
|
||
)
|
||
self.assertEqual([lot["sats_remaining"] for lot in lots], [100000000, 50000000])
|
||
|
||
def test_admin_cost_consumes_nothing(self):
|
||
market_id = golden_market()
|
||
cost = create_transaction(market_id=None, date="2024-12-01", type="admin_cost",
|
||
leg_out_ore=50000)
|
||
ledger.rebuild()
|
||
self.assertEqual(consumptions(cost), [])
|
||
self.assertEqual(ledger.holdings_at("2024-12-31"), {market_id: 150000000})
|
||
self.assertEqual(ledger.sats_on_hand(), {market_id: 150000000})
|
||
self.assertEqual(
|
||
sum(lot["sats_remaining"] for lot in lots_of(market_id)), 150000000
|
||
)
|
||
|
||
def test_rebuild_stays_the_same_with_an_admin_cost(self):
|
||
golden_market()
|
||
create_transaction(market_id=None, date="2024-12-01", type="admin_cost",
|
||
leg_out_sats=50000)
|
||
ledger.rebuild()
|
||
first = snapshot()
|
||
ledger.rebuild()
|
||
self.assertEqual(snapshot(), first)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main()
|