如何使用正在另一个 python 文件中使用的 unittest 模拟变量的值
How to Mock the value of a variable using unittest which is being used in another python file
我有以下文件constants.py
# Here all the constants are written
variable_name = False
...
来自 constants.py
的上述变量 variable_name 正在另一个文件中使用 b.py
#b.py
import constants
def func():
if constants.variable_name:
""" Do Something """
else:
""" Do Something """
在这里,我如何模拟 variable_name 从 constants.py
到 True
来测试 if
条件函数 func
使用 unittest?
如果你只是需要预先设置一个变量的值你可以使用测试用例的setUp
方法:
import constants
class test_class(unittest.TestCase):
def setUp(self):
constants.variable_name = True
您可以使用unittest.mock.patch
修补对象:
from unittest.mock import patch
with patch('constants.variable_name', True):
func()
您可以按如下方式修补变量:
import constants
from mock import patch
@patch('constants.variable_name', True)
我有以下文件constants.py
# Here all the constants are written
variable_name = False
...
来自 constants.py
的上述变量 variable_name 正在另一个文件中使用 b.py
#b.py
import constants
def func():
if constants.variable_name:
""" Do Something """
else:
""" Do Something """
在这里,我如何模拟 variable_name 从 constants.py
到 True
来测试 if
条件函数 func
使用 unittest?
如果你只是需要预先设置一个变量的值你可以使用测试用例的setUp
方法:
import constants
class test_class(unittest.TestCase):
def setUp(self):
constants.variable_name = True
您可以使用unittest.mock.patch
修补对象:
from unittest.mock import patch
with patch('constants.variable_name', True):
func()
您可以按如下方式修补变量:
import constants
from mock import patch
@patch('constants.variable_name', True)