在Pytest中,我正在尝试做以下事情,我需要保存以前的结果并将当前/当前结果与之前的多次迭代进行比较。我做了以下几点:
@pytest.mark.parametrize("iterations",[1,2,3,4,5]) ------> for 5 iterations
@pytest.mark.parametrize("clsObj",[(1,2,3)],indirect = True) ---> here clsObj is the instance. (clsObj.currentVal, here clsObj gets instantiated for every iteration and it is instance of **class func1**)
presentVal = 0
assert clsObj.currentVal > presrntVal
clsObj.currentVal = presentVal
每当我循环presentVal时,如上所述,将得分配给0(预期因为它是局部变量)。相反,上面我试图宣布presentVal
像全球一样,global presentVal
,并且我在我的测试用例之上初始化presentVal
但是没有好转。
class func1():
def __init__(self):
pass
def currentVal(self):
cval = measure() ---------> function from where I get current values
return cval
有人可以建议如何在pytest
或其他最好的方式声明全局变量
提前致谢!
您正在寻找的是一个“夹具”。看看下面的例子,它应该解决你的问题:
import pytest
@pytest.fixture(scope = 'module')
def global_data():
return {'presentVal': 0}
@pytest.mark.parametrize('iteration', range(1, 6))
def test_global_scope(global_data, iteration):
assert global_data['presentVal'] == iteration - 1
global_data['presentVal'] = iteration
assert global_data['presentVal'] == iteration
实际上,您可以跨测试共享一个fixture实例。它适用于更复杂的东西,比如数据库访问对象,但它可能像字典一样微不足道:)
Scope: sharing a fixture instance across tests in a class, module or session