【发布时间】:2017-07-05 15:13:37
【问题描述】:
我试图了解在 Python 中使用 mock.patch 修补常量的不同方法。 我的目标是能够使用我的 Test 类中定义的变量作为我的常量的修补值。
我发现这个问题解释了如何修补常量: How to patch a constant in python 这个问题解释了如何在补丁中使用 self : using self in python @patch decorator
但是从这个第二个链接,我无法让 testTwo 方式(提供模拟作为函数参数)工作
这是我的简化用例:
mymodule.py
MY_CONSTANT = 5
def get_constant():
return MY_CONSTANT
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
我的猜测是我不应该使用 return_value,因为 mock_MY_CONSTANT 不是函数。那么我应该使用什么属性来替换调用常量时返回的值呢?
【问题讨论】:
标签: python unit-testing mocking constants patch