بتل کد Battle Codeدارد باز می‌شود…

Step 3: Test the Core چالش 3 از جلسه‌ی 48، سخت

برای هسته‌ی برنامه کلاس TestExpenses(unittest.TestCase) با دقیقاً این پنج تست بنویسید: test_parse_valid (دسته به حروف کوچک تبدیل می‌شود)، test_parse_rejects_negative و test_parse_rejects_bad_date (با assertRaises)، test_total و test_json_round_trip (ذخیره در test.json و بارگذاری، برابری لیست‌ها). تست‌ها را با TextTestRunner(stream=io.StringIO()) اجرا کنید و ran <n> tests و ok: <bool> را در دو خط چاپ کنید. خروجی:
ran 5 tests
ok: True

import io
import json
import unittest
from dataclasses import dataclass
from datetime import date


@dataclass
class Expense:
    day: date
    category: str
    amount: int


def parse_expense(line: str) -> Expense:
    parts = [part.strip() for part in line.split(",")]
    if len(parts) != 3:
        raise ValueError("expected 3 fields")
    raw_day, category, raw_amount = parts
    try:
        day = date.fromisoformat(raw_day)
    except ValueError:
        raise ValueError("bad date") from None
    if not category:
        raise ValueError("missing category")
    try:
        amount = int(raw_amount)
    except ValueError:
        raise ValueError("bad amount") from None
    if amount <= 0:
        raise ValueError("amount must be positive")
    return Expense(day, category.lower(), amount)


class ExpenseBook:
    def __init__(self, expenses: list[Expense] | None = None):
        self.expenses: list[Expense] = list(expenses or [])

    def add(self, expense: Expense) -> None:
        self.expenses.append(expense)

    def total(self) -> int:
        return sum(e.amount for e in self.expenses)

    def by_category(self) -> dict[str, int]:
        totals: dict[str, int] = {}
        for e in self.expenses:
            totals[e.category] = totals.get(e.category, 0) + e.amount
        return dict(sorted(totals.items()))

    def save(self, path: str) -> None:
        rows = [{"day": e.day.isoformat(), "category": e.category, "amount": e.amount}
                for e in self.expenses]
        with open(path, "w", encoding="utf-8") as f:
            json.dump(rows, f, indent=2)

    @classmethod
    def load(cls, path: str) -> "ExpenseBook":
        with open(path, encoding="utf-8") as f:
            rows = json.load(f)
        return cls([Expense(date.fromisoformat(r["day"]), r["category"], r["amount"]) for r in rows])

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 48: پروژه‌ی پایانی: ابزار خط فرمان مدیریت هزینه · چالش بعدی: Step 4: The CLI and Report

بیشتر بخوان: برنامه‌نویسی شی‌گرا در پایتون (کلاس و شیء) با مثال ساده