Mocking global variables in Python tests

Mocking global variables in Python tests

I attempted to test global variables in Python, specifically for a script that contains global variables. After struggling to do so, I found a simple solution that I can share with you.

🏃 The quick solution

demo_file.py
ENVS = { 'real_value': True, 'another_real_value': False }

Now, let’s go to the test file.

test_your_demo_file.py
mocker.patch("demo_file.ENVS", new={'MOCKED_NONE': None, 'MOCKED_EMPTY': ''})

Next, the ENVS variable will be mocked in your demo_file.

✏️ Solution with description

Requirements

To simplify the process, I recommend using the pytest-mock library: https://pypi.org/project/pytest-mock/

What I was trying to do?

Firstly, suppose you have a file called demo_file.py with the following content (where the global variable is located):

demo_file.py
import os
ENVS = { 'real_value': os.environ('REAL_VALUE'), 'another_real_value': os.environ('ANOTHER_REAL_VALUE') }
def simple_method():
print(ENVS)
return 0

If you try to execute simple_method, it will print the dictionary with real_value and another_real_value there.

Next, we have the following test file.

test_my_envs.py
from demo_file import simple_method
def test_if_simple_method_is_working():
assert simple_method() == 0

I know the test seems simple, but it’s important to make sure that it returns a zero value after printing the values of the ENV variable.

👾 Mocking the Variable

However, as you can see, we are calling environment variables on the current computer. If you write your tests to expect those variables on your CI/CD server, the tests will fail. How can we avoid this and tell our test server (or test pipeline) that we want specific fixed values?

If you have installed the package mentioned in the requirements section, it is easy to start mocking values. We only need to add a single line.

test_my_envs.py
from demo_file import simple_method
@mocker.patch("demo_file.ENVS", new={'MOCKED_REAL_VALUE': None, 'MOCKED_ANOTHER_REAL_VALUE': ''})
def test_if_simple_method_is_working():
assert simple_method() == 0

Your tests will not execute the real ENVS variable and, therefore, will not call os.environ.

My posts are not AI generated, they might be only AI corrected. The first draft is always my creation

Tags

Author

Written by Helmer Davila

In other languages

Estaba intentando probar algunas variables globales con Python, especialmente para un script el cual contiene variables globales. Y después de intentarlo y fallar, pienso que puedo mostrarte la versión más simple de hacerlo.

Testing en Python: Hacer mock de una variable global

J’ai essayé de tester quelques variables globales dans Python, spécialement pour un script, qui contient des variables globales. Et après avoir essayé et essayé (et échouer), je pense que je peux te comment le faire.

Faire un mock pour une variable globale dans les tests de Python

Estava tentando testar algumas variáveis globais com Python, especialmente para um script que contém variáveis globais

Fazer mocks de variáveis globais em testes Python

Related posts

Useful for avoid calling real APIs or services

How to use functions as Mocks in Python tests