如何在pytest中参数化setup_method
How to parameterize a setup_method in pytest
我有这样的测试:
@pytest.mark.parametrize("dtype", (float32, bfloat16))
class TestA:
def setup_method(self, method=None, dtype=float32):
if dtype == float32:
self.a = 10
else
self.a = 5
def test1(self, dtype):
...
test1 总是使用 self.a = 10
,即使 dtype 是 bfloat16。有人知道如何使用正确的值 运行 吗?
简而言之,您不能使用 xunit style setup/teardown, it doesn't support pytest fixtures。
您可以使用 pytest
设置和拆卸机制(xunit 样式文档的 header 中也推荐该机制)
@pytest.mark.parametrize("dtype", (float32, float16))
class TestA:
@pytest.fixture(scope='function', autouse=True)
def setup_and_teardown(self, dtype):
print('setup')
if isinstance(dtype, float32):
self.a = 10
else:
self.a = 5
print(dtype)
yield
print('teardown')
def test1(self, dtype):
print('test1')
输出:
TestA::test1[float32]
setup
<class 'numpy.float32'>
PASSED [ 50%]test1
teardown
TestA::test1[float16]
setup
<class 'numpy.float16'>
PASSED [100%]test1
teardown
我有这样的测试:
@pytest.mark.parametrize("dtype", (float32, bfloat16))
class TestA:
def setup_method(self, method=None, dtype=float32):
if dtype == float32:
self.a = 10
else
self.a = 5
def test1(self, dtype):
...
test1 总是使用 self.a = 10
,即使 dtype 是 bfloat16。有人知道如何使用正确的值 运行 吗?
简而言之,您不能使用 xunit style setup/teardown, it doesn't support pytest fixtures。
您可以使用 pytest
设置和拆卸机制(xunit 样式文档的 header 中也推荐该机制)
@pytest.mark.parametrize("dtype", (float32, float16))
class TestA:
@pytest.fixture(scope='function', autouse=True)
def setup_and_teardown(self, dtype):
print('setup')
if isinstance(dtype, float32):
self.a = 10
else:
self.a = 5
print(dtype)
yield
print('teardown')
def test1(self, dtype):
print('test1')
输出:
TestA::test1[float32]
setup
<class 'numpy.float32'>
PASSED [ 50%]test1
teardown
TestA::test1[float16]
setup
<class 'numpy.float16'>
PASSED [100%]test1
teardown