Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async def test_paginator_interface():
bot = commands.Bot('?')
with open(__file__, 'rb') as file:
paginator = FilePaginator(file, max_size=200)
interface = PaginatorInterface(bot, paginator)
assert interface.pages == paginator.pages
assert interface.page_count == len(paginator.pages)
assert interface.page_size > 200
assert interface.page_size < interface.max_page_size
send_kwargs = interface.send_kwargs
assert isinstance(send_kwargs, dict)
assert 'content' in send_kwargs
content = send_kwargs['content']
assert isinstance(content, str)
assert len(content) <= interface.page_size
embed = send_kwargs['embed']
assert isinstance(embed, discord.Embed)
description = embed.description
assert content.startswith(description)
# check for raise on too large page size
with pytest.raises(ValueError):
PaginatorInterface(None, commands.Paginator(max_size=2000))
# check for raise on not-paginator
with pytest.raises(TypeError):
PaginatorInterface(None, 4)
paginator = commands.Paginator(max_size=100)
for _ in range(100):
paginator.add_line("test text")
# test interfacing
with utils.mock_ctx(bot) as ctx:
interface = PaginatorInterface(bot, paginator)
assert not interface.closed
await interface.send_to(ctx)
await asyncio.sleep(0.1)
await interface.add_line("test text")
)
bot.dispatch(
'raw_reaction_add',
discord.RawReactionActionEvent(payload, emoji, 'REACTION_ADD')
if discord.version_info >= (1, 3) else
discord.RawReactionActionEvent(payload, emoji)
)
await asyncio.sleep(0.1)
assert interface.closed
ctx.send.coro.return_value.delete.assert_called_once()
# test resend, no delete
with utils.mock_ctx(bot) as ctx:
interface = PaginatorInterface(bot, paginator)
assert not interface.closed
await interface.send_to(ctx)
await asyncio.sleep(0.1)
await interface.add_line("test text")
assert interface.page_count > 1
assert not interface.closed
# resend
await interface.send_to(ctx)
await asyncio.sleep(0.1)
await interface.add_line("test text")
# resend
await interface.send_to(ctx)
await asyncio.sleep(0.1)
await interface.add_line("test text")
ctx.send.coro.return_value.delete.assert_not_called()
interface.task.cancel()
await asyncio.sleep(0.1)
assert interface.closed
# test resend, delete
with utils.mock_ctx(bot) as ctx:
interface = PaginatorInterface(bot, paginator, delete_message=True)
assert not interface.closed
await interface.send_to(ctx)
await asyncio.sleep(0.1)
await interface.add_line("test text")
assert interface.page_count > 1
assert not interface.closed
# resend
await interface.send_to(ctx)
await asyncio.sleep(0.1)
await interface.add_line("test text")
try:
async with ReplResponseReactor(ctx.message):
with self.submit(ctx):
executor = AsyncCodeExecutor(argument.content, scope, arg_dict=arg_dict)
async for send, result in AsyncSender(executor):
if result is None:
continue
self.last_result = result
if isinstance(result, discord.File):
send(await ctx.send(file=result))
elif isinstance(result, discord.Embed):
send(await ctx.send(embed=result))
elif isinstance(result, PaginatorInterface):
send(await result.send_to(ctx))
else:
if not isinstance(result, str):
# repr all non-strings
result = repr(result)
if len(result) > 2000:
# inconsistency here, results get wrapped in codeblocks when they are too large
# but don't if they're not. probably not that bad, but noting for later review
paginator = WrappedPaginator(prefix='```py', suffix='```', max_size=1985)
paginator.add_line(result)
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
send(await interface.send_to(ctx))
else:
async def jsk_shell(self, ctx: commands.Context, *, argument: codeblock_converter):
"""
Executes statements in the system shell.
This uses the system shell as defined in $SHELL, or `/bin/bash` otherwise.
Execution can be cancelled by closing the paginator.
"""
async with ReplResponseReactor(ctx.message):
with self.submit(ctx):
paginator = WrappedPaginator(prefix="```sh", max_size=1985)
paginator.add_line(f"$ {argument.content}\n")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
self.bot.loop.create_task(interface.send_to(ctx))
with ShellReader(argument.content) as reader:
async for line in reader:
if interface.closed:
return
await interface.add_line(line)
await interface.add_line(f"\n[status] Return code {reader.close_code}")
with self.submit(ctx):
executor = AsyncCodeExecutor(argument.content, scope, arg_dict=arg_dict)
async for send, result in AsyncSender(executor):
self.last_result = result
header = repr(result).replace("``", "`\u200b`").replace(self.bot.http.token, "[token omitted]")
if len(header) > 485:
header = header[0:482] + "..."
paginator = WrappedPaginator(prefix=f"```prolog\n=== {header} ===\n", max_size=1985)
for name, res in all_inspections(result):
paginator.add_line(f"{name:16.16} :: {res}")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
send(await interface.send_to(ctx))
finally:
scope.clear_intersection(arg_dict)
if size <= 0:
return await ctx.send(f"`{path}`: Cowardly refusing to read a file with no size stat"
f" (it may be empty, endless or inaccessible).")
if size > 50 * (1024 ** 2):
return await ctx.send(f"`{path}`: Cowardly refusing to read a file >50MB.")
try:
with open(path, "rb") as file:
paginator = WrappedFilePaginator(file, line_span=line_span, max_size=1985)
except UnicodeDecodeError:
return await ctx.send(f"`{path}`: Couldn't determine the encoding of this file.")
except ValueError as exc:
return await ctx.send(f"`{path}`: Couldn't read this file, {exc}")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
await interface.send_to(ctx)
Execution can be cancelled by closing the paginator.
"""
message = message if message is not None else "Updated files."
if pull_push == "push":
shellcmd = f'sudo git add .&&sudo git commit -m "{message}"&&sudo git push'
elif pull_push == "pull":
shellcmd = 'sudo git pull'
else:
return await ctx.send("Invalid option given")
async with ReplResponseReactor(ctx.message):
paginator = WrappedPaginator(prefix="```sh", max_size=1985)
paginator.add_line(f"$ git {pull_push}\n")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
self.bot.loop.create_task(interface.send_to(ctx))
with ShellReader(shellcmd) as reader:
async for line in reader:
if interface.closed:
return
await interface.add_line(line)
async def jsk_tasks(self, ctx: commands.Context):
"""
Shows the currently running jishaku tasks.
"""
if not self.tasks:
return await ctx.send("No currently running tasks.")
paginator = commands.Paginator(max_size=1985)
for task in self.tasks:
paginator.add_line(f"{task.index}: `{task.ctx.command.qualified_name}`, invoked at "
f"{task.ctx.message.created_at.strftime('%Y-%m-%d %H:%M:%S')} UTC")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
return await interface.send_to(ctx)