2017-12-18 1041 views
1

在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 

當我做如上我每次循環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或其他最好的辦法

感謝事先聲明全局變量!

+0

爲首發,你可以做出更好的重複使用'@ pytest.mark.parametrize(「計「,範圍(5))'不知道這是否可以幫助你。看到[this](https://stackoverflow.com/questions/42228895/how-to-parametrize-a-pytest-fixture) –

回答

1

你在找什麼叫做「夾具」。看看下面的例子,它應該解決您的問題:

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 

你基本上可以跨越測試共用一個固定的實例。它適用於像數據庫訪問對象更加複雜的東西,但它可以是一些小事就像一本字典:)

Scope: sharing a fixture instance across tests in a class, module or session