我试图找到一种方法来使用nose在一个类中运行多个测试用例但我需要这样做,其中nose只创建该类的一个实例。该类将测试网络,并且网络的设置需要几分钟,因此需要通过类的一个实例运行所有测试。以下是我想要做的基本示例:
class TestUmbrella(object):
def __init__(self):
log.info('__init__ called')
def run_A(self):
log.info('Test A is running')
def run_B(self):
log.info('Test B is running')
def run_C(self):
log.info('Test C is running')
def run_test(self):
for x in (self.run_A, self.run_B, self.run_C):
yield x
这会产生:
2015-03-19 12:22:31,330: INFO: tests.l3.FooTest2: __init__ called
2015-03-19 12:22:31,331: INFO: tests.l3.FooTest2: __init__ called
2015-03-19 12:22:31,331: INFO: tests.l3.FooTest2: Test A is running
.2015-03-19 12:22:31,331: INFO: tests.l3.FooTest2: __init__ called
2015-03-19 12:22:31,332: INFO: tests.l3.FooTest2: Test B is running
.2015-03-19 12:22:31,332: INFO: tests.l3.FooTest2: __init__ called
2015-03-19 12:22:31,332: INFO: tests.l3.FooTest2: Test C is running
.
----------------------------------------------------------------------
Ran 3 tests in 0.002s
OK
我希望看到的是:
2015-03-19 12:22:31,330: INFO: tests.l3.FooTest2: __init__ called
2015-03-19 12:22:31,331: INFO: tests.l3.FooTest2: Test A is running
2015-03-19 12:22:31,332: INFO: tests.l3.FooTest2: Test B is running
2015-03-19 12:22:31,332: INFO: tests.l3.FooTest2: Test C is running
关于如何做到这一点的任何想法?
答案 0 :(得分:2)
获得所需内容的两种方法: 将unittest.TestCase类与setUpClass一起用于TestUmbrella:
from unittest import TestCase
import logging as log
class TestUmbrella(TestCase):
@classmethod
def setUpClass(cls):
log.info('__init__ called')
def run_A_test(self):
log.info('Test A is running')
def run_B_test(self):
log.info('Test B is running')
def run_C_test(self):
log.info('Test C is running')
请注意,您将无法再动态生成内容,并且必须重命名方法以符合鼻子测试模式。那会给你:
$ nosetests cls_test.py -v
INFO:root:__init__ called
run_A_test (cls_test.TestUmbrella) ... INFO:root:Test A is running
ok
run_B_test (cls_test.TestUmbrella) ... INFO:root:Test B is running
ok
run_C_test (cls_test.TestUmbrella) ... INFO:root:Test C is running
ok
----------------------------------------------------------------------
Ran 3 tests in 0.007s
OK
或者,你可以将你的setup方法注入到类中,但不能作为类初始化的一部分:
import logging as log
class TestUmbrella(object):
def my_setup(self):
log.info('__init__ called')
def run_A(self):
log.info('Test A is running')
def run_B(self):
log.info('Test B is running')
def run_C(self):
log.info('Test C is running')
def run_test(self):
self.my_setup()
for x in (self.run_A, self.run_B, self.run_C):
yield x
最后,如果你真的无法从构造函数中卸载重逻辑,你可以从这样的独立函数运行测试:
def run_test():
tu = TestUmbrella()
for x in (tu.run_A, tu.run_B, tu.run_C):
yield x