【问题标题】:Mocking models used in a Django view with arguments带参数的 Django 视图中使用的模拟模型
【发布时间】:2018-01-31 15:02:00
【问题描述】:

在我的一生中,我无法弄清楚这一点,而且我很难找到有关它的信息。

我有一个 Django 视图,它接受一个作为主键的参数(例如:URL/problem/12)并加载一个包含来自参数模型的信息的页面。

我想模拟我的视图使用的模型进行测试,但我无法弄清楚,这是我尝试过的:

@patch('apps.problem.models.Problem',)
def test_search_response(self, problem, chgbk, dispute):
    problem(problem_id=854, vendor_num=100, chgbk=122)

    request = self.factory.get(reverse('dispute_landing:search'))
    request.user = self.user
    request.usertype = self.usertype

    response = search(request, problem_num=12)

    self.assertTemplateUsed('individual_chargeback_view.html')

但是 - 我永远无法通过测试来实际找到问题编号,就好像模型不存在一样。

【问题讨论】:

    标签: python django unit-testing mocking


    【解决方案1】:

    我认为这是因为如果您模拟整个模型本身,该模型将不存在,因为创建/保存它的任何函数都将被模拟。如果Problem 只是一个没有以任何方式修改过的模拟模型类,那么它对于与数据库、ORM 或任何可以从您的 search() 方法中发现的东西进行交互一无所知。

    您可以采取的一种方法是创建 FactoryBoy 模型工厂,而不是自己模拟模型。由于每次测试运行都会破坏测试数据库,因此这些工厂是创建测试数据的好方法:

    http://factoryboy.readthedocs.io/en/latest/

    您可以像这样启动 ProblemFactory:

    class ProblemFactory(factory.Factory):
        class Meta:
            model = Problem
    
        problem_id = factory.Faker("pyint")
        vendor_num = factory.Faker("pyint")
        chgbk = factory.Faker("pyint")
    

    然后用它来创建一个实际存在于你的数据库中的模型:

    def test_search_response(self, problem, chgbk, dispute):
        problem = ProblemFactory(problem_id=854, vendor_num=100, chgbk=122)
    
        request = self.factory.get(reverse('dispute_landing:search', kwargs={'problem_id':problem.id}))
        request.user = self.user
        request.usertype = self.usertype
    
        response = search(request, problem_num=854)
    
        self.assertTemplateUsed('individual_chargeback_view.html')
    

    【讨论】:

      猜你喜欢
      • 2014-06-06
      • 2019-07-14
      • 1970-01-01
      • 2018-07-04
      • 2021-05-02
      • 1970-01-01
      • 2022-01-02
      • 2016-07-23
      • 2016-11-01
      相关资源
      最近更新 更多