def test_predicate_eval_emoji_reaction(self): """Test the predicate_eval_emoji_reaction function.""" valid_reaction = MockReaction(message=MockMessage(id=1)) valid_reaction.__str__.return_value = snekbox.REEVAL_EMOJI valid_ctx = MockContext(message=MockMessage(id=1), author=MockUser(id=2)) valid_user = MockUser(id=2) invalid_reaction_id = MockReaction(message=MockMessage(id=42)) invalid_reaction_id.__str__.return_value = snekbox.REEVAL_EMOJI invalid_user_id = MockUser(id=42) invalid_reaction_str = MockReaction(message=MockMessage(id=1)) invalid_reaction_str.__str__.return_value = ':longbeard:' cases = ((invalid_reaction_id, valid_user, False, 'invalid reaction ID'), (valid_reaction, invalid_user_id, False, 'invalid user ID'), (invalid_reaction_str, valid_user, False, 'invalid reaction __str__'), (valid_reaction, valid_user, True, 'matching attributes')) for reaction, user, expected, testname in cases: with self.subTest( msg=f'Test with {testname} and expected return {expected}' ): actual = snekbox.predicate_eval_emoji_reaction( valid_ctx, reaction, user) self.assertEqual(actual, expected)
def before_request(): # In a real app, the current user and consumer would be determined by # a lookup in either the session or the request headers, as described # in the Annotator authentication documentation[1]. # # [1]: https://github.com/okfn/annotator/wiki/Authentication g.user = MockUser('alice') # By default, this test application won't do full-on authentication # tests. Set AUTH_ON to True in the config file to enable (limited) # authentication testing. if current_app.config['AUTH_ON']: # g.auth = auth.Authenticator(lambda x: MockConsumer('annotateit')) consumer_obj = Consumer('yourconsumerkey') consumer_obj.secret = '6E1C924B-C03B-4F7F-0000-B72EE2338B39' consumer_obj.ttl = auth.DEFAULT_TTL g.auth = auth.Authenticator(lambda x: consumer_obj) else: g.auth = MockAuthenticator() # Similarly, this test application won't prevent you from modifying # annotations you don't own, deleting annotations you're disallowed # from deleting, etc. Set AUTHZ_ON to True in the config file to # enable authorization testing. if current_app.config['AUTHZ_ON']: g.authorize = authz.authorize print("[run.py,before_request], AUTHZ_ON") else: g.authorize = mock_authorizer print("[run.py,before_request], AUTHZ_OFF")
async def test_archive_relays_incident(self): """ If webhook is found, method relays `incident` properly. This test will assert that the fetched webhook's `send` method is fed the correct arguments, and that the `archive` method returns True. """ webhook = MockAsyncWebhook() self.cog_instance.bot.fetch_webhook = AsyncMock( return_value=webhook) # Patch in our webhook # Define our own `incident` to be archived incident = MockMessage( content="this is an incident", author=MockUser(name="author_name", display_avatar=Mock(url="author_avatar")), id=123, ) built_embed = MagicMock(discord.Embed, id=123) # We patch `make_embed` to return this with patch("bot.exts.moderation.incidents.make_embed", AsyncMock(return_value=(built_embed, None))): archive_return = await self.cog_instance.archive( incident, MagicMock(value="A"), MockMember()) # Now we check that the webhook was given the correct args, and that `archive` returned True webhook.send.assert_called_once_with( embed=built_embed, username="******", avatar_url="author_avatar", file=None, ) self.assertTrue(archive_return)
def setUp(self) -> None: """Prepare a mock message which should qualify as an incident.""" self.incident = MockMessage( channel=MockTextChannel(id=123), content="this is an incident", author=MockUser(bot=False), pinned=False, )
async def test_voice_ban_user_left_guild(self, apply_infraction_mock, post_infraction_mock, _): """Should voice ban user that left the guild without throwing an error.""" infraction = {"foo": "bar"} post_infraction_mock.return_value = {"foo": "bar"} user = MockUser() await self.cog.voiceban(self.cog, self.ctx, user, reason=None) post_infraction_mock.assert_called_once_with(self.ctx, user, "voice_ban", None, active=True, expires_at=None) apply_infraction_mock.assert_called_once_with(self.cog, self.ctx, infraction, user, ANY) # Test action action = self.cog.apply_infraction.call_args[0][-1] self.assertTrue(inspect.iscoroutine(action)) await action
async def test_archive_clyde_username(self): """ The archive webhook username is cleansed using `sub_clyde`. Discord will reject any webhook with "clyde" in the username field, as it impersonates the official Clyde bot. Since we do not control what the username will be (the incident author name is used), we must ensure the name is cleansed, otherwise the relay may fail. This test assumes the username is passed as a kwarg. If this test fails, please review whether the passed argument is being retrieved correctly. """ webhook = MockAsyncWebhook() self.cog_instance.bot.fetch_webhook = AsyncMock(return_value=webhook) message_from_clyde = MockMessage(author=MockUser( name="clyde the great")) await self.cog_instance.archive(message_from_clyde, MagicMock(incidents.Signal), MockMember()) self.assertNotIn("clyde", webhook.send.call_args.kwargs["username"])
def before_request(): # In a real app, the current user and consumer would be determined by # a lookup in either the session or the request headers, as described # in the Annotator authentication documentation[1]. # # [1]: https://github.com/okfn/annotator/wiki/Authentication g.user = MockUser('anonymous') # By default, this test application won't do full-on authentication # tests. Set AUTH_ON to True in the config file to enable (limited) # authentication testing. if current_app.config['AUTH_ON']: g.auth = auth.Authenticator(lambda x: MockConsumer('annotateit')) else: g.auth = MockAuthenticator() # Similarly, this test application won't prevent you from modifying # annotations you don't own, deleting annotations you're disallowed # from deleting, etc. Set AUTHZ_ON to True in the config file to # enable authorization testing. if current_app.config['AUTHZ_ON']: g.authorize = authz.authorize else: g.authorize = mock_authorizer
def setUp(self): self.bot = MockBot() self.member = MockMember(id=1234) self.user = MockUser(id=1234) self.ctx = MockContext(bot=self.bot, author=self.member)
async def test_post_user(self): """Should POST a new user and return the response if successful or otherwise send an error message.""" user = MockUser(discriminator=5678, id=1234, name="Test user") not_user = MagicMock(discriminator=3333, id=5678, name="Wrong user") test_cases = [ { "user": user, "post_result": "bar", "raise_error": None, "payload": { "discriminator": 5678, "id": self.user.id, "in_guild": False, "name": "Test user", "roles": [] } }, { "user": self.member, "post_result": "foo", "raise_error": ResponseCodeError(MagicMock(status=400), "foo"), "payload": { "discriminator": 0, "id": self.member.id, "in_guild": False, "name": "Name unknown", "roles": [] } }, { "user": not_user, "post_result": "bar", "raise_error": None, "payload": { "discriminator": not_user.discriminator, "id": not_user.id, "in_guild": False, "name": not_user.name, "roles": [] } } ] for case in test_cases: user = case["user"] post_result = case["post_result"] raise_error = case["raise_error"] payload = case["payload"] with self.subTest(user=user, post_result=post_result, raise_error=raise_error, payload=payload): self.bot.api_client.post.reset_mock(side_effect=True) self.ctx.bot.api_client.post.return_value = post_result self.ctx.bot.api_client.post.side_effect = raise_error result = await utils.post_user(self.ctx, user) if raise_error: self.assertIsNone(result) self.ctx.send.assert_awaited_once() self.assertIn(str(raise_error.status), self.ctx.send.call_args[0][0]) else: self.assertEqual(result, post_result) self.bot.api_client.post.assert_awaited_once_with("bot/users", json=payload)
# Monkeypatching Path.home() to force creation of a new dir monkeypatch.setattr(Path, "home", lambda: tmp_path) test_bot = edubot.__class__() # Creating a new instance of EduBot assert str(test_bot.datadir) == str(tmp_path / ".edubot") @pytest.mark.asyncio async def test_on_ready(edubot, capture_print): """Checking if the correct print statement is isued `on_ready`.""" await edubot.on_ready() assert capture_print.statement == "None has connected to Discord!" TEST_DM_TEST_CASES = { "argnames": "member", "argvalues": [MockUser(name="Uncle"), MockMember(name="Bob")], } @pytest.mark.parametrize(**TEST_DM_TEST_CASES) @pytest.mark.asyncio async def test_dm_with_qualified_user( edubot, member, capture_print, ): """Testing if direct messaging works on discord objects.""" # Testing with dm_channel already existing await edubot.dm(member, f"Hello {member.name}. This is Pytest!")
def test_is_incident_false_author(self): """Message doesn't qualify if author is a bot.""" self.incident.author = MockUser(bot=True) self.check_false()