繁体   English   中英

如何在python中模拟自己?

[英]How to mock self in python?

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

另一种选择是模拟self参数。 这可以将verify_client的逻辑与类Foo的实例化解耦

import unittest
import mock


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):

    def test_verify_client(self):
        mock_self = mock.Mock()
        mock_self.get_value.return_value = 'client'
        result = Foo.verify_client(mock_self)  # NOTE: Foo is the class, not an instance
        self.assertTrue(result)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM