我试图了解使用ock.patch在Python中修补常量的不同方法。我的目标是能够使用Test类中定义的变量作为常量的修补值。
我发现了这个问题,该问题解释了如何修补常量: 如何在python中修补常量, 并且这个问题解释了如何在patch中 使用self:在python中使用self @patch decorator
但是从第二个链接,我无法获得testTwo方法(将模拟作为函数参数提供)
这是我的简化用例:
mymodule.py
MY_CONSTANT = 5
def get_constant():
return MY_CONSTANT
Run Code Online (Sandbox Code Playgroud)
test_mymodule.py
import unittest
from unittest.mock import patch
import mymodule
class Test(unittest.TestCase):
#This works
@patch("mymodule.MY_CONSTANT", 3)
def test_get_constant_1(self):
self.assertEqual(mymodule.get_constant(), 3)
#This also works
def test_get_constant_2(self):
with patch("mymodule.MY_CONSTANT", 3):
self.assertEqual(mymodule.get_constant(), 3)
#But this doesn't
@patch("mymodule.MY_CONSTANT")
def test_get_constant_3(self, mock_MY_CONSTANT):
mock_MY_CONSTANT.return_value = 3
self.assertEqual(mymodule.get_constant(), 3)
#AssertionError: <MagicMock name='MY_CONSTANT' id='64980808'> != 3
Run Code Online (Sandbox Code Playgroud)
我的猜测是我不应该使用return_value,因为mock_MY_CONSTANT不是函数。那么我应该使用什么属性来替换调用常量时返回的值?