aboutsummaryrefslogtreecommitdiffstats
path: root/tests/cogs/test_math_commands.py
blob: 21e9a2ee10181cc15080e06295f621e8fb480b01 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from conftest import MockApplicationContext


@pytest.fixture
def math_cog(bot):
    from cogs.math_commands import Math
    cog = Math(bot)
    return cog


@pytest.mark.asyncio
async def test_math_command_valid_expression(math_cog, mock_channel, mock_guild, bot):
    ctx = MockApplicationContext(bot=bot, channel=mock_channel, guild=mock_guild)

    mock_process = MagicMock()
    mock_process.returncode = 0
    mock_process.communicate = AsyncMock(return_value=(b"4", b""))

    with patch('cogs.math_commands.asyncio.create_subprocess_exec', return_value=mock_process) as mock_subprocess:
        with patch('cogs.math_commands.re.search', return_value=None):
            with patch.object(ctx, 'respond', new_callable=AsyncMock) as mock_respond:
                await math_cog.math.callback(math_cog, ctx, equation="2+2")
                mock_subprocess.assert_called_once()
                mock_respond.assert_called_once()


@pytest.mark.asyncio
async def test_math_command_invalid_expression(math_cog, mock_channel, mock_guild, bot):
    ctx = MockApplicationContext(bot=bot, channel=mock_channel, guild=mock_guild)

    with patch('cogs.math_commands.re.search', return_value=MagicMock()):
        with patch.object(ctx, 'respond', new_callable=AsyncMock) as mock_respond:
            await math_cog.math.callback(math_cog, ctx, equation="eval(1)")
            mock_respond.assert_called_once()
            args = mock_respond.call_args
            assert "Invalid" in str(args)


@pytest.mark.asyncio
async def test_math_command_process_error(math_cog, mock_channel, mock_guild, bot):
    ctx = MockApplicationContext(bot=bot, channel=mock_channel, guild=mock_guild)

    mock_process = MagicMock()
    mock_process.returncode = 1
    mock_process.communicate = AsyncMock(return_value=(b"", b"Error: invalid expression"))

    with patch('cogs.math_commands.asyncio.create_subprocess_exec', return_value=mock_process):
        with patch('cogs.math_commands.re.search', return_value=None):
            with patch.object(ctx, 'respond', new_callable=AsyncMock) as mock_respond:
                await math_cog.math.callback(math_cog, ctx, equation="2++")
                mock_respond.assert_called_once()
                args = mock_respond.call_args
                assert "error" in str(args).lower() or "Error" in str(args)