如何在Unittest方法中使用pytest设备

2024-10-01 13:43:40 发布

您现在位置:Python中文网/ 问答频道 /正文

class MyTestCase(unittest.Testcase):
    def setUp(self):
        self.something = True

    @pytest.fixture(autouse=True)
    def MyTestMethod(self, frozentime):
        fn(self.something)  # self.something is NOT defined

如果我使用@pytest.fixture(autouse=True),那么PyTest会产生一些奇怪的行为。PyTest没有在test方法之前调用我的setUp方法,而是跳过setUp并调用MyTestMethod,就好像它是一个PyTest MyTestFunction,这当然不是很好用。在

如何让MyTestMethod使用frozentime夹具,而不忽略应该首先调用的setUp方法。在

^{pr2}$

Tags: 方法selftruepytestdefsetupunittestfixture
1条回答
网友
1楼 · 发布于 2024-10-01 13:43:40

这是因为autouse fixture是在setUp/tearDown方法之前执行的:

Note

Due to architectural differences between the two frameworks, setup and teardown for unittest-based tests is performed during the call phase of testing instead of in pytest‘s standard setup and teardown stages. This can be important to understand in some situations, particularly when reasoning about errors. For example, if a unittest-based suite exhibits errors during setup, pytest will report no errors during its setup phase and will instead raise the error during call.

Source

对于这种行为你无能为力。您可以将fixture相关的代码移出setUp/tearDown方法,例如:如果在类范围fixture中使用self.flag,则可以替换

class Tests(unittest.TestCase):

    def setUp(self):
        self.flag = True

    def tearDown(self):
        self.flag = False

    @pytest.fixture(autouse=True)
    def myfixture(self):
        print(self.flag)

^{pr2}$

或者您可以从fixture中移动所有setUp相关代码:

class Tests(unittest.TestCase):

    def setUp(self):
        self.flag = True

    @pytest.fixture(autouse=True)
    def myfixture(self, somearg):
        fn(self.flag, somearg)

变成

class Tests(unittest.TestCase):

    def setUp(self):
        self.flag = True
        fn(self.flag, self._somearg)

    @pytest.fixture(autouse=True)
    def assign_stuff(self, somearg):
        self._somearg = somearg

相关问题 更多 >