import json import tempfile import threading import unittest from pathlib import Path from unittest import mock from virtual_account import AccountError, VirtualAccount class VirtualAccountTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.path = Path(self.temp.name) / 'account.json' self.account = VirtualAccount(self.path, 100) def test_one_balance_fees_reservations_profit_and_deposits(self): a = self.account a.commit('coin:a', {'positions': [1]}, cash_total=-1, reserved=60, event='entry') self.assertEqual(a.view()['free'], 39) with self.assertRaises(AccountError): a.commit('cross', {}, cash_total=-1, reserved=40) a.mark('coin:a', -10) self.assertEqual(a.view()['free'], 29) with self.assertRaises(AccountError): a.adjust(-30, 'withdraw-1') a.adjust(25, 'deposit-1') self.assertEqual(a.view()['realized'], -1) a.commit('coin:a', {'positions': []}, cash_total=9, reserved=0, event='close') self.assertEqual(a.view()['balance'], 134) self.assertEqual(a.view()['free'], 134) self.assertEqual(a.view()['realized'], 9) def test_repeat_adjustment_is_idempotent_across_restart(self): self.account.adjust(50, 'deposit-123') again = VirtualAccount(self.path, 9999) again.adjust(50, 'deposit-123') self.assertEqual(again.view()['balance'], 150) with self.assertRaises(AccountError): again.adjust(60, 'deposit-123') def test_owner_snapshot_and_cash_are_committed_together(self): self.account.commit('a', {'position': 12}, cash_total=-2, reserved=50) again = VirtualAccount(self.path) self.assertEqual(again.restore('a'), {'position': 12}) again.commit('a', {'position': 12}, cash_total=-2, reserved=50) self.assertEqual(again.view()['balance'], 98) with mock.patch('virtual_account.atomic_write_json', side_effect=OSError('disk full')): with self.assertRaises(AccountError): again.commit('a', {'position': None}, cash_total=8, reserved=0) self.assertEqual(again.restore('a'), {'position': 12}) self.assertEqual(again.view()['balance'], 98) self.assertEqual(VirtualAccount(self.path).restore('a'), {'position': 12}) def test_concurrent_entries_cannot_spend_same_free_money(self): barrier = threading.Barrier(2) results = [] def enter(owner): barrier.wait() try: self.account.commit(owner, {'open': True}, cash_total=-1, reserved=60) results.append(True) except AccountError: results.append(False) jobs = [threading.Thread(target=enter, args=(name,)) for name in ('a', 'b')] for job in jobs: job.start() for job in jobs: job.join() self.assertEqual(sorted(results), [False, True]) self.assertEqual(self.account.view()['reserved'], 60) def test_existing_exposure_imported_but_new_risk_blocked(self): self.account.commit('old', {'open': True}, cash_total=0, reserved=150, allow_existing=True) with self.assertRaises(AccountError): self.account.commit('old', {}, cash_total=0, reserved=160, allow_existing=True) self.account.commit('old', {'open': False}, cash_total=-120, reserved=0) self.assertEqual(self.account.view()['balance'], -20) self.assertEqual(self.account.view()['free'], 0) def test_invalid_values_do_not_change_balance(self): for value in (0, True, 'NaN', 'inf', '-inf', 'abc', None, -101): with self.subTest(value=value), self.assertRaises(AccountError): self.account.adjust(value, 'request-123') self.assertEqual(self.account.view()['balance'], 100) def test_corrupt_file_blocks_without_overwriting(self): self.path.write_text('{broken', encoding='utf-8') broken = VirtualAccount(self.path) self.assertTrue(broken.view()['error']) with self.assertRaises(AccountError): broken.adjust(10, 'deposit-321') self.assertEqual(self.path.read_text(), '{broken') def test_stale_open_position_blocks_withdrawal_but_allows_close(self): self.account.commit('a', {}, cash_total=-1, reserved=60) again = VirtualAccount(self.path) self.assertEqual(again.view()['stale'], ['a']) with self.assertRaises(AccountError): again.adjust(-1, 'withdraw-321') again.commit('a', {}, cash_total=-3, reserved=0) self.assertEqual(again.view()['free'], 97) def test_second_instance_cannot_overwrite_prior_adjustment(self): other = VirtualAccount(self.path) self.account.adjust(50, 'first-123') other.adjust(25, 'second-123') self.assertEqual(VirtualAccount(self.path).view()['balance'], 175) def test_external_owner_change_invalidates_old_valuation(self): self.account.commit('x', {}, cash_total=0, reserved=20, unrealized=-10) other = VirtualAccount(self.path) other.commit('x', {'changed': True}, cash_total=0, reserved=20, unrealized=-60) with self.assertRaises(AccountError): self.account.adjust(-70, 'withdraw-xyz') self.assertEqual(self.account.view()['equity'], 40) def test_structurally_corrupt_account_reports_error(self): original = json.loads(self.path.read_text()) for patch in ({'balance': '100'}, {'owners': {'broken': []}}, {'balance': True}): self.path.write_text(json.dumps({**original, **patch}), encoding='utf-8') account = VirtualAccount(self.path) self.assertTrue(account.view()['error']) def test_runtime_lock_prevents_two_engines_for_same_directory(self): from runtime_lock import RuntimeLock path = Path(self.temp.name) / 'engine.lock' with RuntimeLock(path): with self.assertRaises(RuntimeError): with RuntimeLock(path): self.fail('second engine acquired directory') with RuntimeLock(path): pass def test_repeated_large_adjustment_cannot_write_unreadable_totals(self): path = Path(self.temp.name) / 'large-account.json' account = VirtualAccount(path, 0) account.adjust(1e12, 'large-deposit-1') before = path.read_bytes() with self.assertRaises(AccountError): account.adjust(1e12, 'large-deposit-2') self.assertEqual(path.read_bytes(), before) self.assertEqual(account.view()['balance'], 1e12) self.assertEqual(account.view()['error'], '') restarted = VirtualAccount(path) self.assertEqual(restarted.view()['error'], '') self.assertEqual(restarted.view()['balance'], 1e12) self.assertNotIn('large-deposit-2', restarted.data['adjustments']) def test_commit_and_net_deposits_are_validated_before_persistence(self): path = Path(self.temp.name) / 'large-account.json' account = VirtualAccount(path, 1e12) before = path.read_bytes() with self.assertRaises(AccountError): account.commit('profit', {}, cash_total=1, reserved=0) self.assertEqual(path.read_bytes(), before) self.assertIsNone(account.restore('profit')) account.commit('loss', {}, cash_total=-1000, reserved=0) before = path.read_bytes() with self.assertRaises(AccountError): # Balance would stay below the cap, but cumulative net deposits would exceed it. account.adjust(500, 'net-deposits-overflow') self.assertEqual(path.read_bytes(), before) restarted = VirtualAccount(path) self.assertEqual(restarted.view()['error'], '') self.assertEqual(restarted.view()['balance'], 1e12 - 1000) self.assertEqual(restarted.view()['net_deposits'], 1e12) if __name__ == '__main__': unittest.main()