Saturday, May 29, 2010

Python mock testing with mox module

Python module mox is based on EasyMock. Install mox module:
easy_install mox
Suppose you need to test withdraw operation in ATM (file atm.py):
from datetime import datetime

class Atm:
    def signin(self, account):
        self._account = account

    def signout(self):
        self._account = None

    def withdraw(self, amount):
        try:
            self._account.withdraw(amount)
            self._account.comission(amount * 0.005)
        except ValueError:
            self._account.comission(amount * 0.001)
        return self._account.balance(datetime.now())
When you create a mock object, it is in record mode. You record the behavior by calling the expected methods. Once you are done, switch to replay mode. Here is our test (file moxexample.py):
from datetime import datetime
from atm import Atm
import unittest
from mox import Mox, IgnoreArg, Func

class TestAtm(unittest.TestCase):

    def setUp(self):
        self._mox = Mox()
        self._mock_account = self._mox.CreateMockAnything()
        self._atm = Atm()
        self._atm.signin(self._mock_account)

    def tearDown(self):
        self._atm.signout()
        self._mox.VerifyAll()

    def test_withdraw(self):
        # Arrange
        self._mock_account.deposit(150)
        self._mock_account.withdraw(100)
        self._mock_account.comission(0.5)
        self._mock_account.balance(\
                Func(lambda d: d <= datetime.now()))\
                .AndReturn(49.5)
        self._mox.ReplayAll()

        # Act
        self._mock_account.deposit(150)
        remaining_balance = self._atm.withdraw(100)

        # Assert
        assert remaining_balance == 49.5

    def test_withdraw_insufficient_funds(self):
        # Arrange
        self._mock_account.deposit(50)
        self._mock_account.withdraw(100)\
                .AndRaise(ValueError('Insufficient funds'))
        self._mock_account.comission(0.1)
        self._mock_account.balance(IgnoreArg())\
                .AndReturn(49.9)
        self._mox.ReplayAll()

        # Act
        self._mock_account.deposit(50)
        remaining_balance = self._atm.withdraw(100)

        # Assert
        assert remaining_balance == 49.9

if __name__ == '__main__':
    unittest.main()
Run tests:
python moxexample.py
Read more about mox here.

2 comments :