From d098a84b03277d8172d299c88af16ecf4f8b3fba Mon Sep 17 00:00:00 2001 From: Paul de Raaij Date: Wed, 29 Jul 2026 01:20:50 -0400 Subject: [PATCH] feat: add max 2 decimal places validation to Money --- domain/marketplace/money.py | 6 ++++++ domain/marketplace/price.py | 1 + tests/test_money.py | 23 +++++++++++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/domain/marketplace/money.py b/domain/marketplace/money.py index f269633..cae793b 100644 --- a/domain/marketplace/money.py +++ b/domain/marketplace/money.py @@ -6,6 +6,12 @@ from decimal import Decimal class Money: amount: Decimal + def __post_init__(self): + if self.amount.as_tuple().exponent < -2: + raise ValueError( + f"Money amount cannot have more than 2 decimal places: {self.amount}" + ) + def __add__(self, other): return Money(self.amount + other.amount) diff --git a/domain/marketplace/price.py b/domain/marketplace/price.py index bf3ee57..7ca5a46 100644 --- a/domain/marketplace/price.py +++ b/domain/marketplace/price.py @@ -6,5 +6,6 @@ from domain.marketplace.money import Money @dataclass(frozen=True) class Price(Money): def __post_init__(self): + super().__post_init__() if self.amount < 0: raise ValueError(f"Price cannot be negative: {self.amount}") diff --git a/tests/test_money.py b/tests/test_money.py index ed51dc0..ca28bbb 100644 --- a/tests/test_money.py +++ b/tests/test_money.py @@ -37,3 +37,26 @@ def test_money_substract(): money1 = Money(amount=Decimal("5.00")) money2 = Money(amount=Decimal("3.00")) assert (money1 - money2) == Money(amount=Decimal("2.00")) + + +def test_money_can_not_have_more_than_two_decimals(): + try: + Money(amount=Decimal("1.234")) + assert False, "Should have raised ValueError" + except ValueError: + pass + + +def test_money_allows_two_decimals(): + money = Money(amount=Decimal("1.23")) + assert money.amount == Decimal("1.23") + + +def test_money_allows_one_decimal(): + money = Money(amount=Decimal("1.2")) + assert money.amount == Decimal("1.2") + + +def test_money_allows_no_decimals(): + money = Money(amount=Decimal(1)) + assert money.amount == Decimal(1)