Python源码示例:asyncio.run()
示例1
def test_roles_command_command(self):
"""Test if the `role_info` command correctly returns the `moderator_role`."""
self.ctx.guild.roles.append(self.moderator_role)
self.cog.roles_info.can_run = unittest.mock.AsyncMock()
self.cog.roles_info.can_run.return_value = True
coroutine = self.cog.roles_info.callback(self.cog, self.ctx)
self.assertIsNone(asyncio.run(coroutine))
self.ctx.send.assert_called_once()
_, kwargs = self.ctx.send.call_args
embed = kwargs.pop('embed')
self.assertEqual(embed.title, "Role information (Total 1 role)")
self.assertEqual(embed.colour, discord.Colour.blurple())
self.assertEqual(embed.description, f"\n`{self.moderator_role.id}` - {self.moderator_role.mention}\n")
示例2
def test_user_command_helper_method_get_requests(self):
"""The helper methods should form the correct get requests."""
test_values = (
{
"helper_method": self.cog.basic_user_infraction_counts,
"expected_args": ("bot/infractions", {'hidden': 'False', 'user__id': str(self.member.id)}),
},
{
"helper_method": self.cog.expanded_user_infraction_counts,
"expected_args": ("bot/infractions", {'user__id': str(self.member.id)}),
},
{
"helper_method": self.cog.user_nomination_counts,
"expected_args": ("bot/nominations", {'user__id': str(self.member.id)}),
},
)
for test_value in test_values:
helper_method = test_value["helper_method"]
endpoint, params = test_value["expected_args"]
with self.subTest(method=helper_method, endpoint=endpoint, params=params):
asyncio.run(helper_method(self.member))
self.bot.api_client.get.assert_called_once_with(endpoint, params=params)
self.bot.api_client.get.reset_mock()
示例3
def test_fetch_webhook_logs_when_unable_to_fetch_webhook(self):
"""The `fetch_webhook` method should log an exception when it fails to fetch the webhook."""
self.bot.fetch_webhook.side_effect = discord.HTTPException(response=MagicMock(), message="Not found.")
self.cog.webhook_id = 1
log = logging.getLogger('bot.cogs.duck_pond')
with self.assertLogs(logger=log, level=logging.ERROR) as log_watcher:
asyncio.run(self.cog.fetch_webhook())
self.bot.wait_until_guild_available.assert_called_once()
self.bot.fetch_webhook.assert_called_once_with(1)
self.assertEqual(len(log_watcher.records), 1)
record = log_watcher.records[0]
self.assertEqual(record.levelno, logging.ERROR)
示例4
def test_send_webhook_correctly_passes_on_arguments(self):
"""The `send_webhook` method should pass the arguments to the webhook correctly."""
self.cog.webhook = helpers.MockAsyncWebhook()
content = "fake content"
username = "fake username"
avatar_url = "fake avatar_url"
embed = "fake embed"
asyncio.run(self.cog.send_webhook(content, username, avatar_url, embed))
self.cog.webhook.send.assert_called_once_with(
content=content,
username=username,
avatar_url=avatar_url,
embed=embed
)
示例5
def test_on_raw_reaction_add_returns_on_message_with_green_checkmark_placed_by_bot(self, count_ducks, is_staff):
"""The `on_raw_reaction_add` event should return when the message has a green check mark placed by the bot."""
channel_id = 31415926535
message_id = 27182818284
user_id = 16180339887
channel, message, member, payload = self._raw_reaction_mocks(channel_id, message_id, user_id)
payload.emoji = helpers.MockPartialEmoji(name=self.unicode_duck_emoji)
payload.emoji.is_custom_emoji.return_value = False
message.reactions = [helpers.MockReaction(emoji=self.checkmark_emoji, users=[self.bot.user])]
is_staff.return_value = True
count_ducks.side_effect = AssertionError("Expected method to return before calling `self.count_ducks`")
self.assertIsNone(asyncio.run(self.cog.on_raw_reaction_add(payload)))
# Assert that we've made it past `self.is_staff`
is_staff.assert_called_once()
示例6
def get(cli_ctx, key, prefix, scope):
'''
Get the value of a key in the configured etcd namespace.
'''
async def _impl():
async with etcd_ctx(cli_ctx) as etcd:
try:
if prefix:
data = await etcd.get_prefix(key, scope=scope)
print(json.dumps(dict(data), indent=4))
else:
val = await etcd.get(key, scope=scope)
if val is None:
sys.exit(1)
print(val)
except Exception:
log.exception('An error occurred.')
with cli_ctx.logger:
asyncio.run(_impl())
示例7
def emulate(self, *coroutines: Iterable[asyncio.coroutine]):
""" Convenience method that runs a full method in a blocking manner.
Performs connect, run, and then disconnect.
Parameters:
*coroutines -- any asyncio coroutines to be executed concurrently
with our emulation
"""
self.connect()
try:
self.run_with(*coroutines)
except KeyboardInterrupt:
pass
finally:
self.disconnect()
#
# I/O interface.
#
示例8
def run():
mdb = None
if 'test' in sys.argv:
import credentials
mdb = motor.motor_asyncio.AsyncIOMotorClient(credentials.test_mongo_url).avrae
else:
mclient = motor.motor_asyncio.AsyncIOMotorClient(os.getenv('MONGO_URL', "mongodb://localhost:27017"))
mdb = mclient[os.getenv('MONGO_DB', "avrae")]
if 'bestiary' in sys.argv:
input(f"Reindexing {mdb.name} bestiaries. Press enter to continue.")
await migrate_bestiaries(mdb)
if 'tome' in sys.argv:
input(f"Reindexing {mdb.name} tomes. Press enter to continue.")
await migrate_tomes(mdb)
if 'pack' in sys.argv:
input(f"Reindexing {mdb.name} packs. Press enter to continue.")
await migrate_packs(mdb)
示例9
def test_async_this_thread(server):
async def _():
loop = asyncio.get_event_loop()
fs = fsspec.filesystem("http", asynchronous=True, loop=loop)
with pytest.raises(RuntimeError):
# fails because client creation has not yet been awaited
await fs._cat(server + "/index/realfile")
await fs.set_session() # creates client
out = await fs._cat(server + "/index/realfile")
del fs
assert out == data
asyncio.run(_())
示例10
def _patch_asyncio():
"""
Patch asyncio module to use pure Python tasks and futures,
use module level _current_tasks, all_tasks and patch run method.
"""
def run(future, *, debug=False):
loop = asyncio.get_event_loop()
loop.set_debug(debug)
return loop.run_until_complete(future)
if sys.version_info >= (3, 6, 0):
asyncio.Task = asyncio.tasks._CTask = asyncio.tasks.Task = \
asyncio.tasks._PyTask
asyncio.Future = asyncio.futures._CFuture = asyncio.futures.Future = \
asyncio.futures._PyFuture
if sys.version_info < (3, 7, 0):
asyncio.tasks._current_tasks = asyncio.tasks.Task._current_tasks # noqa
asyncio.all_tasks = asyncio.tasks.Task.all_tasks # noqa
if not hasattr(asyncio, '_run_orig'):
asyncio._run_orig = getattr(asyncio, 'run', None)
asyncio.run = run
示例11
def main():
import argparse
parser = argparse.ArgumentParser(description='Polls the kerberos service for a TGT for the sepcified user', formatter_class=argparse.RawDescriptionHelpFormatter, epilog = kerberos_url_help_epilog)
parser.add_argument('kerberos_connection_url', help='the kerberos target string. ')
parser.add_argument('ccache', help='ccache file to store the TGT ticket in')
parser.add_argument('-v', '--verbose', action='count', default=0)
args = parser.parse_args()
if args.verbose == 0:
logging.basicConfig(level=logging.INFO)
elif args.verbose == 1:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=1)
asyncio.run(amain(args))
示例12
def main():
import argparse
parser = argparse.ArgumentParser(description='Gets an S4U2proxy ticket impersonating given user', formatter_class=argparse.RawDescriptionHelpFormatter, epilog = kerberos_url_help_epilog)
parser.add_argument('kerberos_connection_url', help='the kerberos target string in the following format <domain>/<username>/<secret_type>:<secret>@<domaincontroller-ip>')
parser.add_argument('spn', help='the service principal in format <service>/<server-hostname>@<domain> Example: cifs/fileserver.test.corp@TEST.corp for a TGS ticket to be used for file access on server "fileserver". IMPORTANT: SERVER\'S HOSTNAME MUST BE USED, NOT IP!!!')
parser.add_argument('targetuser', help='')
parser.add_argument('ccache', help='ccache file to store the TGT ticket in')
parser.add_argument('-v', '--verbose', action='count', default=0)
args = parser.parse_args()
if args.verbose == 0:
logger.setLevel(logging.WARNING)
elif args.verbose == 1:
logger.setLevel(logging.INFO)
else:
logger.setLevel(1)
asyncio.run(amain(args))
示例13
def main():
import argparse
parser = argparse.ArgumentParser(description='Polls the kerberos service for a TGS for the sepcified user and specified service', formatter_class=argparse.RawDescriptionHelpFormatter, epilog = kerberos_url_help_epilog)
parser.add_argument('kerberos_connection_string', help='the kerberos target string in the following format <domain>/<username>/<secret_type>:<secret>@<domaincontroller-ip>')
parser.add_argument('spn', help='the service principal in format <service>/<server-hostname>@<domain> Example: cifs/fileserver.test.corp@TEST.corp for a TGS ticket to be used for file access on server "fileserver". IMPORTANT: SERVER\'S HOSTNAME MUST BE USED, NOT IP!!!')
parser.add_argument('ccache', help='ccache file to store the TGT ticket in')
parser.add_argument('-u', action='store_true', help='Use UDP instead of TCP (not tested)')
parser.add_argument('-v', '--verbose', action='count', default=0)
args = parser.parse_args()
if args.verbose == 0:
logging.basicConfig(level=logging.INFO)
elif args.verbose == 1:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=1)
asyncio.run(amain(args))
示例14
def run(self):
req = self.construct_tgt_req()
rep = await self.ksoc.sendrecv(req.dump(), throw = False)
if rep.name != 'KRB_ERROR':
# user doesnt need preauth, but it exists
return True
elif rep.native['error-code'] != KerberosErrorCode.KDC_ERR_PREAUTH_REQUIRED.value:
# any other error means user doesnt exist
return False
else:
# preauth needed, only if user exists
return True
示例15
def run_cli(self, *args, input: Optional[str]=None):
conn_args = self.get_connect_args()
cmd_args = (
'--host', conn_args['host'],
'--port', str(conn_args['port']),
'--user', conn_args['user'],
) + args
if conn_args['password']:
cmd_args = ('--password-from-stdin',) + cmd_args
if input is not None:
input = f"{conn_args['password']}\n{input}"
else:
input = f"{conn_args['password']}\n"
subprocess.run(
('edgedb',) + cmd_args,
input=input.encode() if input else None,
check=True,
capture_output=True,
)
示例16
def _init(self, pg_connector):
if self._env:
env = os.environ.copy()
env.update(self._env)
else:
env = None
init = subprocess.run(
self._edgedb_cmd + ['--bootstrap'],
stdout=sys.stdout, stderr=sys.stderr,
env=env)
if init.returncode != 0:
raise ClusterError(
f'edgedb-server --bootstrap failed with '
f'exit code {init.returncode}')
示例17
def eva():
"""
Start the eva system
"""
# Get the hostname and port information from the configuration file
config = ConfigurationManager()
hostname = config.get_value('server', 'hostname')
port = config.get_value('server', 'port')
socket_timeout = config.get_value('server', 'socket_timeout')
loop = asyncio.new_event_loop()
stop_server_future = loop.create_future()
# Launch server
try:
asyncio.run(start_server(host=hostname,
port=port,
loop=loop,
socket_timeout=socket_timeout,
stop_server_future=stop_server_future)
)
except Exception as e:
LoggingManager().log(e, LoggingLevel.CRITICAL)
示例18
def with_appcontext(fn: Optional[Callable] = None) -> Callable:
# decorator was used with parenthesis
if fn is None:
return with_appcontext
@click.pass_context
def decorator(__ctx: click.Context, *args: Any, **kwargs: Any) -> Any:
async def _inner() -> Any:
async with __ctx.ensure_object(ScriptInfo).load_app().app_context():
return __ctx.invoke(fn, *args, **kwargs)
return asyncio.run(_inner())
return functools.update_wrapper(decorator, fn)
示例19
def run_command(info: ScriptInfo, host: str, port: int, certfile: str, keyfile: str) -> None:
debug = get_debug_flag()
app = info.load_app()
app.run(
debug=debug, host=host, port=port, certfile=certfile, keyfile=keyfile, use_reloader=True
)
示例20
def test_create_test_on_mock_bot_closes_passed_coroutine(self):
"""`bot.loop.create_task` should close the passed coroutine object to prevent warnings."""
async def dementati():
"""Dummy coroutine for testing purposes."""
coroutine_object = dementati()
bot = helpers.MockBot()
bot.loop.create_task(coroutine_object)
with self.assertRaises(RuntimeError, msg="cannot reuse already awaited coroutine"):
asyncio.run(coroutine_object)
示例21
def _method_subtests(self, method, test_values, default_header):
"""Helper method that runs the subtests for the different helper methods."""
for test_value in test_values:
api_response = test_value["api response"]
expected_lines = test_value["expected_lines"]
with self.subTest(method=method, api_response=api_response, expected_lines=expected_lines):
self.bot.api_client.get.return_value = api_response
expected_output = "\n".join(default_header + expected_lines)
actual_output = asyncio.run(method(self.member))
self.assertEqual(expected_output, actual_output)
示例22
def test_create_user_embed_uses_nick_in_title_if_available(self):
"""The embed should use the nick if it's available."""
ctx = helpers.MockContext(channel=helpers.MockTextChannel(id=1))
user = helpers.MockMember()
user.nick = "Cat lover"
user.__str__ = unittest.mock.Mock(return_value="Mr. Hemlock")
embed = asyncio.run(self.cog.create_user_embed(ctx, user))
self.assertEqual(embed.title, "Cat lover (Mr. Hemlock)")
示例23
def test_create_user_embed_ignores_everyone_role(self):
"""Created `!user` embeds should not contain mention of the @everyone-role."""
ctx = helpers.MockContext(channel=helpers.MockTextChannel(id=1))
admins_role = helpers.MockRole(name='Admins')
admins_role.colour = 100
# A `MockMember` has the @Everyone role by default; we add the Admins to that.
user = helpers.MockMember(roles=[admins_role], top_role=admins_role)
embed = asyncio.run(self.cog.create_user_embed(ctx, user))
self.assertIn("&Admins", embed.description)
self.assertNotIn("&Everyone", embed.description)
示例24
def test_create_user_embed_expanded_information_in_moderation_channels(self, nomination_counts, infraction_counts):
"""The embed should contain expanded infractions and nomination info in mod channels."""
ctx = helpers.MockContext(channel=helpers.MockTextChannel(id=50))
moderators_role = helpers.MockRole(name='Moderators')
moderators_role.colour = 100
infraction_counts.return_value = "expanded infractions info"
nomination_counts.return_value = "nomination info"
user = helpers.MockMember(id=314, roles=[moderators_role], top_role=moderators_role)
embed = asyncio.run(self.cog.create_user_embed(ctx, user))
infraction_counts.assert_called_once_with(user)
nomination_counts.assert_called_once_with(user)
self.assertEqual(
textwrap.dedent(f"""
**User Information**
Created: {"1 year ago"}
Profile: {user.mention}
ID: {user.id}
**Member Information**
Joined: {"1 year ago"}
Roles: &Moderators
expanded infractions info
nomination info
""").strip(),
embed.description
)
示例25
def test_create_user_embed_basic_information_outside_of_moderation_channels(self, infraction_counts):
"""The embed should contain only basic infraction data outside of mod channels."""
ctx = helpers.MockContext(channel=helpers.MockTextChannel(id=100))
moderators_role = helpers.MockRole(name='Moderators')
moderators_role.colour = 100
infraction_counts.return_value = "basic infractions info"
user = helpers.MockMember(id=314, roles=[moderators_role], top_role=moderators_role)
embed = asyncio.run(self.cog.create_user_embed(ctx, user))
infraction_counts.assert_called_once_with(user)
self.assertEqual(
textwrap.dedent(f"""
**User Information**
Created: {"1 year ago"}
Profile: {user.mention}
ID: {user.id}
**Member Information**
Joined: {"1 year ago"}
Roles: &Moderators
basic infractions info
""").strip(),
embed.description
)
示例26
def test_create_user_embed_uses_top_role_colour_when_user_has_roles(self):
"""The embed should be created with the colour of the top role, if a top role is available."""
ctx = helpers.MockContext()
moderators_role = helpers.MockRole(name='Moderators')
moderators_role.colour = 100
user = helpers.MockMember(id=314, roles=[moderators_role], top_role=moderators_role)
embed = asyncio.run(self.cog.create_user_embed(ctx, user))
self.assertEqual(embed.colour, discord.Colour(moderators_role.colour))
示例27
def test_create_user_embed_uses_png_format_of_user_avatar_as_thumbnail(self):
"""The embed thumbnail should be set to the user's avatar in `png` format."""
ctx = helpers.MockContext()
user = helpers.MockMember(id=217)
user.avatar_url_as.return_value = "avatar url"
embed = asyncio.run(self.cog.create_user_embed(ctx, user))
user.avatar_url_as.assert_called_once_with(static_format="png")
self.assertEqual(embed.thumbnail.url, "avatar url")
示例28
def setUp(self):
"""Set up steps executed before each test is run."""
self.bot = helpers.MockBot()
self.cog = information.Information(self.bot)
self.moderator_role = helpers.MockRole(name="Moderators", id=2, position=10)
self.flautist_role = helpers.MockRole(name="Flautists", id=3, position=2)
self.bassist_role = helpers.MockRole(name="Bassists", id=4, position=3)
self.author = helpers.MockMember(id=1, name="syntaxaire")
self.moderator = helpers.MockMember(id=2, name="riffautae", roles=[self.moderator_role])
self.target = helpers.MockMember(id=3, name="__fluzz__")
示例29
def test_regular_member_cannot_target_another_member(self, constants):
"""A regular user should not be able to use `!user` targeting another user."""
constants.MODERATION_ROLES = [self.moderator_role.id]
ctx = helpers.MockContext(author=self.author)
asyncio.run(self.cog.user_info.callback(self.cog, ctx, self.target))
ctx.send.assert_called_once_with("You may not use this command on users other than yourself.")
示例30
def test_regular_member_cannot_use_command_outside_of_bot_commands(self, constants):
"""A regular user should not be able to use this command outside of bot-commands."""
constants.MODERATION_ROLES = [self.moderator_role.id]
constants.STAFF_ROLES = [self.moderator_role.id]
constants.Channels.bot_commands = 50
ctx = helpers.MockContext(author=self.author, channel=helpers.MockTextChannel(id=100))
msg = "Sorry, but you may only use this command within <#50>."
with self.assertRaises(InWhitelistCheckFailure, msg=msg):
asyncio.run(self.cog.user_info.callback(self.cog, ctx))