8

我有一些我正在用鼻子发现和运行的 Python 单元测试。我观察到 setUpModule()、tearDownModule() 和测试模块导入的一些奇怪顺序。我有这个(示例)目录结构:

test1.py
test_dir/test2.py

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__)

当我运行时nosetests -s test1.py test_dir/test2.py,我看到这个序列:

  1. 导入测试1
  2. 导入测试2
  3. 设置测试1
  4. 运行 test1.test1
  5. 拆解测试1
  6. 设置测试2
  7. 运行 test2.test1
  8. 拆解测试2

这是我所期望/渴望的。当我运行nosetests -s test1.py test_dir(使用测试发现来查找 test2.py)时,我看到了这个序列:

  1. 导入测试1
  2. 导入测试2
  3. 设置测试1
  4. 运行 test1.test1
  5. 设置测试2
  6. 运行 test2.test1
  7. 拆解测试2
  8. 拆解测试1

请注意,test1 的 tearDown 在 test2 的测试之后执行。这意味着test2运行时系统不处于干净状态!显然,在从大型目录树中发现的数千个测试的生产环境中,这可能是一个问题。

这是怎么回事?我是不是误会了什么?有没有办法确保 tearDownModule 在每个测试模块之后运行?

4

1 回答 1

3

Since your test2.py file is under the same module as test1.py, the setUpModule and tearDownModule methods from test1.py both apply to test2.py.

I'd just use setUpClass and tearDownClass and place them inside your Test class. This way you will make sure that the setUp and tearDown are tied to each class separately.

于 2014-03-03T21:11:27.780 回答