简体   繁体   English

如何使用在另一个 python 文件中使用的 unittest 模拟变量的值

[英]How to Mock the value of a variable using unittest which is being used in another python file

I have the following file constants.py我有以下文件constants.py

# Here all the constants are written
variable_name = False
...

The above variable variable_name from constants.py is being used in another file b.py上面来自constants.py的变量variable_name正在另一个文件b.py中使用

#b.py

import constants
def func():
   if constants.variable_name:
       """ Do Something """
   else:
       """ Do Something """

Here, how can I mock the variable_name from constants.py to True to test the if condition of the function func using unittest?在这里,我如何将variable_nameconstants.py模拟为True以使用 unittest 测试 function funcif条件?

If you just need to pre-set the value of a variable you can use the setUp method of the test case:如果你只需要预先设置一个变量的值,你可以使用测试用例的setUp方法:

import constants
class test_class(unittest.TestCase):
    def setUp(self):
        constants.variable_name = True

You can use unittest.mock.patch to patch the object:您可以使用unittest.mock.patch来修补 object:

from unittest.mock import patch

with patch('constants.variable_name', True):
    func()

You can patch the variable as follows:您可以按如下方式修补变量:

import constants
from mock import patch
@patch('constants.variable_name', True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM