在 pytest 夹具中设置类属性

Leo*_*Glt 5 python testing fixtures pytest

我正在为 pytest 制作一个测试类,我想设置一个a将用于多种测试方法的类属性。为此,我使用了一个固定装置set_a,它会自动启动autouse=True,并且只为类 ( scope='class') 调用一次,因为设置a成本很高。这是我的代码:

import pytest
import time


class Test:

    @pytest.fixture(scope='class', autouse=True)
    def set_a(self):
        print('Setting a...')
        time.sleep(5)
        self.a = 1

    def test_1(self):
        print('TEST 1')
        assert self.a == 1

Run Code Online (Sandbox Code Playgroud)

但测试失败并出现以下错误:

========================================================================= FAILURES ==========================================================================
________________________________________________________________________ Test.test_1 ________________________________________________________________________

self = <tests.test_file.Test object at 0x116d953a0>

    def test_1(self):
        print('TEST 1')
>       assert self.a == 1
E       AttributeError: 'Test' object has no attribute 'a'

tests/test_file.py:15: AttributeError
------------------------------------------------------------------- Captured stdout setup -------------------------------------------------------------------
Setting a...
------------------------------------------------------------------- Captured stdout call --------------------------------------------------------------------
TEST 1
Run Code Online (Sandbox Code Playgroud)

即使被调用,它看起来a也没有设置set_a,就像在执行测试时创建了该类的新实例一样。

如果我将夹具范围更改为 ,效果很好function,但我不想a为每个测试进行设置。

知道这里有什么问题吗?

Flo*_*loh 2

您不应该\xe2\x80\x99 设置范围,因为您已经在班级中了。

\n
class Test:\n    @pytest.fixture(autouse=True)\n    def set_a(self):\n        print("Setting a...")\n        time.sleep(5)\n        self.a = 1\n\n    def test_1(self):\n        print("TEST 1")\n        assert self.a == 1\n
Run Code Online (Sandbox Code Playgroud)\n

这就是您应该如何使用scope=class,这意味着它适用于模块中的任何类:

\n
@pytest.fixture(scope="class", autouse=True)\ndef a(request):\n    print("Setting a...")\n    time.sleep(5)\n    request.cls.a = 1\n\n\nclass Test:\n    def test_1(self):\n        print("TEST 1")\n        assert self.a == 1\n
Run Code Online (Sandbox Code Playgroud)\n