From 0994d88979cbcf8ccf37168f4b4696a302086698 Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Sun, 18 Jun 2023 20:25:22 +0100 Subject: Use the new pydis_core send_to_paste_service function --- tests/bot/exts/utils/snekbox/test_snekbox.py | 13 +--- tests/bot/utils/test_services.py | 90 ---------------------------- 2 files changed, 2 insertions(+), 101 deletions(-) delete mode 100644 tests/bot/utils/test_services.py (limited to 'tests') diff --git a/tests/bot/exts/utils/snekbox/test_snekbox.py b/tests/bot/exts/utils/snekbox/test_snekbox.py index fa28aade8..6d9b6b1e4 100644 --- a/tests/bot/exts/utils/snekbox/test_snekbox.py +++ b/tests/bot/exts/utils/snekbox/test_snekbox.py @@ -5,6 +5,7 @@ from unittest.mock import AsyncMock, MagicMock, Mock, call, create_autospec, pat from discord import AllowedMentions from discord.ext import commands +from pydis_core.utils.paste_service import MAX_PASTE_SIZE from bot import constants from bot.errors import LockedResourceError @@ -56,19 +57,9 @@ class SnekboxTests(unittest.IsolatedAsyncioTestCase): async def test_upload_output_reject_too_long(self): """Reject output longer than MAX_PASTE_LENGTH.""" - result = await self.cog.upload_output("-" * (snekbox._cog.MAX_PASTE_LENGTH + 1)) + result = await self.cog.upload_output("-" * (MAX_PASTE_SIZE + 1)) self.assertEqual(result, "too long to upload") - @patch("bot.exts.utils.snekbox._cog.send_to_paste_service") - async def test_upload_output(self, mock_paste_util): - """Upload the eval output to the URLs.paste_service.format(key="documents") endpoint.""" - await self.cog.upload_output("Test output.") - mock_paste_util.assert_called_once_with( - "Test output.", - extension="txt", - max_length=snekbox._cog.MAX_PASTE_LENGTH - ) - async def test_codeblock_converter(self): ctx = MockContext() cases = ( diff --git a/tests/bot/utils/test_services.py b/tests/bot/utils/test_services.py deleted file mode 100644 index 3c9e037ce..000000000 --- a/tests/bot/utils/test_services.py +++ /dev/null @@ -1,90 +0,0 @@ -import logging -import unittest -from unittest.mock import AsyncMock, MagicMock, Mock, patch - -from aiohttp import ClientConnectorError - -from bot.utils.services import ( - FAILED_REQUEST_ATTEMPTS, MAX_PASTE_LENGTH, PasteTooLongError, PasteUploadError, send_to_paste_service -) -from tests.helpers import MockBot - - -class PasteTests(unittest.IsolatedAsyncioTestCase): - def setUp(self) -> None: - patcher = patch("bot.instance", new=MockBot()) - self.bot = patcher.start() - self.addCleanup(patcher.stop) - - @patch("bot.utils.services.URLs.paste_service", "https://paste_service.com/{key}") - async def test_url_and_sent_contents(self): - """Correct url was used and post was called with expected data.""" - response = MagicMock( - json=AsyncMock(return_value={"key": ""}) - ) - self.bot.http_session.post.return_value.__aenter__.return_value = response - self.bot.http_session.post.reset_mock() - await send_to_paste_service("Content") - self.bot.http_session.post.assert_called_once_with("https://paste_service.com/documents", data="Content") - - @patch("bot.utils.services.URLs.paste_service", "https://paste_service.com/{key}") - async def test_paste_returns_correct_url_on_success(self): - """Url with specified extension is returned on successful requests.""" - key = "paste_key" - test_cases = ( - (f"https://paste_service.com/{key}.txt?noredirect", "txt"), - (f"https://paste_service.com/{key}.py", "py"), - (f"https://paste_service.com/{key}?noredirect", ""), - ) - response = MagicMock( - json=AsyncMock(return_value={"key": key}) - ) - self.bot.http_session.post.return_value.__aenter__.return_value = response - - for expected_output, extension in test_cases: - with self.subTest(msg=f"Send contents with extension {extension!r}"): - self.assertEqual( - await send_to_paste_service("", extension=extension), - expected_output - ) - - async def test_request_repeated_on_json_errors(self): - """Json with error message and invalid json are handled as errors and requests repeated.""" - test_cases = ({"message": "error"}, {"unexpected_key": None}, {}) - self.bot.http_session.post.return_value.__aenter__.return_value = response = MagicMock() - self.bot.http_session.post.reset_mock() - - for error_json in test_cases: - with self.subTest(error_json=error_json): - response.json = AsyncMock(return_value=error_json) - with self.assertRaises(PasteUploadError): - await send_to_paste_service("") - self.assertEqual(self.bot.http_session.post.call_count, FAILED_REQUEST_ATTEMPTS) - - self.bot.http_session.post.reset_mock() - - async def test_request_repeated_on_connection_errors(self): - """Requests are repeated in the case of connection errors.""" - self.bot.http_session.post = MagicMock(side_effect=ClientConnectorError(Mock(), Mock())) - with self.assertRaises(PasteUploadError): - await send_to_paste_service("") - self.assertEqual(self.bot.http_session.post.call_count, FAILED_REQUEST_ATTEMPTS) - - async def test_general_error_handled_and_request_repeated(self): - """All `Exception`s are handled, logged and request repeated.""" - self.bot.http_session.post = MagicMock(side_effect=Exception) - with self.assertRaises(PasteUploadError): - await send_to_paste_service("") - self.assertEqual(self.bot.http_session.post.call_count, FAILED_REQUEST_ATTEMPTS) - self.assertLogs("bot.utils", logging.ERROR) - - async def test_raises_error_on_too_long_input(self): - """Ensure PasteTooLongError is raised if `contents` is longer than `MAX_PASTE_LENGTH`.""" - contents = "a" * (MAX_PASTE_LENGTH + 1) - with self.assertRaises(PasteTooLongError): - await send_to_paste_service(contents) - - async def test_raises_on_too_large_max_length(self): - """Ensure ValueError is raised if `max_length` passed is greater than `MAX_PASTE_LENGTH`.""" - with self.assertRaises(ValueError): - await send_to_paste_service("Hello World!", max_length=MAX_PASTE_LENGTH + 1) -- cgit v1.2.3 From d961f5e2cc89c6c2a30b923756e3304d65f1ae28 Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Thu, 22 Jun 2023 22:33:50 +0100 Subject: Mock _lexers_supported_by_pastebin in test to ensure no call to external service is made --- bot/exts/utils/snekbox/_cog.py | 9 ++++----- tests/bot/exts/utils/snekbox/test_snekbox.py | 4 ++++ 2 files changed, 8 insertions(+), 5 deletions(-) (limited to 'tests') diff --git a/bot/exts/utils/snekbox/_cog.py b/bot/exts/utils/snekbox/_cog.py index f07bcb7df..875357fb3 100644 --- a/bot/exts/utils/snekbox/_cog.py +++ b/bot/exts/utils/snekbox/_cog.py @@ -10,8 +10,7 @@ from typing import Literal, NamedTuple, TYPE_CHECKING from discord import AllowedMentions, HTTPException, Interaction, Message, NotFound, Reaction, User, enums, ui from discord.ext.commands import Cog, Command, Context, Converter, command, guild_only -from pydis_core.utils import interactions -from pydis_core.utils.paste_service import PasteTooLongError, PasteUploadError, send_to_paste_service +from pydis_core.utils import interactions, paste_service from pydis_core.utils.regex import FORMATTED_CODE_REGEX, RAW_CODE_REGEX from bot.bot import Bot @@ -208,15 +207,15 @@ class Snekbox(Cog): log.trace("Uploading full output to paste service...") try: - paste_link = await send_to_paste_service( + paste_link = await paste_service.send_to_paste_service( contents=output, lexer="text", http_session=self.bot.http_session, ) return paste_link["link"] - except PasteTooLongError: + except paste_service.PasteTooLongError: return "too long to upload" - except PasteUploadError: + except paste_service.PasteUploadError: return "unable to upload" @staticmethod diff --git a/tests/bot/exts/utils/snekbox/test_snekbox.py b/tests/bot/exts/utils/snekbox/test_snekbox.py index 6d9b6b1e4..200aa5a20 100644 --- a/tests/bot/exts/utils/snekbox/test_snekbox.py +++ b/tests/bot/exts/utils/snekbox/test_snekbox.py @@ -55,6 +55,10 @@ class SnekboxTests(unittest.IsolatedAsyncioTestCase): ) resp.json.assert_awaited_once() + @patch( + "bot.exts.utils.snekbox._cog.paste_service._lexers_supported_by_pastebin", + {"https://paste.pythondiscord.com": ["text"]}, + ) async def test_upload_output_reject_too_long(self): """Reject output longer than MAX_PASTE_LENGTH.""" result = await self.cog.upload_output("-" * (MAX_PASTE_SIZE + 1)) -- cgit v1.2.3