gpt4 book ai didi

python - 如何模拟在同一文件中定义且未被测试方法导入的函数?

转载 作者:行者123 更新时间:2023-12-04 13:02:59 24 4
gpt4 key购买 nike

到目前为止,我有以下代码:

import unittest
from mock import patch, Mock


def method_1():
from math import ceil
return ceil(1.2)


def test_1():
m = Mock(return_value=10)
with patch('math.ceil', m) as p:
a = method_1()
assert(a == 10)


def method_2():
return method_1() + 1


def test_2():
m = Mock(return_value=20)
with patch('method_1', m) as p:
a = method_2()
assert(a == 21)

在运行测试时,我收到以下错误:
$ nosetests -s unittest.py 
.E
======================================================================
ERROR: unittest.test_2
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/srv/www/rpr/unittest.py", line 27, in test_2
with patch('method_1', m) as p:
File "/usr/local/lib/python2.7/dist-packages/mock.py", line 1564, in patch
getter, attribute = _get_target(target)
File "/usr/local/lib/python2.7/dist-packages/mock.py", line 1413, in _get_target
(target,))
TypeError: Need a valid target to patch. You supplied: 'method_1'

----------------------------------------------------------------------
Ran 2 tests in 27.840s

FAILED (errors=1)

我可以模拟 math.ceil正确和 test_1通过没有任何问题。我很难 mock method_1本身。我该怎么做呢?

最佳答案

我不得不改变 test_2以使其正常工作:

def test_2():
m = Mock(return_value=20)
with patch(__name__ + '.method_1', m) as p:
a = method_2()
assert(a == 21)

关于python - 如何模拟在同一文件中定义且未被测试方法导入的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50446643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com