Python Mock not asserting calls

人盡茶涼 提交于 2019-12-11 02:21:41

问题


I'm using the mock library to patch a class in a program that connects to a external resource and sends a dictioanry.

The structure goes a litle like this...

code.py

def make_connection():
    connection = OriginalClass(host, port)
    connection.connect()
    connection.send(param)
    connection.close()

test.py

@mock.path('code.OriginalClass')
def test_connection(self, mocked_conn):
    code.make_connection()
    mocked_conn.assert_called_with(host, port)
    mocked_conn.connect.assert_called_once()
    mocked_conn.send.assert_called_with(param)

The first assert_called_with works perfectly, but the calls to method of the mocked class don't pass. I have tried using patch.object as a decorator also with no luck.


回答1:


The connect() and send() methods are called on the return value of the first call; adjust your test accordingly:

mocked_conn.return_value.connect.assert_called_once()
mocked_conn.return_value.send.assert_called_with(param)

I usually store a reference to the 'instance' first:

@mock.path('code.OriginalClass')
def test_connection(self, mocked_conn):
    code.make_connection()
    mocked_conn.assert_called_with(host, port)
    mocked_instance = mocked_conn.return_value
    mocked_instance.connect.assert_called_once()
    mocked_instance.send.assert_called_with(param)


来源:https://stackoverflow.com/questions/26343600/python-mock-not-asserting-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!