简体   繁体   中英

How to mock self in python?

Consider the following code. I want to mock self.get_value , which is invoked in 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

Another option would be to mock the self parameter. This can decouple the logic in verify_client from the instantiation of the class 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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