Bjö*_*lex 6 python testing unit-testing nose nosetests
我目前正在用鼻子写一些功能测试.我正在测试的库操纵一个目录结构.
为了获得可重现的结果,我存储了一个测试目录结构的模板,并在执行测试之前创建了它的副本(我在测试setup函数中执行此操作).这确保了我在测试开始时总是有一个定义良好的状态.
现在我还有两个要求:
这两个要求都可以通过为每个执行的测试创建一个具有不同名称的新副本来解决.出于这个原因,我想访问当前在setup函数中执行的测试的名称,以便我可以适当地命名副本.有没有办法实现这个目标?
一个示例代码示例:
def setup_func(test_name):
print "Setup of " + test_name
def teardown_func(test_name):
print "Teardown of " + test_name
@with_setup(setup_func, teardown_func)
def test_one():
pass
@with_setup(setup_func, teardown_func)
def test_two():
pass
Run Code Online (Sandbox Code Playgroud)
预期产量:
Setup of test_one
Teardown of test_one
Setup of test_two
Teardown of test_two
Run Code Online (Sandbox Code Playgroud)
注入名称作为参数将是最好的解决方案,但我也对其他建议持开放态度.
听起来像self._testMethodName或self.id()应该适合你.这些是unittest.TestCase课堂上的属性和方法.例如:
from django.test import TestCase
class MyTestCase(TestCase):
def setUp(self):
print self._testMethodName
print self.id()
def test_one(self):
self.assertIsNone(1)
def test_two(self):
self.assertIsNone(2)
Run Code Online (Sandbox Code Playgroud)
打印:
...
AssertionError: 1 is not None
-------------------- >> begin captured stdout << ---------------------
test_one
path.MyTestCase.test_one
--------------------- >> end captured stdout << ----------------------
...
AssertionError: 2 is not None
-------------------- >> begin captured stdout << ---------------------
test_two
path.MyTestCase.test_two
--------------------- >> end captured stdout << ----------------------
Run Code Online (Sandbox Code Playgroud)
另见:
希望有所帮助.
我有一个适用于测试功能的解决方案,使用自定义装饰器:
def with_named_setup(setup=None, teardown=None):
def wrap(f):
return with_setup(
lambda: setup(f.__name__) if (setup is not None) else None,
lambda: teardown(f.__name__) if (teardown is not None) else None)(f)
return wrap
@with_named_setup(setup_func, teardown_func)
def test_one():
pass
@with_named_setup(setup_func, teardown_func)
def test_two():
pass
Run Code Online (Sandbox Code Playgroud)
这会重用现有的with_setup装饰器,但将装饰函数的名称绑定到作为参数传递的setup和teardown函数。