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 )
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 = ("Infractions", "expanded infractions info") nomination_counts.return_value = ("Nominations", "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""" Created: {"1 year ago"} Profile: {user.mention} ID: {user.id} """).strip(), embed.fields[0].value ) self.assertEqual( textwrap.dedent(f""" Joined: {"1 year ago"} Roles: &Moderators """).strip(), embed.fields[1].value )
async 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') infraction_counts.return_value = ("Infractions", "basic infractions info") user = helpers.MockMember(id=314, roles=[moderators_role], colour=100) embed = await self.cog.create_user_embed(ctx, user) infraction_counts.assert_called_once_with(user) self.assertEqual( textwrap.dedent(f""" Created: {"1 year ago"} Profile: {user.mention} ID: {user.id} """).strip(), embed.fields[0].value ) self.assertEqual( textwrap.dedent(f""" Joined: {"1 year ago"} Roles: &Moderators """).strip(), embed.fields[1].value ) self.assertEqual( "basic infractions info", embed.fields[2].value )
async def test_sync_confirmation_context_redirect(self): """If ctx is given, a new message should be sent and author should be ctx's author.""" mock_member = helpers.MockMember() subtests = ( (None, self.bot.user, None), (helpers.MockContext(author=mock_member), mock_member, helpers.MockMessage()), ) for ctx, author, message in subtests: with self.subTest(ctx=ctx, author=author, message=message): if ctx is not None: ctx.send.return_value = message # Make sure `_get_diff` returns a MagicMock, not an AsyncMock self.syncer._get_diff.return_value = mock.MagicMock() self.syncer._get_confirmation_result = mock.AsyncMock( return_value=(False, None)) guild = helpers.MockGuild() await self.syncer.sync(guild, ctx) if ctx is not None: ctx.send.assert_called_once() self.syncer._get_confirmation_result.assert_called_once() self.assertEqual( self.syncer._get_confirmation_result.call_args[0][1], author) self.assertEqual( self.syncer._get_confirmation_result.call_args[0][2], message)
async 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) await self.cog.user_info(self.cog, ctx, self.target) ctx.send.assert_called_once_with("You may not use this command on users other than yourself.")
def test_bot_latency_correct_time(self, create_embed, constants): """Ping should return correct ping responses dependent on message sent.""" ctx = helpers.MockContext() ctx.message = helpers.MockMessage() timestamp = 1587263832 ctx.message.created_at = datetime.fromtimestamp(timestamp) self.assertEqual( information.time_difference_milliseconds(datetime.fromtimestamp(1587263836), ctx.message), 4000)
async def test_create_user_embed_uses_blurple_colour_when_user_has_no_roles(self): """The embed should be created with a blurple colour if the user has no assigned roles.""" ctx = helpers.MockContext() user = helpers.MockMember(id=217) embed = await self.cog.create_user_embed(ctx, user) self.assertEqual(embed.colour, discord.Colour.blurple())
def setUp(self): """Sets up fresh objects for each test.""" self.bot = helpers.MockBot() self.cog = information.Information(self.bot) self.ctx = helpers.MockContext() self.ctx.author.roles.append(self.moderator_role)
async def test_convert_command(self): context = helpers.MockContext() await self.cog.convert(self.cog, context, number=32) self.assertEqual( context.send.call_args.kwargs["embed"].description, "```32°F is 0.00°C```", )
async def test_regular_user_can_explicitly_target_themselves(self, create_embed, _): """A user should target itself with `!user` when a `user` argument was not provided.""" constants.STAFF_ROLES = [self.moderator_role.id] ctx = helpers.MockContext(author=self.author, channel=self.bot_command_channel) await self.cog.user_info(self.cog, ctx, self.author) create_embed.assert_called_once_with(ctx, self.author) ctx.send.assert_called_once()
async 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] 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): await self.cog.user_info(self.cog, ctx)
async def test_embedjson_command(self): context = helpers.MockContext() await self.cog.embed_json(self.cog, context, message=helpers.MockMessage()) self.assertEqual( context.send.call_args.kwargs["embed"].description[:61], '```json\n<MagicMock name="mock.embeds.__getitem__().to_dict()"', )
async def test_staff_members_can_bypass_channel_restriction(self, create_embed, constants): """Staff members should be able to bypass the bot-commands channel restriction.""" constants.STAFF_ROLES = [self.moderator_role.id] ctx = helpers.MockContext(author=self.moderator, channel=helpers.MockTextChannel(id=200)) await self.cog.user_info(self.cog, ctx) create_embed.assert_called_once_with(ctx, self.moderator) ctx.send.assert_called_once()
async def test_twos_command(self): context = helpers.MockContext() await self.cog.twos(self.cog, context, number=32, bits=8) self.assertEqual( context.send.call_args.kwargs["embed"].description, "```00100000```", )
async def test_ones_command(self): context = helpers.MockContext() await self.cog.ones(self.cog, context, number=32) self.assertEqual( context.send.call_args.kwargs["embed"].description, "```011111```", )
async def test_regular_user_may_use_command_in_bot_commands_channel(self, create_embed, constants): """A regular user should be allowed to use `!user` targeting themselves in bot-commands.""" constants.STAFF_ROLES = [self.moderator_role.id] ctx = helpers.MockContext(author=self.author, channel=self.bot_command_channel) await self.cog.user_info(self.cog, ctx) create_embed.assert_called_once_with(ctx, self.author) ctx.send.assert_called_once()
async def test_calc_command(self): context = helpers.MockContext() await self.cog.calc(self.cog, context, num_base="hex", args="0x7d * 0x7d") self.assertEqual( context.send.call_args.kwargs["embed"].description, "```ml\n125 * 125\n\n3d09\n\nDecimal: 15625```", )
async 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') user = helpers.MockMember(id=314, roles=[moderators_role], colour=100) embed = await self.cog.create_user_embed(ctx, user) self.assertEqual(embed.colour, discord.Colour(100))
async 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 = await self.cog.create_user_embed(ctx, user) self.assertEqual(embed.title, "Cat lover (Mr. Hemlock)")
async def test_create_user_embed_uses_string_representation_of_user_in_title_if_nick_is_not_available(self): """The embed should use the string representation of the user if they don't have a nick.""" ctx = helpers.MockContext(channel=helpers.MockTextChannel(id=1)) user = helpers.MockMember() user.nick = None user.__str__ = unittest.mock.Mock(return_value="Mr. Hemlock") embed = await self.cog.create_user_embed(ctx, user) self.assertEqual(embed.title, "Mr. Hemlock")
async def test_ship_command(self): context = helpers.MockContext( guild=helpers.MockGuild( members=[helpers.MockMember(), helpers.MockMember()] ) ) await self.cog.ship(self.cog, context) self.assertEqual(context.send.call_args.kwargs.get("embed"), None)
def test_mock_context_default_initialization(self): """Tests if MockContext initializes with the correct values.""" context = helpers.MockContext() # The `spec` argument makes sure `isistance` checks with `discord.ext.commands.Context` pass self.assertIsInstance(context, discord.ext.commands.Context) self.assertIsInstance(context.bot, helpers.MockBot) self.assertIsInstance(context.guild, helpers.MockGuild) self.assertIsInstance(context.author, helpers.MockMember)
async 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 = await 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")
async def test_match_command(self): context = helpers.MockContext() await self.cog.match( self.cog, context, user1=helpers.MockMember(name="Snake Bot", id=744747000293228684), ) self.assertEqual(context.send.call_args.kwargs.get("embed"), None)
def setUp(self): """ Set up a clean environment for each test. Each check takes a context object, except for is_mod which can take either a context object or a member object. """ self.ctx = helpers.MockContext() self.member = self.ctx.author self.loop = asyncio.new_event_loop()
async def test_moderators_can_target_another_member(self, create_embed, constants): """A moderator should be able to use `!user` targeting another user.""" constants.MODERATION_ROLES = [self.moderator_role.id] constants.STAFF_ROLES = [self.moderator_role.id] ctx = helpers.MockContext(author=self.moderator, channel=helpers.MockTextChannel(id=50)) await self.cog.user_info(self.cog, ctx, self.target) create_embed.assert_called_once_with(ctx, self.target) ctx.send.assert_called_once()
async def test_stock_command(self): context = helpers.MockContext() context.invoked_subcommand = None context.subcommand_passed = "TSLA" await self.cog.stock(self.cog, context) self.assertNotEqual( context.send.call_args.kwargs["embed"].description, "```No stock found for TSLA```", )
def test_regular_user_can_explicitly_target_themselves(self, create_embed, constants): """A user should target itself with `!user` when a `user` argument was not provided.""" constants.STAFF_ROLES = [self.moderator_role.id] constants.Channels.bot_commands = 50 ctx = helpers.MockContext(author=self.author, channel=helpers.MockTextChannel(id=50)) asyncio.run(self.cog.user_info.callback(self.cog, ctx, self.author)) create_embed.assert_called_once_with(ctx, self.author) ctx.send.assert_called_once()
async 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') # A `MockMember` has the @Everyone role by default; we add the Admins to that. user = helpers.MockMember(roles=[admins_role], colour=100) embed = await self.cog.create_user_embed(ctx, user) self.assertIn("&Admins", embed.fields[1].value) self.assertNotIn("&Everyone", embed.fields[1].value)
async def test_animal_commands(self): if not bot.client_session: bot.client_session = ClientSession() context = helpers.MockContext() await asyncio.gather( *[ self.run_command(command, context) for command in self.cog.walk_commands() ] )