close

How to share global variables between tests?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to share global variables between tests in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to share global variables between tests?

  1. How to share global variables between tests?

    pytest provides a way to use some global variables within the session. These variables can be used by fixtures as well.

  2. share global variables between tests

    pytest provides a way to use some global variables within the session. These variables can be used by fixtures as well.

Method 1

According to docs, pytest_namespace has been removed in version 4.0:

One can use pytest_configure to share global variables.

Example:

import pytest

def pytest_configure():
pytest.my_symbol = MySymbol()

Method 2

pytest provides a way to use some global variables within the session. These variables can be used by fixtures as well.

These variables are controlled via pytest hooks.

import pytest

def pytest_namespace():
    return {'my_global_variable': 0}

@pytest.fixture
def data():
    pytest.my_global_variable = 100

def test(data):
    print pytest.my_global_variable

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read