dbn*_*dbn 7 python unit-testing nose nosetests
我有一些Python单元测试,我发现并运行鼻子.我观察到setUpModule(),tearDownModule()和测试模块导入的奇怪排序.我有这个(示例)目录结构:
test1.py
test_dir/test2.py
Run Code Online (Sandbox Code Playgroud)
test1.py和test2.py都是这样的:
import sys
import unittest
def flushwrite(text):
sys.stdout.write(text + '\n')
sys.stdout.flush()
flushwrite("import %s" % __name__)
def setUpModule():
flushwrite("setUp %s" % __name__)
def tearDownModule():
flushwrite("tearDown %s" % __name__)
class Test(unittest.TestCase):
def test1(self):
flushwrite("running %s.test1" % __name__)
Run Code Online (Sandbox Code Playgroud)
当我跑步时nosetests -s test1.py test_dir/test2.py,我看到了这个序列:
这是我期望/渴望的.当我运行nosetests -s test1.py test_dir(使用测试发现来查找test2.py)时,我看到了这个序列:
请注意,test1的tearDown在test2的测试后执行.这意味着当test2运行时系统不处于干净状态!显然,在从大型目录树发现的数千个测试的生产环境中,这可能是一个问题.
这是怎么回事?我误会了什么吗?有没有办法确保在每个测试模块之后运行tearDownModule?
由于您的test2.py文件与 位于同一模块下test1.py,因此两者中的setUpModule和tearDownModule方法都test1.py适用于test2.py.
我只需使用setUpClassandtearDownClass并将它们放在您的测试类中。这样,您将确保 setUp 和tearDown 分别与每个类相关联。