2017-12-18 10 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に割り当てる取得(それはローカル変数であるため、期待されます)。上記の代わりにpresentValglobal presentValのようにグローバルに宣言しようとしましたが、私もpresentValを私のテストケースの上に初期化しましたが、うまくいきませんでした。

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

は、誰かが事前にpytestまたは他の最良の方法

おかげでグローバル変数を宣言する方法を提案することができます!

+0

(「カウントのような些細なものになることができます"、range(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 

本質的には、テスト全体にわたってフィクスチャインスタンスを共有できます。これは、データベース・アクセス・オブジェクトのようなより複雑なもののために意図だが、それは辞書:)よりよい `@のpytest.mark.parametrizeを使用して、あなたが繰り返しを作ることができるスタータ用

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