When mocking a global variable, if I initialize another global from the mocked global, the other global does not pick up the mocked value. I hope the code makes it clearer.
myglobal.py:
ROOT="/"
#When we mock ROOT to "/tmp/", DIR below
#still gets "/etc". Assignments from the global, in the module
#that contains/creates the global, don't pick up the mocked value.
DIR=ROOT+"etc"
mytest.py:
import unittest
import myglobal
from unittest.mock import patch
my_root=""
my_dir=""
class TestGlobal(unittest.TestCase):
def setUp(self):
# Mock ROOT global in myglobal
self.mock_ROOT_patcher = patch.object(myglobal, 'ROOT', "/tmp/")
self.mock_ROOT = self.mock_ROOT_patcher.start()
def tearDown(self):
self.mock_ROOT_patcher.stop()
def test_root(self):
# Local Globals do get the mocked global value.
# The print Bellow prints:
#
# myglobal.ROOT=/tmp/, myglobal.DIR=/etc
# my_root:/tmp/, my_dir:/tmp/etc
#
my_root=myglobal.ROOT
my_dir=my_root+"etc"
print(f"\n myglobal.ROOT={myglobal.ROOT}, myglobal.DIR={myglobal.DIR}")
print(f"my_root:{my_root}, my_dir:{my_dir}")
What I see printed: myglobal.ROOT=/tmp/, myglobal.DIR=/etc my_root:/tmp/, my_dir:/tmp/etc
What I want to see printed: myglobal.ROOT=/tmp/, myglobal.DIR=/tmp/etc my_root:/tmp/, my_dir:/tmp/etc