gpt4 book ai didi

python - 如何在 python 中模拟 self ?

转载 作者:太空狗 更新时间:2023-10-29 21:36:30 25 4
gpt4 key购买 nike

考虑以下代码。我想模拟 self.get_value,它在 foo.verify_client()

中调用
import unittest
import mock

def mock_get_value(self, value):
return 'client'

class Foo:
def __init__(self):
pass
def get_value(self, value):
return value
def verify_client(self):
client = self.get_value('client')
return client == 'client'

class testFoo(unittest.TestCase):
@mock.patch('self.get_value', side_effect = mock_get_value, autospec = True)
def test_verify_client(self):
foo = Foo()
result = foo.verify_client()
self.assertTrue(result)

if __name__ == "__main__":
unittest.main()

但是我失败了,错误如下。

E
======================================================================
ERROR: test_verify_client (__main__.testFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1297, in patched
arg = patching.__enter__()
File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1353, in __enter__
self.target = self.getter()
File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1523, in <lambda>
getter = lambda: _importer(target)
File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1206, in _importer
thing = __import__(import_path)
ImportError: No module named self

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

我该怎么做?

最佳答案

我想通了。改变这一行

@mock.patch('self.get_value', side_effect = mock_get_value, autospec = True)

@mock.patch('test.Foo.get_value', mock_get_value)

成功了。

注意打补丁函数的格式应该是module_name + class_name + method_name

关于python - 如何在 python 中模拟 self ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39698094/

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