假设我有多组参数:
[
('a', 'b'),
('c', 'd'),
('e', 'f')
]
这组参数不是静态的。它是从另一个函数中获取的。
因此,在我的情况下,使用此参数集对类进行参数化非常方便:
@pytest.mark.parametrize('a, b', [
('a', 'b'),
('c', 'd'),
('e', 'f')
])
class TestClass:
def test_a(self, a, b):
print(a)
def test_b(self, a, b):
print(b)
但是我也有一些情况需要根据这些值c
和a
计算一些第三值b
。值c
的计算是非常耗时的任务,因此我想将其移至固定装置(类似这样):
@pytest.mark.parametrize('a, b', [
('a', 'b'),
('c', 'd'),
('e', 'f')
])
class TestClass:
@pytest.fixture
def calculate_c(a, b):
return a + b
def test_a(self, a, b, calculate_c):
print(a)
def test_b(self, a, b, calculate_c):
print(b)
很明显,对于每组参数,函数calculate_c
的结果都将不同。
我知道pytest中有一个scope="class"
,但是根据我的实验,这不是我所需要的。
有人可以帮我解决这个问题吗?
谢谢!
这似乎有效。当然,如果c的大小很大,并且参数的数量很大,则可能要付出明显的内存成本来存储所有这些参数。不幸的是,您无法一次只存储一个,因为pytest在继续进行test_b之前会使用每个参数对运行test_a。
导入pytest
@pytest.mark.parametrize('a, b', [
('a', 'b'),
('c', 'd'),
('e', 'f')
])
class TestClass:
@classmethod
def calculate_c(self, a, b):
try:
if self.c_map[(a,b)]:
print("didn't calculate")
return self.c_map[(a,b)]
except AttributeError:
self.c_map = {}
except KeyError:
pass
self.c_map[(a, b)] = a+b # do whatever expensive computation here
return self.c_map[(a,b)]
def test_a(self, a, b):
c = self.calculate_c(a, b)
print(a, c)
def test_b(self, a, b):
c = self.calculate_c(a, b)
print(b, c)
产生:
a ab
.c cd
.e ef
.didn't calculate
b ab
.didn't calculate
d cd
.didn't calculate
f ef
.