模拟全局变量时,如果我从模拟全局变量中初始化另一个全局变量,则另一个全局变量不会获取模拟值。我希望代码能使它更清晰。
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}")
我看到的打印内容: myglobal.ROOT = / tmp /,myglobal.DIR = / etc my_root:/ tmp /,my_dir:/ tmp / etc
我想看到的印刷品: myglobal.ROOT = / tmp /,myglobal.DIR = / tmp / etc my_root:/ tmp /,my_dir:/ tmp / etc