0

We create mock objects and specify the behavior of methods called on them:

from unittest.mock import patch, Mock

execute = Mock()
execute.fetchone = Mock(return_value={'state': json.dumps({})})
with patch('modules.data_chat.chatbot.execute', new=lambda x, y, z: execute):
        auto_reply(None, "test_user_id", "Hello?", 1)

assert execute.fetchone.called
assert execute.called

code under test (auto_reply) implementation:

from tools.db_tools import execute
[...]
cur = execute(conn, sql, (bot_id, channel_id))
state = cur.fetchone()

Back in the test code, execute.fetchone.called == True. However, execute.called == False

Why is execute.called == False and how can I fix this? Is new=lambda x, y, z: execute correct?

2 Answers 2

3

Because you didn't call it. You called a lambda, which returned it.

I'm not sure why you are doing this. You should use the mocks.

fetchone = Mock(return_value={'state': json.dumps({})})
execute = Mock(return_value=fetchone)
with patch('modules.data_chat.chatbot.execute', new=execute):
    ...
Sign up to request clarification or add additional context in comments.

1 Comment

This also corrects the error of treating fetchone as an attribute of execute, rather than an attribute of the return value of execute.
0

@Daniel Roseman put me on the right track. One step in the chain was missing in his answer though. execute should not return fetchone directly, but a cursor mock; which can mock fetchone. I added names to the mocks for debugging purposes:

cursorMock = Mock(name="cursorMock")
cursorMock.fetchone = Mock(name="fetchoneMock", return_value={'state': json.dumps({})})

execute = Mock(name="executeMock", return_value=cursorMock)
with patch('modules.data_chat.chatbot.execute', new=execute):
    ...

assert cursorMock.fetchone.called
assert execute.called

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.