Files
skuld/tests/test_tax.py
T

308 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Unit tests for the year report of docs/spec.md section 6.
Run with: python3 -m unittest discover -s tests -v
"""
import os
import tempfile
import unittest
import database
import ledger
import rates
import tax
import validation
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,
}
# The seeded year-end rate for tax year 2024, in ore per BTC.
RATE_2024 = 106037489
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()
class TaxTestCase(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_gains_per_method(self):
golden_market()
expected = {
"FIFO": (29500000, 0, 20000000),
"LIFO": (4500000, 0, 45000000),
"HIFO": (0, 500000, 50000000),
}
for method, (gevinst, tap, brukt) in expected.items():
database.set_setting("lot_method", method)
ledger.rebuild()
totals = tax.report(2024)["totals"]
self.assertEqual(
(totals["gevinst_ore"], totals["tap_ore"], totals["brukt_ore"]),
(gevinst, tap, brukt),
method,
)
def test_formue_uses_the_year_end_rate(self):
market_id = golden_market()
ledger.rebuild()
report = tax.report(2024)
# 1,5 BTC times the published 1 060 374,89 kr per BTC
self.assertEqual(report["year_end_price_ore"], RATE_2024)
self.assertEqual(report["totals"]["formue_ore"], 159056234)
self.assertEqual(report["accounts"][0]["sats"], 150000000)
self.assertEqual(report["accounts"][0]["share_percent"], 100.0)
rates.set_rate(rates.year_end_date(2024), 70000000)
self.assertEqual(tax.report(2024)["totals"]["formue_ore"], 105000000)
self.assertEqual(market_id, report["accounts"][0]["market_id"])
def test_income_is_income_and_becomes_the_cost_basis(self):
market_id = create_market("Børs_01")
create_transaction(market_id=market_id, date="2024-05-01", type="income",
leg_in_sats=10000000, value_ore=5000000)
ledger.rebuild()
report = tax.report(2024)
self.assertEqual(report["totals"]["inntekt_ore"], 5000000)
self.assertEqual(report["totals"]["gevinst_ore"], 0)
self.assertEqual(report["totals"]["tap_ore"], 0)
lot = lots_of(market_id)[0]
self.assertEqual(lot["sats_original"], 10000000)
self.assertEqual(lot["cost_ore_original"], 5000000)
# 0,1 BTC times the published rate
self.assertEqual(report["totals"]["formue_ore"], 10603749)
def test_non_taxable_account_stays_out_of_every_total(self):
exchange = create_market("Børs_01")
child = create_market("Barn", kind="other", taxable=0,
custody_market_id=exchange)
create_transaction(market_id=exchange, date="2024-01-10",
leg_in_sats=100000000, leg_out_ore=20000000)
create_transaction(market_id=child, date="2024-02-10",
leg_in_sats=50000000, leg_out_ore=10000000)
create_transaction(market_id=child, date="2024-03-10",
leg_in_ore=15000000, leg_out_sats=50000000)
ledger.rebuild()
report = tax.report(2024)
totals = report["totals"]
self.assertEqual(totals["gevinst_ore"], 0)
self.assertEqual(totals["brukt_ore"], 0)
self.assertEqual(totals["formue_ore"], 106037489)
self.assertEqual([row["name"] for row in report["accounts"]], ["Børs_01"])
self.assertEqual(len(report["non_taxable"]), 1)
child_row = report["non_taxable"][0]
self.assertEqual(child_row["name"], "Barn")
self.assertEqual(child_row["sats"], 0)
self.assertEqual(child_row["gevinst_ore"], 5000000)
self.assertEqual(report["skattemelding"]["gevinst"], 0)
def test_custody_totals_sum_the_custodian_and_its_dependants(self):
exchange = create_market("Børs_01")
child = create_market("Barn", kind="other", taxable=0, custody_market_id=exchange)
create_transaction(market_id=exchange, date="2024-01-10",
leg_in_sats=150000000, leg_out_ore=30000000)
create_transaction(market_id=child, date="2024-01-10",
leg_in_sats=50000000, leg_out_ore=10000000)
ledger.rebuild()
rows = tax.report(2024)["custody_totals"]
self.assertEqual([row["name"] for row in rows], ["Børs_01"])
self.assertEqual(rows[0]["sats"], 200000000)
def test_fees_follow_section_3_2(self):
market_id = create_market("Børs_01")
# A buy fee in NOK raises the cost basis.
create_transaction(market_id=market_id, date="2024-01-10",
leg_in_sats=100000000, leg_out_ore=20000000, fee_ore=50000)
# A buy fee in sats lowers the sats received, the cost stays.
create_transaction(market_id=market_id, date="2024-02-10",
leg_in_sats=100000000, leg_out_ore=20000000, fee_sats=100000)
# A sell fee in NOK lowers the proceeds.
create_transaction(market_id=market_id, date="2024-03-10",
leg_in_ore=30000000, leg_out_sats=100000000, fee_ore=100000)
ledger.rebuild()
lots = lots_of(market_id)
self.assertEqual(lots[0]["sats_original"], 100000000)
self.assertEqual(lots[0]["cost_ore_original"], 20050000)
self.assertEqual(lots[1]["sats_original"], 99900000)
self.assertEqual(lots[1]["cost_ore_original"], 20000000)
# The buy must not have consumed anything: its sats fee only lowered the
# sats it received, so the second lot is untouched.
self.assertEqual(lots[0]["sats_remaining"], 0)
self.assertEqual(lots[1]["sats_remaining"], 99900000)
# Proceeds 300 000 kr minus the 1 000 kr fee, cost 200 500 kr (FIFO).
self.assertEqual(tax.report(2024)["totals"]["gevinst_ore"], 9850000)
def test_gift_received_sets_the_cost_basis(self):
market_id = create_market("Lommebok", kind="wallet")
create_transaction(market_id=market_id, date="2024-03-01", type="gift_received",
leg_in_sats=50000000, value_ore=15000000)
ledger.rebuild()
report = tax.report(2024)
self.assertEqual(report["totals"]["inntekt_ore"], 0)
self.assertEqual(report["totals"]["gevinst_ore"], 0)
self.assertEqual(lots_of(market_id)[0]["cost_ore_original"], 15000000)
self.assertEqual(report["totals"]["formue_ore"], 53018745)
def test_netto_tax_and_the_tax_return_block(self):
golden_market()
ledger.rebuild()
report = tax.report(2024)
totals = report["totals"]
self.assertEqual(totals["netto_ore"], 29500000)
self.assertEqual(totals["skatt_ore"], 6490000)
self.assertEqual(totals["lot_method"], "FIFO")
self.assertEqual(totals["admin_cost_ore"], 0)
block = report["skattemelding"]
self.assertEqual(block["formue"], totals["formue_ore"])
self.assertEqual(block["gevinst"], 29500000)
self.assertEqual(block["tap"], 0)
self.assertEqual(block["inntekt"], 0)
self.assertEqual(block["accounts"], ["Børs_01"])
self.assertIn("skattepliktige", block["note"])
def test_admin_cost_is_counted_on_its_own(self):
golden_market()
create_transaction(market_id=None, date="2024-12-01", type="admin_cost",
leg_out_sats=50000)
ledger.rebuild()
report = tax.report(2024)
totals = report["totals"]
for key in ("formue_ore", "gevinst_ore", "tap_ore", "brukt_ore", "netto_ore",
"inntekt_ore", "skatt_ore", "formuesskatt_ore", "admin_cost_sats",
"admin_cost_ore", "lot_method"):
self.assertIn(key, totals)
self.assertEqual(totals["admin_cost_sats"], 50000)
self.assertEqual(totals["admin_cost_ore"], 0)
self.assertEqual(totals["netto_ore"], 29500000)
# The account row is untouched by a cost that has no account.
self.assertEqual([row["name"] for row in report["accounts"]], ["Børs_01"])
self.assertEqual(report["accounts"][0]["sats"], 150000000)
self.assertEqual(report["accounts"][0]["gevinst_ore"], 29500000)
self.assertEqual(report["accounts"][0]["brukt_ore"], 20000000)
def test_admin_cost_is_deducted_only_when_the_setting_is_on(self):
golden_market()
create_transaction(market_id=None, date="2024-12-01", type="admin_cost",
leg_out_sats=50000)
ledger.rebuild()
self.assertEqual(tax.report(2024)["totals"]["admin_cost_ore"], 0)
database.set_setting("deduct_admin_costs", "1")
totals = tax.report(2024)["totals"]
# 50 000 sats at the 2024 rate of 1 060 374,89 kr per BTC
self.assertEqual(totals["admin_cost_ore"], 53019)
self.assertEqual(totals["netto_ore"], 29500000 - 53019)
self.assertEqual(totals["skatt_ore"], 6478336)
def test_btc_price_of_a_buy_and_a_sale(self):
buy = {"type": "trade", "leg_in_sats": 1000, "leg_in_ore": None,
"leg_out_sats": None, "leg_out_ore": 1000, "value_ore": None}
sale = {"type": "trade", "leg_in_sats": None, "leg_in_ore": 50000000,
"leg_out_sats": 1000000, "leg_out_ore": None, "value_ore": None}
# 1 000 sats for 10 kr, and 1 000 000 sats for 500 000 kr.
self.assertEqual(tax.btc_price_ore(buy), 100000000)
self.assertEqual(tax.btc_price_ore(sale), 5000000000)
def test_btc_price_is_none_where_there_is_none(self):
for tx_type in ("transfer_out", "transfer_in", "gift_given", "admin_cost"):
self.assertIsNone(tax.btc_price_ore({
"type": tx_type, "leg_in_sats": None, "leg_in_ore": None,
"leg_out_sats": 1000, "leg_out_ore": None, "value_ore": 1000000,
}))
if __name__ == "__main__":
unittest.main()