Reputation: 34593
I have an instance method on a Django form class that returns a Python object from a payment service if successful.
The object has an id
property, which I then persist on a Django model instance.
I'm having some difficulty getting the mocked object to return its .id
property correctly.
# tests.py
class DonationFunctionalTest(TestCase):
def test_foo(self):
with mock.patch('donations.views.CreditCardForm') as MockCCForm:
MockCCForm.charge_customer.return_value = Mock(id='abc123')
# The test makes a post request to the view here.
# The view being tested calls:
# charge = credit_card_form.charge_customer()
# donation.charge_id = charge.id
# donation.save()
However:
print donation.charge_id
# returns
u"<MagicMock name='CreditCardForm().charge_customer().id'
I expected to see "abc123" for the donation.charge_id
, but instead I see a unicode representation of the MagicMock
. What am I doing wrong?
Upvotes: 0
Views: 33
Reputation: 34593
Got it working by doing the patching a bit differently:
@mock.patch('donations.views.CreditCardForm.create_card')
@mock.patch('donations.views.CreditCardForm.charge_customer')
def test_foo(self, mock_charge_customer, mock_create_card):
mock_create_card.return_value = True
mock_charge_customer.return_value = MagicMock(id='abc123')
# remainder of code
Now the id matches what I expect. I'd still like to know what I did wrong on the previous code though.
Upvotes: 1