本文整理汇总了Python中unittest.mock.AsyncMock方法的典型用法代码示例。如果您正苦于以下问题:Python mock.AsyncMock方法的具体用法?Python mock.AsyncMock怎么用?Python mock.AsyncMock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类unittest.mock
的用法示例。
在下文中一共展示了mock.AsyncMock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_txt_file_redirect_embed_description
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import AsyncMock [as 别名]
def test_txt_file_redirect_embed_description(self):
"""A message containing a .txt file should result in the correct embed."""
attachment = MockAttachment(filename="python.txt")
self.message.attachments = [attachment]
self.message.channel.send = AsyncMock()
antimalware.TXT_EMBED_DESCRIPTION = Mock()
antimalware.TXT_EMBED_DESCRIPTION.format.return_value = "test"
await self.cog.on_message(self.message)
self.message.channel.send.assert_called_once()
args, kwargs = self.message.channel.send.call_args
embed = kwargs.pop("embed")
cmd_channel = self.bot.get_channel(Channels.bot_commands)
self.assertEqual(embed.description, antimalware.TXT_EMBED_DESCRIPTION.format.return_value)
antimalware.TXT_EMBED_DESCRIPTION.format.assert_called_with(cmd_channel_mention=cmd_channel.mention)
示例2: test_other_disallowed_extention_embed_description
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import AsyncMock [as 别名]
def test_other_disallowed_extention_embed_description(self):
"""Test the description for a non .py/.txt disallowed extension."""
attachment = MockAttachment(filename="python.disallowed")
self.message.attachments = [attachment]
self.message.channel.send = AsyncMock()
antimalware.DISALLOWED_EMBED_DESCRIPTION = Mock()
antimalware.DISALLOWED_EMBED_DESCRIPTION.format.return_value = "test"
await self.cog.on_message(self.message)
self.message.channel.send.assert_called_once()
args, kwargs = self.message.channel.send.call_args
embed = kwargs.pop("embed")
meta_channel = self.bot.get_channel(Channels.meta)
self.assertEqual(embed.description, antimalware.DISALLOWED_EMBED_DESCRIPTION.format.return_value)
antimalware.DISALLOWED_EMBED_DESCRIPTION.format.assert_called_with(
blocked_extensions_str=".disallowed",
meta_channel_mention=meta_channel.mention
)
示例3: test_relay_message_correctly_relays_content_and_attachments
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import AsyncMock [as 别名]
def test_relay_message_correctly_relays_content_and_attachments(self):
"""The `relay_message` method should correctly relay message content and attachments."""
send_webhook_path = f"{MODULE_PATH}.DuckPond.send_webhook"
send_attachments_path = f"{MODULE_PATH}.send_attachments"
self.cog.webhook = helpers.MockAsyncWebhook()
test_values = (
(helpers.MockMessage(clean_content="", attachments=[]), False, False),
(helpers.MockMessage(clean_content="message", attachments=[]), True, False),
(helpers.MockMessage(clean_content="", attachments=["attachment"]), False, True),
(helpers.MockMessage(clean_content="message", attachments=["attachment"]), True, True),
)
for message, expect_webhook_call, expect_attachment_call in test_values:
with patch(send_webhook_path, new_callable=AsyncMock) as send_webhook:
with patch(send_attachments_path, new_callable=AsyncMock) as send_attachments:
with self.subTest(clean_content=message.clean_content, attachments=message.attachments):
await self.cog.relay_message(message)
self.assertEqual(expect_webhook_call, send_webhook.called)
self.assertEqual(expect_attachment_call, send_attachments.called)
message.add_reaction.assert_called_once_with(self.checkmark_emoji)
示例4: test_sync_diff_size
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import AsyncMock [as 别名]
def test_sync_diff_size(self):
"""The diff size should be correctly calculated."""
subtests = (
(6, _Diff({1, 2}, {3, 4}, {5, 6})),
(5, _Diff({1, 2, 3}, None, {4, 5})),
(0, _Diff(None, None, None)),
(0, _Diff(set(), set(), set())),
)
for size, diff in subtests:
with self.subTest(size=size, diff=diff):
self.syncer._get_diff.reset_mock()
self.syncer._get_diff.return_value = diff
self.syncer._get_confirmation_result = mock.AsyncMock(return_value=(False, None))
guild = helpers.MockGuild()
await self.syncer.sync(guild)
self.syncer._get_diff.assert_called_once_with(guild)
self.syncer._get_confirmation_result.assert_called_once()
self.assertEqual(self.syncer._get_confirmation_result.call_args[0][0], size)
示例5: test_sync_message_edited
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import AsyncMock [as 别名]
def test_sync_message_edited(self):
"""The message should be edited if one was sent, even if the sync has an API error."""
subtests = (
(None, None, False),
(helpers.MockMessage(), None, True),
(helpers.MockMessage(), ResponseCodeError(mock.MagicMock()), True),
)
for message, side_effect, should_edit in subtests:
with self.subTest(message=message, side_effect=side_effect, should_edit=should_edit):
self.syncer._sync.side_effect = side_effect
self.syncer._get_confirmation_result = mock.AsyncMock(
return_value=(True, message)
)
guild = helpers.MockGuild()
await self.syncer.sync(guild)
if should_edit:
message.edit.assert_called_once()
self.assertIn("content", message.edit.call_args[1])
示例6: test_confirmation_result_small_diff
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import AsyncMock [as 别名]
def test_confirmation_result_small_diff(self):
"""Should always return True and the given message if the diff size is too small."""
author = helpers.MockMember()
expected_message = helpers.MockMessage()
for size in (3, 2): # pragma: no cover
with self.subTest(size=size):
self.syncer._send_prompt = mock.AsyncMock()
self.syncer._wait_for_confirmation = mock.AsyncMock()
coro = self.syncer._get_confirmation_result(size, author, expected_message)
result, actual_message = await coro
self.assertTrue(result)
self.assertEqual(actual_message, expected_message)
self.syncer._send_prompt.assert_not_called()
self.syncer._wait_for_confirmation.assert_not_called()
示例7: test_apply_ban_reason_truncation
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import AsyncMock [as 别名]
def test_apply_ban_reason_truncation(self, post_infraction_mock, get_active_mock):
"""Should truncate reason for `ctx.guild.ban`."""
get_active_mock.return_value = None
post_infraction_mock.return_value = {"foo": "bar"}
self.cog.apply_infraction = AsyncMock()
self.bot.get_cog.return_value = AsyncMock()
self.cog.mod_log.ignore = Mock()
self.ctx.guild.ban = Mock()
await self.cog.apply_ban(self.ctx, self.target, "foo bar" * 3000)
self.ctx.guild.ban.assert_called_once_with(
self.target,
reason=textwrap.shorten("foo bar" * 3000, 512, placeholder="..."),
delete_message_days=0
)
self.cog.apply_infraction.assert_awaited_once_with(
self.ctx, {"foo": "bar"}, self.target, self.ctx.guild.ban.return_value
)
示例8: test_upload_output
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import AsyncMock [as 别名]
def test_upload_output(self):
"""Upload the eval output to the URLs.paste_service.format(key="documents") endpoint."""
key = "MarkDiamond"
resp = MagicMock()
resp.json = AsyncMock(return_value={"key": key})
context_manager = MagicMock()
context_manager.__aenter__.return_value = resp
self.bot.http_session.post.return_value = context_manager
self.assertEqual(
await self.cog.upload_output("My awesome output"),
constants.URLs.paste_service.format(key=key)
)
self.bot.http_session.post.assert_called_with(
constants.URLs.paste_service.format(key="documents"),
data="My awesome output",
raise_for_status=True
)
示例9: test_send_eval
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import AsyncMock [as 别名]
def test_send_eval(self):
"""Test the send_eval function."""
ctx = MockContext()
ctx.message = MockMessage()
ctx.send = AsyncMock()
ctx.author.mention = '@LemonLemonishBeard#0042'
self.cog.post_eval = AsyncMock(return_value={'stdout': '', 'returncode': 0})
self.cog.get_results_message = MagicMock(return_value=('Return code 0', ''))
self.cog.get_status_emoji = MagicMock(return_value=':yay!:')
self.cog.format_output = AsyncMock(return_value=('[No output]', None))
await self.cog.send_eval(ctx, 'MyAwesomeCode')
ctx.send.assert_called_once_with(
'@LemonLemonishBeard#0042 :yay!: Return code 0.\n\n```py\n[No output]\n```'
)
self.cog.post_eval.assert_called_once_with('MyAwesomeCode')
self.cog.get_status_emoji.assert_called_once_with({'stdout': '', 'returncode': 0})
self.cog.get_results_message.assert_called_once_with({'stdout': '', 'returncode': 0})
self.cog.format_output.assert_called_once_with('')
示例10: test_send_eval_with_paste_link
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import AsyncMock [as 别名]
def test_send_eval_with_paste_link(self):
"""Test the send_eval function with a too long output that generate a paste link."""
ctx = MockContext()
ctx.message = MockMessage()
ctx.send = AsyncMock()
ctx.author.mention = '@LemonLemonishBeard#0042'
self.cog.post_eval = AsyncMock(return_value={'stdout': 'Way too long beard', 'returncode': 0})
self.cog.get_results_message = MagicMock(return_value=('Return code 0', ''))
self.cog.get_status_emoji = MagicMock(return_value=':yay!:')
self.cog.format_output = AsyncMock(return_value=('Way too long beard', 'lookatmybeard.com'))
await self.cog.send_eval(ctx, 'MyAwesomeCode')
ctx.send.assert_called_once_with(
'@LemonLemonishBeard#0042 :yay!: Return code 0.'
'\n\n```py\nWay too long beard\n```\nFull output: lookatmybeard.com'
)
self.cog.post_eval.assert_called_once_with('MyAwesomeCode')
self.cog.get_status_emoji.assert_called_once_with({'stdout': 'Way too long beard', 'returncode': 0})
self.cog.get_results_message.assert_called_once_with({'stdout': 'Way too long beard', 'returncode': 0})
self.cog.format_output.assert_called_once_with('Way too long beard')
示例11: test_send_eval_with_non_zero_eval
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import AsyncMock [as 别名]
def test_send_eval_with_non_zero_eval(self):
"""Test the send_eval function with a code returning a non-zero code."""
ctx = MockContext()
ctx.message = MockMessage()
ctx.send = AsyncMock()
ctx.author.mention = '@LemonLemonishBeard#0042'
self.cog.post_eval = AsyncMock(return_value={'stdout': 'ERROR', 'returncode': 127})
self.cog.get_results_message = MagicMock(return_value=('Return code 127', 'Beard got stuck in the eval'))
self.cog.get_status_emoji = MagicMock(return_value=':nope!:')
self.cog.format_output = AsyncMock() # This function isn't called
await self.cog.send_eval(ctx, 'MyAwesomeCode')
ctx.send.assert_called_once_with(
'@LemonLemonishBeard#0042 :nope!: Return code 127.\n\n```py\nBeard got stuck in the eval\n```'
)
self.cog.post_eval.assert_called_once_with('MyAwesomeCode')
self.cog.get_status_emoji.assert_called_once_with({'stdout': 'ERROR', 'returncode': 127})
self.cog.get_results_message.assert_called_once_with({'stdout': 'ERROR', 'returncode': 127})
self.cog.format_output.assert_not_called()
示例12: test_continue_eval_does_continue
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import AsyncMock [as 别名]
def test_continue_eval_does_continue(self, partial_mock):
"""Test that the continue_eval function does continue if required conditions are met."""
ctx = MockContext(message=MockMessage(add_reaction=AsyncMock(), clear_reactions=AsyncMock()))
response = MockMessage(delete=AsyncMock())
new_msg = MockMessage()
self.bot.wait_for.side_effect = ((None, new_msg), None)
expected = "NewCode"
self.cog.get_code = create_autospec(self.cog.get_code, spec_set=True, return_value=expected)
actual = await self.cog.continue_eval(ctx, response)
self.cog.get_code.assert_awaited_once_with(new_msg)
self.assertEqual(actual, expected)
self.bot.wait_for.assert_has_awaits(
(
call(
'message_edit',
check=partial_mock(snekbox.predicate_eval_message_edit, ctx),
timeout=snekbox.REEVAL_TIMEOUT,
),
call('reaction_add', check=partial_mock(snekbox.predicate_eval_emoji_reaction, ctx), timeout=10)
)
)
ctx.message.add_reaction.assert_called_once_with(snekbox.REEVAL_EMOJI)
ctx.message.clear_reactions.assert_called_once()
response.delete.assert_called_once()
示例13: test_protocol_handle_max_incomplete
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import AsyncMock [as 别名]
def test_protocol_handle_max_incomplete(monkeypatch: MonkeyPatch) -> None:
config = Config()
config.h11_max_incomplete_size = 5
MockHTTPStream = AsyncMock() # noqa: N806
MockHTTPStream.return_value = AsyncMock(spec=HTTPStream)
monkeypatch.setattr(hypercorn.protocol.h11, "HTTPStream", MockHTTPStream)
context = Mock()
context.event_class.return_value = AsyncMock(spec=IOEvent)
protocol = H11Protocol(AsyncMock(), config, context, False, None, None, AsyncMock())
await protocol.handle(RawData(data=b"GET / HTTP/1.1\r\nHost: hypercorn\r\n"))
protocol.send.assert_called()
assert protocol.send.call_args_list == [
call(
RawData(
data=b"HTTP/1.1 400 \r\ncontent-length: 0\r\nconnection: close\r\n"
b"date: Thu, 01 Jan 1970 01:23:20 GMT\r\nserver: hypercorn-h11\r\n\r\n"
)
),
call(RawData(data=b"")),
call(Closed()),
]
示例14: test_pings
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import AsyncMock [as 别名]
def test_pings(stream: WSStream, event_loop: asyncio.AbstractEventLoop) -> None:
stream.config.websocket_ping_interval = 0.1
await stream.handle(
Request(
stream_id=1,
http_version="2",
headers=[(b"sec-websocket-version", b"13")],
raw_path=b"/?a=b",
method="GET",
)
)
async with TaskGroup(event_loop) as task_group:
stream.context = Context(task_group)
await stream.app_send({"type": "websocket.accept"})
stream.app_put = AsyncMock()
await asyncio.sleep(0.15)
assert stream.send.call_args_list == [
call(Response(stream_id=1, headers=[], status_code=200)),
call(Data(stream_id=1, data=b"\x89\x00")),
call(Data(stream_id=1, data=b"\x89\x00")),
]
await stream.handle(StreamClosed(stream_id=1))
示例15: supervisor_data
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import AsyncMock [as 别名]
def supervisor_data():
supervisor = AsyncMock()
mailbox = DefaultMailbox(None, None, None)
local_process = ActorProcess(mailbox)
pid_child = PID()
pid_child.address = 'address'
pid_child.id = 'id'
restart_statistic = RestartStatistics(5, datetime(2017, 2, 15))
return {
'supervisor': supervisor,
'mailbox': mailbox,
'local_process': local_process,
'pid_child': pid_child,
'restart_statistic': restart_statistic
}