Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python pytest中的全局变量_Python_Oop_Pytest - Fatal编程技术网

Python pytest中的全局变量

Python pytest中的全局变量,python,oop,pytest,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. (clsOb

在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 get赋值给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实例。它适用于更复杂的东西,比如数据库访问对象,但也可以是一些琐碎的东西,比如字典:)


对于初学者,您可以使用
@pytest.mark.parametrize(“count”,range(5))
来改进迭代。看见