怎么写django测试意味着失败?

问题描述 投票:43回答:3

我有一个名为Thing的模型,其名称为name,我希望name为char字段,只有3个字符长。

我该怎么写测试?

class TestCase1(TestCase):
    def test1(self):
        thing = Thing(name='1234')

那个测试应该失败。如何正确编写测试以便在该对象失败时测试通过?

django testing tdd
3个回答
80
投票

如果你期望Thing(name ='1234')引发异常,有两种方法可以解决这个问题。

一种是使用Django的assertRaises(实际上来自unittest / unittest2):

def mytest(self):
    self.assertRaises(FooException, Thing, name='1234')

除非Thing(name ='1234')引发FooException错误,否则会失败。另一种方法是捕获预期的异常并在没有发生的情况下引发异常,如下所示:

def mytest(self):
    try:
        thing = Thing(name='1234')
        self.fail("your message here")
    except FooException:
        pass

显然,将FooException替换为您希望通过太长的字符串创建对象所获得的FooException。 ValidationError?

第三个选项(从Python 2.7开始)是使用assertRaises作为上下文管理器,这使得代码更清晰,更易读:

def mytest(self):
    with self.assertRaises(FooException):
        thing = Thing(name='1234')

遗憾的是,这不允许自定义测试失败消息,因此请妥善记录您的测试。有关详细信息,请参阅https://hg.python.org/cpython/file/2.7/Lib/unittest/case.py#l97


3
投票

我目前正在使用expectedFailureunittest装饰器。这与广告一样:在没有错误时失败,在失败时通过。

我使用expectedFailure验证我的自定义断言例程实际工作,而不仅仅是rubberstamp一切正常。

import unittest
from django.test import TestCase

class EmojiTestCase(TestCase):

    @unittest.expectedFailure
    def testCustomAssert(self):
        self.assertHappyFace(':(') # must fail.

但在测试期间打印警告消息。我和Django和Nose一起使用它。哪个others也见过。

/usr/lib64/python3.4/unittest/case.py:525:RuntimeWarning:TestResult没有addExpectedFailure方法,报告为通过RuntimeWarning)

我来这里寻找更好的解决方案,但没有找到。所以我至少想告诉其他人,我一直在努力。


-1
投票

这样的事情应该有效:

thing = Thing.objects.create(name='1234')  
# not sure if you need here .get() or if. create() truncates the field on its own
self.assertEqual(thing.name, '123') # or: self.assertEqual(len(thing.name), 3)

- 但这样的测试看起来很奇怪:-)

另请注意,MySQLdb后端会引发警告异常以通知您截断字符串,因此您可能需要使用assertRaises进行检查。

© www.soinside.com 2019 - 2024. All rights reserved.