Testing a method that uses a global variable

Question:

I’m trying to test a method that uses a global settings variable (python). I have these 3 files:

setting_to_test.py:

import os

GLOBAL_VAR = os.environ.get("GLOBAL_VAR", 6)

function_to_test.py:

from setting_to_test import GLOBAL_VAR


def funca():
    return GLOBAL_VAR ** 2

test_module.py:

from unittest.mock import patch

from function_to_test import funca


@patch("setting_to_test.GLOBAL_VAR", 66)
def test_my_module():
    assert funca() == 66 ** 2

As the test specify, I want to be able to override the default values (6) to be 66. Unfortunately, no matter what I try, the value keeps being 6.
I’m using pycharm to run this test:

"C:Program FilesJetBrainsPyCharm 2021.3.2pluginspythonhelperspycharm_jb_pytest_runner.py" --path C:/myfolder/code/testing_project/test_module.py

Am I missing something?

Asked By: Netanel

||

Answers:

from https://docs.python.org/3/library/unittest.mock.html#id6:

Now we want to test some_function but we want to mock out SomeClass using patch(). The problem is that when we import module b, which we will have to do then it imports SomeClass from module a. If we use patch() to mock out a.SomeClass then it will have no effect on our test; module b already has a reference to the real SomeClass and it looks like our patching had no effect.
The key is to patch out SomeClass where it is used (or where it is looked up). In this case some_function will actually look up SomeClass in module b, where we have imported it.

try:

@patch("function_to_test.GLOBAL_VAR", 66)
def test_my_module():
    assert funca() == 66 ** 2
Answered By: Daniel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.