难以模拟修补函数返回的对象
Having difficulty mocking object returned by patched function
我在 Django 表单 class 上有一个实例方法,如果成功,return 是来自支付服务的 Python 对象。
该对象有一个 id
属性,然后我将其保留在 Django 模型实例上。
我在将模拟对象 return 正确 .id
属性 时遇到了一些困难。
# 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()
但是:
print donation.charge_id
# returns
u"<MagicMock name='CreditCardForm().charge_customer().id'
我希望看到 donation.charge_id
的 "abc123",但我看到的是 MagicMock
的 unicode 表示。我做错了什么?
通过稍微不同的方式进行修补使其工作:
@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
现在 ID 符合我的预期。不过,我仍然想知道我在之前的代码中做错了什么。
我在 Django 表单 class 上有一个实例方法,如果成功,return 是来自支付服务的 Python 对象。
该对象有一个 id
属性,然后我将其保留在 Django 模型实例上。
我在将模拟对象 return 正确 .id
属性 时遇到了一些困难。
# 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()
但是:
print donation.charge_id
# returns
u"<MagicMock name='CreditCardForm().charge_customer().id'
我希望看到 donation.charge_id
的 "abc123",但我看到的是 MagicMock
的 unicode 表示。我做错了什么?
通过稍微不同的方式进行修补使其工作:
@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
现在 ID 符合我的预期。不过,我仍然想知道我在之前的代码中做错了什么。