我正在使用 pytest,通常将我的测试分组为包中模块的“镜像”。为了在我的测试模块中有一个良好的结构,我喜欢将一些测试分组到类中,即使我使用的是 pytest。我\xc2\xb4ve遇到了灯具范围级别的问题。考虑这个最小的例子:
\n\nimport pytest\n\n\n@pytest.fixture(scope=\'module\')\ndef fixture_a():\n return 2\n\n\nclass TestExample:\n b = 1.\n\n @pytest.fixture(autouse=True, scope=\'function\')\n def add_info(self, fixture_a):\n self.c = self.b * fixture_a\n\n def test_foo(self):\n assert self.c + self.b == 3\n\n def test_bar(self):\n assert self.c * self.b == 2\nRun Code Online (Sandbox Code Playgroud)\n\n这是有效的,但是“setup”执行两次,即每个测试方法执行一次。我希望每个类实例只执行一次,但是当将固定装置范围更改为“类”时,我得到:
\n\nFAILED [ 50%]\ntests\\tests_simple\\test_library\\test_example_sof.py:15 (TestExample.test_foo)\nself = <test_example_sof.TestExample object at 0x0000019A8C9C9CC0>\n\n def test_foo(self):\n> assert self.c + self.b == 3\nE AttributeError: \'TestExample\' object has no attribute \'c\'\n\ntest_example_sof.py:17: AttributeError\nFAILED [100%]\ntests\\tests_simple\\test_library\\test_example_sof.py:18 (TestExample.test_bar)\nself = <test_example_sof.TestExample object at 0x0000019A8C9C9EF0>\n\n def test_bar(self):\n> assert self.c * self.b …Run Code Online (Sandbox Code Playgroud)