【问题标题】:Unittest or Pytest for Discord BotDiscord Bot 的 Unittest 或 Pytest
【发布时间】:2021-04-23 09:27:35
【问题描述】:

编写单元测试/Pytests

我有一个不和谐的机器人,我正在尝试为它编写测试。我尝试了一个名为 distest 的库,它在某些方面效果很好,但不是全部..

我有第二个机器人发送消息并检查响应,但它不能与 Unittests 或 Pytest 一起使用。

这是我的一项测试的示例, 它正在检查回复“Pong!”如果发送了“ping”。

我在使用 pytest 调用脚本之前运行需要测试的机器人

from discord.ext import commands
from dotenv import load_dotenv
import os
import pytest

TOKEN = "bot token of tester bot"
bot = commands.Bot(command_prefix='?/')
bot.run(TOKEN)
target_id = "ID of bot to be tested"
channel_id = "ID of channel of where it will be tested"

async def test_ping():
    correct_response = 'Pong!'
    channel = await bot.fetch_channel(channel_id)
    await channel.send("ping")

    def check(m):
        return m.content == correct_response and m.author.id == target_id

    response = await bot.wait_for('message', check=check)
    assert (response.content == correct_response)

Pytests 卡在收集上,当我尝试 Unittests 时,它只是挂起,什么也没做

【问题讨论】:

    标签: python discord.py pytest


    【解决方案1】:

    您确实在运行机器人后尝试注册 ping 命令。 bot.run(TOKEN) 必须是代码的结尾。此外,您必须将装饰器放入重新注册命令。所以代码是这样的:

    from discord.ext import commands
    from dotenv import load_dotenv
    import os
    import pytest
    
    TOKEN = "bot token of tester bot"
    bot = commands.Bot(command_prefix='?/')
    target_id = "ID of bot to be tested"
    channel_id = "ID of channel of where it will be tested"
    
    @bot.command(name="ping") #if name did not entered, function name will be the command name
    async def test_ping(ctx): #Every command takes context object as first parameter
        correct_response = 'Pong!'
        channel = await bot.fetch_channel(channel_id)
        await channel.send("ping")
    
        def check(m):
            return m.content == correct_response and m.author.id == target_id
    
        response = await bot.wait_for('message', check=check)
        assert (response.content == correct_response)
    
    bot.run(TOKEN)
    

    基本上是上下文对象:

    await ctx.send("message") #sends message to command's invoked channel.
    ctx.guild #returns server if not channel is a DM channel
    ctx.channel #returns channel
    ctx.author #returns message's author
    ctx.message #returns message
    ctx.message.content #returns the messsge's content
    

    【讨论】:

    • 我认为你不明白我在问什么。我正在尝试测试我的机器人,而不是使用命令运行它。我已经有一个机器人正在运行,第二个机器人将尝试使用 pytest 通过这些测试对其进行测试
    猜你喜欢
    • 2015-03-13
    • 2021-06-15
    • 2021-07-03
    • 2021-01-19
    • 2022-10-21
    • 2021-07-04
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    相关资源
    最近更新 更多