Pytest中的全局变量

5
在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中如何声明全局变量或其他最佳方法吗?谢谢!

作为一个初学者,你可以使用@pytest.mark.parametrize("count",range(5))来改进迭代。不确定这是否对你有帮助。请参考此链接 - Macintosh_89
1个回答

8
你需要的是所谓的“fixture”。看一下下面的例子,它应该能解决你的问题:
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

您可以在测试之间共享夹具实例。它旨在用于更复杂的东西,例如数据库访问对象,但它也可以是一些微不足道的东西,例如字典 :)

范围:在类、模块或会话中共享夹具实例


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接