在我的 setUpClass
中,我想一次在数据库中创建一个资源,然后将其用于类中的所有测试。
在 setUpClass
中创建资源后,我想立即对其执行断言。但是,我不确定如何在 setUpClass
中调用断言,因为所有断言函数都是实例方法,而不是类方法。
import unittest
class TestFoo(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.foo = cls.make_foo(name='bar')
# How would I assert that cls.foo['name'] == 'bar'?
# The following does not work, as the assertEquals function is not a class method
# cls.assertEquals(cls.foo['name'], 'bar')
@classmethod
def make_foo(cls, name):
# Calls a POST API to create a resource in the database
return {'name': name}
def test_foo_0(self):
# Do something with cls.foo
pass
def test_foo_1(self):
# do something else with cls.foo
pass
我能想到的唯一替代方法是在 setUpClass 中引发异常:
@classmethod
def setUpClass(cls):
cls.foo = cls.make_foo(name='bar')
if cls.foo['name'] != 'bar':
raise Exception("Failed to create resource, cannot do the tests")
当然,我不想从每个测试中调用断言,因为这只会重复代码。
编辑:我认为这个 workaround 不好,因为失败消息将指向 self.assertFalse(self.flag)
行,而不是 if cls.foo['name'] ~= 'bar'
行。此外,如果您创建了多个资源,则需要多个标志来消除歧义。
flag=False
@classmethod
def setUpClass(cls):
cls.foo = cls.make_foo(name='bar')
if cls.foo['name'] != 'bar':
cls.flag=True
def setUp(self):
self.assertFalse(self.flag)