目の前に僕らの道がある

勉強会とか、技術的にはまったことのメモ

テスト駆動開発入門をPythonで写経してみた。11

11章で実施したこと

  • DollarクラスおよびFrancクラスの削除
  • 冗長なテストの見直し

不必要なテストを削除しています。

money.py

#!/usr/bin/env python
# coding: utf-8
"""テスト駆動開発入門 11章 諸悪の根源
"""

class Money(object):
    def __init__(self, amount, currency):
        self._amount = amount
        self._currency = currency

    def __mul__(self, multiplier):
        return Money(self._amount * multiplier, self.currency())

    @staticmethod
    def dollar(amount):
        return Money(amount, "USD")

    @staticmethod
    def franc(amount):
        return Money(amount, "CHF")

    def currency(self):
        return self._currency

    def __eq__(self, other):
        return self._amount == other._amount and \
                self.currency() == other.currency()

    def __str__(self):
        """デバッグ用出力文字列 原書のtoString()メソッド
        """
        return str(self._amount) + " " + str(self._currency)

    __unicode__ = __str__
    __repr__ = __str__

money_test.py

#!/usr/bin/env python
# coding: utf-8
"""テスト駆動開発入門 11章 諸悪の根源
"""

import unittest
from money import Money

class TestMoney(unittest.TestCase):
    """moneyモジュールのテスト
    """

    def testMultiplication(self):
        """かけ算のテスト
        """
        five = Money.dollar(5)
        self.assertEqual(Money.dollar(10), five * 2)
        self.assertEqual(Money.dollar(15), five * 3)

    def testEuality(self):
        """同値テスト
        """

        self.assert_(    Money.dollar(5) == Money.dollar(5) )
        self.assert_(not Money.dollar(5) == Money.dollar(6) )
        self.assert_(not Money.franc(5)  == Money.dollar(5) )

    def testCurrency(self):
        """通貨単位のテスト
        """

        self.assertEqual("USD", Money.dollar(1).currency() )
        self.assertEqual("CHF", Money.franc(1).currency() )

if __name__ == "__main__":
    unittest.main()