测试方法各有不同的设置/拆卸

时间:2014-08-10 22:29:20

标签: python testing

我正在使用许多测试方法测试一个类。但是,每种方法都有一个独特的上下文。然后我按如下方式编写代码:

class TestSomeClass(unittest.TestCase):
    def test_a():
        with a_context() as c:
            pass

    def test_b():
        with b_context() as c:
            pass

    def test_c():
        with c_context() as c:
            pass

但是,上下文管理器与测试用例无关,并生成临时文件。为了在测试失败时不污染文件系统,我想在设置/拆卸场景中使用每个上下文管理器。

我看过鼻子的with_setup,但文档说这只是针对功能,而不是方法。另一种方法是使用setup / teardown函数将测试方法移动到单独的类中。这是一个很好的方法吗?

1 个答案:

答案 0 :(得分:1)

首先,我不确定你为什么没有工作。我编写了一些测试代码,它表明在unittest.main()执行环境下总是会调用 exit 代码。 (注意,我没有测试鼻子,所以也许这就是为什么我无法复制你的失败。)也许你的上下文管理器坏了?

这是我的测试:

import unittest
import contextlib
import sys

@contextlib.contextmanager
def context_mgr():
    print "setting up context"
    try:
        yield
    finally:
        print "tearing down context"

class TestSomeClass(unittest.TestCase):
    def test_normal(self):
        with context_mgr() as c:
            print "normal task"

    def test_raise(self):
        with context_mgr() as c:
            print "raise task"
            raise RuntimeError

    def test_exit(self):
        with context_mgr() as c:
            print "exit task"
            sys.exit(1)

if __name__ == '__main__':
    unittest.main()

通过$ python test_test.py运行,我看到tearing down context用于所有3次测试。

无论如何,要回答你的问题,如果你想为每个测试单独设置和拆卸,那么你需要将每个测试放在自己的类中。您可以设置父类来完成大部分工作,因此没有太多额外的样板:

class TestClassParent(unittest.TestCase):
    context_guard = context_mgr()
    def setUp(self):
        #do common setup tasks here
        self.c = self.context_guard.__enter__()
    def tearDown(self):
        #do common teardown tasks here
        self.context_guard.__exit__(None,None,None)

class TestA(TestClassParent):
    context_guard = context_mgr('A')
    def test_normal(self):
        print "task A"

class TestB(TestClassParent):
    context_guard = context_mgr('B')
    def test_normal(self):
        print "task B"

这会产生输出:

$ python test_test.py 
setting up context: A
task A
tearing down context: A
.setting up context: B
task B
tearing down context: B
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
相关问题