简体   繁体   English

如何在python中模拟自己?

[英]How to mock self in python?

Consider the following code.考虑以下代码。 I want to mock self.get_value , which is invoked in foo.verify_client()我想模拟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()

But I failed, the errors are as follows.但是我失败了,错误如下。

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)

How can I do it?我该怎么做?

I figured it out.我想通了。 Changing this line改变这条线

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

to

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

worked.工作。

Note that the format of the patched function should be module_name + class_name + method_name注意被打补丁的函数的格式应该是module_name + class_name + method_name

Another option would be to mock the self parameter.另一种选择是模拟self参数。 This can decouple the logic in verify_client from the instantiation of the class Foo这可以将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