小编Hag*_*ert的帖子

Pytest如何将“设置”固定装置包含在范围“类”中

我正在使用 pytest,通常将我的测试分组为包中模块的“镜像”。为了在我的测试模块中有一个良好的结构,我喜欢将一些测试分组到类中,即使我使用的是 pytest。我\xc2\xb4ve遇到了灯具范围级别的问题。考虑这个最小的例子:

\n\n
import 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\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是有效的,但是“setup”执行两次,即每个测试方法执行一次。我希望每个类实例只执行一次,但是当将固定装置范围更改为“类”时,我得到:

\n\n
FAILED                        [ 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)

python fixtures pytest

5
推荐指数
1
解决办法
5597
查看次数

标签 统计

fixtures ×1

pytest ×1

python ×1