Django:如何为对象创建编写模拟/补丁测试?

时间:2018-01-12 12:41:35

标签: django python-3.x unit-testing django-models mocking

我试一试,但是我收到了以下代码的错误消息AttributeError: Mock object has no attribute '_state'。不确定我做错了什么。

在问题的最后请注意我提到我尝试使用补丁,没有更多的运气。

Model.py

class Sale(models.Model):
    from_product = models.ForeignKey(Product)
    from_til = models.ForeignKey(Til)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    create_date = models.DateTimeField('sale_date', editable=False)

    def __str__(self):
        return "%s %s %s" % (self.from_product, self.price, self.create_date)

    def save(self, *args, **kwargs):
        if not self.id:
            self.create_date = timezone.now()

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

test_models.py

class SaleModelTestCase(TestCase):
    @classmethod
    def setUpClass(cls):
        super(SaleModelTestCase, cls).setUpClass()
        cls.product = MagicMock(spec=Product)
        cls.til = MagicMock(spec=Til)
        cls.price = 2.34

    def test_create_sale(self):
        now = datetime.now()
        with mock.patch('django.utils.datetime_safe.datetime') as dt_mock:
            dt_mock.now().return_value = now
            new_sale = Sale.objects.create(from_product=self.product, from_til = self.til,
                                       price=self.price)
            self.assertTrue(isinstance(new_sale, Sale))
            self.assertEqual(new_sale.create_date, now)

我一直在读书并且变得非常困惑。如果我理解正确,我可以将Sale.objects替换为位于@patch('app.models.Sale.objects')之上的class SaleModelTestCase(TestCase):,并包含一个额外的mock_sale参数。

我也给了它一个去,但self.assertTrue(isinstance(new_sale, Sale))返回False is not true

如果有人要告诉我出错的地方,我将非常感激。

0 个答案:

没有答案