为什么 setUpClass(cls): 执行多次?

问题描述:

我正在为 Web 服务实施组件测试.我想使用类方法 setUpClass(cls): 只在开始时启动我的 Web 服务一次,但是 setUpClass(cls): 在我的每个测试之前执行案件.为什么?文档说它在执行测试用例之前只执行一次.有任何想法吗?我使用的是 Python 3.5.

I'm implementing component tests for a web service. I want to use the class method setUpClass(cls): to start my web service only once in the beginning, however setUpClass(cls): is executed before each of my test cases. Why? The documentation says it is executed only once before the test cases are executed. Any ideas? I'm using Python 3.5.

class SomeTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.MyService = ComponentManager.GetMyService()
        cls.MyService.Start()
        return super(SomeTest, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        return super(SomeTest, cls).tearDownClass()

    def test_invalid_request(self):
        response = self.client.SendJSONRequest(Constants.METHOD_POST, '/tile/invalid/', '{}')
        ...

适用于 Visual Studio 源代码的 Python 工具,VS 测试运行器完全独立地运行每个测试用例.

Looking at the Python tools for Visual Studio source code, the VS test runner runs each test case entirely in isolation.

每个测试用例都作为 Python 解释器的单独命令行调用运行(使用 自定义测试启动器,为每个传递模块和测试名称),这就是为每个测试调用类设置和拆卸的原因.Python 从来没有机会一起运行这些测试.

Each test case is run as a separate command-line invocation of the Python interpreter (using a custom test launcher, passing in the module and test name for each), which is why the class setup and teardown are called for each test. Python is never given the opportunity to run these tests together.

如果这对您很重要,您必须向 Python 工具项目提交工单;我目前没有看到测试适配器的相关公开票.

If this matters to you, you'll have to file a ticket with the Python Tools project; I see no relevant open ticket for the test adapter at this time.

或者,使用不同的测试运行程序运行您的测试.您可以使用 内置 unittest命令行,例如:

Alternatively, run your tests with a different test runner. You could use the built-in unittest command line, for example:

python3 -m unittest your_package

或选择任何可用的流行工具.