python - 如何在 python 中模拟 self ?

标签 python unit-testing mocking

考虑以下代码。我想模拟 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/

相关文章:

python - 在同一个应用程序中使用 django 信号是否合适

python - 通过聚合函数过滤 Pandas 数据框?

php - 模拟框架返回具有不同名称和类型的类

angular - Angular 中的单元测试 socket.io

ruby-on-rails - 如何在Carrierwave中从远程URL stub 下载

javascript - 开 Jest : Mocking navigator. 存储.坚持

python - 如何从 Django 中的多对多中间模型中进行选择?

Python 生成器和产量 : How to know which line the program is at

c++ - 使用 qExec 创建 Qt 测试套件

python-3.x - 使用上下文管理器进行 Pytests