I'm trying to mock an instance method of an object contained in another object.
I got two objects
class CreditCard(object):
def charge(self, amount):
if amount < 0:
raise Exception('Invalid amount')
print "charging %d" % amount
class Transaction(object):
def __init__(self, credit_card, amount):
self.amount = amount
self.credit_card = credit_card
self.status = 'PRISTINE'
def pay(self):
self.credit_card.charge(self.amount)
self.status = 'COMPLETE'
This is a simplified example of what i'm trying to acheive
class TestTransaction(TestCase):
def setUp(self):
cc = CreditCard()
t = Transaction(cc, 10)
def test_should_not_mark_transaction_as_complete_if_charge_failed(self):
with mock.patch('t.credit_card.charge') as mock_charge:
mock_charge.side_effect = Exception
with self.assertRaises(Exception):
t.pay()
self.assertEquaL(t.status, 'PRISTINE')
There is a lot of logic inside charge so I'm trying to isolate the transaction test by mocking the charge.
Thanks, python 2.7