【问题标题】:pytest: How to DRY up similar model manager method testspytest:如何干燥类似的模型管理器方法测试
【发布时间】:2020-08-27 00:25:12
【问题描述】:

我有什么

经理和模型

与经理一起,我可以获得那些已完成、已完成或规定的案例。

from datetime import date

class CaseManager(models.Manager):
    """Define a manager for Case model."""

    def fulfilled(self):
        """Get all cases that will fulfill soon."""
        return self.get_queryset().filter(fulfillment=date.today())

    def caducated(self):
        """Get all cases that will caducate soon."""
        return self.get_queryset().filter(caducity=date.today())

    def prescribed(self):
        """Get all cases that will prescribe soon."""
        return self.get_queryset().filter(prescription=date.today())

class Case(models.Model):
    """Representation of a legal case."""

    fulfillment = models.DateField(verbose_name=_("Fulfillment"), default=date.today)
    caducity = models.DateField(verbose_name=_("Caducity"), default=date.today)
    prescription = models.DateField(verbose_name=_("Prescription"), default=date.today)

    objects = CaseManager()

工厂

创建用于测试的假案例。

class CaseFactory(DjangoModelFactory):
    """Define Case Factory"""

    fulfillment = Faker("date")
    caducity = Faker("date")
    prescription = Faker("date")

    class Meta:
        model = Case

我尝试过的

测试

class TestCasesManagers:
    def test_fulfilled(self):
        case = CaseFactory(fulfillment=date.today())
        assert case in Case.objects.fulfilled()

    def test_caducated(self):
        case = CaseFactory(caducity=date.today())
        assert case in Case.objects.caducated()

    def test_prescribed(self):
        case = CaseFactory(prescription=date.today())
        assert case in Case.objects.prescribed()

问题

使用这种方法,我必须对经理的所有相似但不可扩展的方法重复几乎相同的测试。

我想要什么

  1. 创建 cases 并更改传递给工厂的关键字 args 以创建假模型。
  2. 在assert中调用经理的不同方法,不要重复相同的代码。

【问题讨论】:

    标签: django pytest pytest-django


    【解决方案1】:

    您可以使用对象列表来概括这些:

    class TestCasesManagers:
        kws = [
            ('fulfillment', 'fulfilled'),
            ('caducity', 'caducated'),
            ('prescription', 'prescribed')
        ]
    
        def make_test(ky, mg):
            def f(self):
                case = CaseFactory(**{ky: date.today()})
                assert case in getattr(Case.objects, mg)()
            return f
        for ky, mg in kws:
            locals()[f'test_{mg}'] = make_test(ky, mg)
        del make_test

    因此,您也可以轻松地将额外的 2 元组添加到列表 kws 以测试此组合。这些仍然是单独的测试,因此您可以决定只运行测试一个管理器功能,或者只重试失败的功能。

    【讨论】:

    • 你为什么用这条线del make_test?它的目的是什么?
    猜你喜欢
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 2017-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多