Reputation: 69
In Pytest I'm trying to do following thing, where I need to save previous result and compare current/present result with previous for multiple iterations. I've done as following ways:
@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
When I do as above every time I loop presentVal get's assign to 0 (expected since it is local variable). Instead above I tried to declare presentVal
as global like,global presentVal
and also I intialized presentVal
above my test case but didn't turn well.
class func1():
def __init__(self):
pass
def currentVal(self):
cval = measure() ---------> function from where I get current values
return cval
Can someone suggest how declare global variable in pytest
or other best way
Thanks in advance!
Upvotes: 5
Views: 19546
Reputation: 3721
What you are looking for is called a "fixture". Have a look at the following example, it should solve your problem:
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
You can essentially share a fixture instance across tests. It's intended for more complicated stuff like a database access object, but it can be something trivial like a dictionary :)
Scope: sharing a fixture instance across tests in a class, module or session
Upvotes: 8