无法在Django测试中模拟模型方法

4

我希望在我的测试中模拟其中一个模型的方法。这是我要模拟的方法所在的模型:

class Customer(models.Model):
    # Fields ...

    def save(self, *args, **kwargs):

        update_collector = self.id is None

        super(Customer, self).save(*args, **kwargs)

        if update_collector:
            self.send_to_address_book()

    def send_to_address_book(self):  # This is the method I want mocked
        email = self.user.email
        first_name = self.user.first_name
        last_name = self.user.last_name
        print("This is not being mocked")

        investigate_customer.apply_async(
            args=[first_name, last_name, email]
        )

然后,我希望所有继承自CustomerTestCase的测试用例都能对send_to_address_book进行模拟。

class CustomerTestCase(object):
    @mock.patch('accounts.models.Customer.send_to_address_book')
    def create_user_and_customer(self, name, mock_method):
        mock_method.return_value = None
        if not name:
            name = 'test'
        email = name + '@test.si'
        user = User.objects.create_user(name, email)
        customer = Customer.objects.create(user=user)
        return user, customer

然而,当我运行以下测试时,send_to_address_book没有被模拟。
class CustomerQueriesTest(CustomerTestCase, TestCase):
    def setUp(self):
        G(Language, code='en', name='English')
        self.user, self.customer = self.create_user_and_customer()

    def test_queries_running(self):
        profile = self.user.profile
        resp = self.user.profile.queries_running()
        self.assertEqual(resp, 0)
        G(Package)  # using Django dynamic fixtures to create a new Package

我错过了什么?


1
也许这可以给你一些提示:https://docs.python.org/3/library/unittest.mock.html#where-to-patch - diegueus9
1个回答

5

所以,我找到了问题所在。

部分原因是由于DDF的默认设置问题 - 如果一个模型字段是空/NULL,它仍然会默认填充。因此,当使用DDF创建一个Package时,也会因为外键创建一个Customer

问题的第二部分是,PackageCustomer 不在同一模块中,因此@mock.patch('accounts.models.Customer.send_to_address_book') 没有起作用(更多细节请参见Python文档)。我必须添加第二个补丁来处理通过Package创建Customer时的情况:

@mock.patch('billing.models.Customer.send_to_address_book')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接