pytest 中的全局变量

Kum*_*mar 2 python oop pytest

在 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
Run Code Online (Sandbox Code Playgroud)

当我每次循环时执行上述操作时,presentVal get 的赋值为 0(预期,因为它是局部变量)。相反,我试图在上面声明presentVal为 global like,global presentVal并且我也在presentVal我的测试用例之上初始化,但没有好转。

class func1():
    def __init__(self):
        pass
    def currentVal(self):
        cval = measure()  ---------> function from where I get current values
        return cval
Run Code Online (Sandbox Code Playgroud)

有人可以建议如何以pytest或其他最佳方式声明全局变量

提前致谢!

s-m*_*m-e 5

您正在寻找的东西称为“夹具”。看看下面的例子,它应该可以解决你的问题:

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
Run Code Online (Sandbox Code Playgroud)

您基本上可以跨测试共享夹具实例。它适用于更复杂的东西,如数据库访问对象,但它可能像字典一样微不足道:)

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