Global variable in pytest

12,693

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

Share:
12,693
Kumar
Author by

Kumar

Updated on June 09, 2022

Comments

  • Kumar
    Kumar about 2 years

    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!

    • Macintosh_89
      Macintosh_89 over 6 years
      for a starter you could make iterations better using @pytest.mark.parametrize("count",range(5)) not sure if this could help you. see this