gpt4 book ai didi

python - 如何将 pytest fixtures 与 Unittest 方法一起使用

转载 作者:太空宇宙 更新时间:2023-11-03 15:44:40 25 4
gpt4 key购买 nike

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 没有在测试方法之前调用我的 setUp 方法,而是跳过 setUp 并调用 MyTestMethod 就好像它是 PyTest MyTestFunction 这当然不能很好地工作。

如何让 MyTestMethod 使用 frozentime fixture 而不忽略应首先调用的 setUp 方法。

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

#@pytest.fixture(autouse=True)
def MyTestMethod(self, frozentime): # Fails on call, because it needs too many arguments.
fn(self.something)

最佳答案

那是因为 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 方法,例如:如果 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)

class Tests(unittest.TestCase):

@pytest.fixture(autouse=True)
def prepare_flag(self):
self.flag = True
yield
self.flag = False

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

或者您可以从 fixtures 中移动所有 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

关于python - 如何将 pytest fixtures 与 Unittest 方法一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50710028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com