From d8dfc7119ee3a9475a18fa297ddf86d02ce784b2 Mon Sep 17 00:00:00 2001 From: ekzyis Date: Fri, 24 Sep 2021 23:07:32 +0200 Subject: [PATCH] Add test for ensure_voice --- requirements.txt | 1 + src/bot.py | 1 - test/conftest.py | 13 +++++++++++++ test/test_bot.py | 41 ++++++++++++++++++++++++++++++++++++++--- 4 files changed, 52 insertions(+), 4 deletions(-) diff --git a/requirements.txt b/requirements.txt index c93160a..04e10c6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -25,6 +25,7 @@ PyNaCl==1.4.0 pyparsing==2.4.7 pytest==6.2.5 pytest-cov==2.12.1 +pytest-mock==3.6.1 python-dotenv==0.19.0 six==1.16.0 toml==0.10.2 diff --git a/src/bot.py b/src/bot.py index 0a52a8e..9964019 100644 --- a/src/bot.py +++ b/src/bot.py @@ -32,7 +32,6 @@ class Music(commands.Cog): if ctx.author.voice: await ctx.author.voice.channel.connect() else: - await ctx.send("You are not connected to a voice channel.") raise commands.CommandError("Author not connected to a voice channel.") elif ctx.voice_client.is_playing(): ctx.voice_client.stop() diff --git a/test/conftest.py b/test/conftest.py index bdfc4e1..0a6029a 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -1,6 +1,19 @@ import sys from pathlib import Path +import pytest +from pytest_mock import MockerFixture + # Add source to PATH such that imports within src modules are properly resolved. SRC_PATH = str(Path(__file__).parent / '..' / 'src') sys.path.insert(0, SRC_PATH) + + +@pytest.fixture +def bot(mocker: MockerFixture): + yield mocker.patch('discord.ext.commands.Bot', autospec=True) + + +@pytest.fixture +def ctx(mocker: MockerFixture): + yield mocker.patch('discord.ext.commands.Context', autospec=True) diff --git a/test/test_bot.py b/test/test_bot.py index 8433e13..8c0ca09 100644 --- a/test/test_bot.py +++ b/test/test_bot.py @@ -1,3 +1,38 @@ -def test_bot(): - # placeholder test - assert 1 + 1 == 2 +from unittest.mock import AsyncMock + +import pytest +from discord.ext import commands + +from bot import Music + + +@pytest.mark.asyncio +async def test_bot_ensure_voice(bot, ctx): + mbot = Music(bot) + + # 1. Inside a voice channel + # 1.1 Does not call stop if no sound is playing + ctx.voice_client.is_playing.return_value = False + await mbot.ensure_voice(ctx) + assert ctx.voice_client.stop.call_count == 0 + ctx.reset_mock(return_value=True) + + # 1.2 Does call stop if sound is playing + ctx.voice_client.is_playing.return_value = True + await mbot.ensure_voice(ctx) + assert ctx.voice_client.stop.call_count == 1 + ctx.reset_mock(return_value=True) + + # 2. Not inside a voice channel + # 2.1 Connects to voice channel of author if possible + ctx.voice_client = None + ctx.author.voice = AsyncMock() + await mbot.ensure_voice(ctx) + assert ctx.author.voice.channel.connect.call_count == 1 + ctx.reset_mock(return_value=True) + + # 2.2 Error if author not inside a channel + ctx.voice_client = None + ctx.author.voice = None + with pytest.raises(commands.CommandError): + await mbot.ensure_voice(ctx)