The starting state and the expected answer
Consider two fictional share holdings, valued at whole-dollar USD marks. There are no fees, FX conversions or contract multipliers in this example.
| Instrument | Quantity (shares) | Mark (USD per share) | Value (USD) |
|---|---|---|---|
| A | 2 | 100 | 200 |
| B | 3 | 50 | 150 |
| Total | 350 |
Small invented data are useful because every contribution is visible. They do not establish that the fixture resembles a realistic portfolio or covers stressed markets. Testing a missing mark, a short position or a currency mismatch requires explicitly designed cases and a stated contract for each.
Fresh objects prevent accidental test dependencies
setUp(), which unittest calls before each test method. It was executed with Python 3.14.4; it needs only the standard library.import unittest
def holdings_fixture() -> list[dict]:
"""Create fresh fictional share holdings for each test."""
return [
{"instrument": "A", "quantity": 2, "price_usd": 100},
{"instrument": "B", "quantity": 3, "price_usd": 50},
]
def value_usd(holdings: list[dict]) -> int:
"""Value integer share quantities at whole-dollar marks."""
return sum(row["quantity"] * row["price_usd"] for row in holdings)
class HoldingsTest(unittest.TestCase):
def setUp(self):
self.holdings = holdings_fixture()
def test_base_value(self):
self.assertEqual(value_usd(self.holdings), 350)
def test_quantity_change(self):
self.holdings[0]["quantity"] = 3
self.assertEqual(value_usd(self.holdings), 450)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(HoldingsTest)
result = unittest.TestResult()
suite.run(result)
print(result.testsRun, len(result.failures), len(result.errors))
# 2 0 0Cleanup belongs to the fixture too
unittest, addCleanup() registers cleanup callbacks that still run if a later step in setUp() fails; tearDown() runs only after successful setup. Python's TemporaryDirectory can manage a disposable directory through a context manager.For a quant test, prefer an isolated working directory or test database over mutable production state. Record the price timestamp, currency and conventions needed to interpret a stored snapshot. A fixed snapshot makes that experiment repeatable; it does not make the snapshot current or guarantee that the chosen expected answer is economically correct.
Sources
- Python: unittest — fixture terminology, per-test setup and cleanup semantics, including
addCleanup(). - Python: TemporaryDirectory — temporary-directory lifecycle. The current documentation consulted identifies itself as Python 3.15.2; the example above was run on Python 3.14.4.