我想用单元测试覆盖on_text
方法。我想用非unicode消息检查on_text
以查看是否已调用send_message
。
class MyTornadoClass(object):
@gen.coroutine
def on_text(self, message):
"""
User message controller
"""
id_ = message.message_id
chat = message.chat
text = message.text.strip().replace(" ", "-").replace("[()&?]", "")
if not self.is_ascii(text):
yield self.send_message(chat.id_, "Sorry, I didn't find anything according to you request. Try again!",
reply_to_message_id=id_)
else:
yield self.perform_search(text, id_, chat)
我的模拟测试是:
def test_app(self):
message = types.Message({'message_id': '1', 'text': 'Ў',
'chat': {"id": 227071993, "first_name": "Sergei", "last_name": "Rudenkov",
"type": "private"}, 'from': 343})
zombie = bot_telegram.starter.MyTornadoClass('API_TOKEN', 'SO_WS_URL')
zombie.on_text(message)
with mock.patch.object(bot_telegram.starter.MyTornadoClass, 'send_message') as mock_zombie:
mock_zombie.assert_called_with(227071993,
"""Sorry, I didn't find anything according to you request.
Try again!""",
1)
我收到例外:
Traceback (most recent call last):
File "/home/sergei-rudenkov/PycharmProjects/python_tasks/bot_telegram/unit_tests/telezombie_api/starter_test.py", line 21, in test_app
1)
File "/usr/local/lib/python3.5/dist-packages/mock/mock.py", line 925, in assert_called_with
raise AssertionError('Expected call: %s\nNot called' % (expected,))
AssertionError: Expected call: send_message(227071993, "Sorry, I didn't find anything according to you request.\n Try again!", 1)
Not called
----------------------------------------------------------------------
Ran 1 test in 0.006s
FAILED (failures=1)
我不知道我做错了什么。请指出我的错误。
答案 0 :(得分:1)
当您使用patch.object()
作为上下文管理器时,修补将应用于with
语句后的缩进块。如果您将调用移至1>} 块中的.on_text()
,您会看到不同的AssertionError
:
with mock.patch.object(bot_telegram.starter.MyTornadoClass, 'send_message') as mock_zombie:
zombie.on_text(message)
mock_zombie.assert_called_with(args)
AssertionError: Expected call: send_message(227071993, "Sorry, I didn't find anything according to you request.\n Try again!", 1)
Actual call: send_message(227071993, "Sorry, I didn't find anything according to you request. Try again!", reply_to_message_id='1')