python函数调用时所提供的参数可以是常量_如何使用模拟作为函数参数在Python中修补常量...

我试图了解使用ock.patch在Python中修补常量的不同方法。我的目标是能够使用Test类中定义的变量作为常量的修补值。

但是从第二个链接,我无法获得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: != 3

我的猜测是我不应该使用return_value,因为mock_MY_CONSTANT不是函数。那么我应该使用什么属性来替换调用常量时返回的值?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值