我对TestCase.setUp()
不满意:如果测试有装饰器,则会在装饰器外调用setUp()
。
我不是python的新手,我可以帮助自己,但我会搜索最佳实践解决方案。
TestCase.setUp()
感觉就像是在Python中引入装饰器之前处理东西的方法。
如果设置应该在测试方法的装饰器中进行,那么设置测试的干净解决方案是什么?
这将是一个解决方案,但setUp()
会被调用两次:
class Test(unittest.TestCase):
def setUp(self):
...
@somedecorator
def test_foo(self):
self.setUp()
示例用例:somedecorator
打开数据库连接,它的工作方式与with语句类似:它不能分为两种方法(setUp()
,tearDown()
)。
更新
somedecorator
来自不同的应用程序。我不想修改它。我可以做一些复制+粘贴,但这不是一个好的解决方案。
答案 0 :(得分:0)
丑?是:
class Test(unittest.TestCase):
def actualSetUp(self):
...
def setUp(self):
if not any('test_foo' in i for i in inspect.stack()):
self.actualSetUp()
@somedecorator
def test_foo(self):
self.actualSetUp()
通过检查当前堆栈并确定我们是否处于名为' test_foo'的任何函数中来工作,因此显然应该是唯一的名称。
可能更干净,只需为此测试创建另一个TestCase
类,您可以不使用setUp
方法。