Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Discord机器人的Unittest或Pytest_Python_Discord.py_Pytest - Fatal编程技术网

Python Discord机器人的Unittest或Pytest

Python Discord机器人的Unittest或Pytest,python,discord.py,pytest,Python,Discord.py,Pytest,编写单元测试/Pytests 我有一个discord机器人,我正试图为它编写测试。我尝试了一个名为distest的库,它在某些方面效果很好,但不是所有方面 我有第二个bot,它发送消息并检查响应,但它不能与Unittests或Pytest一起工作 这是我的一个测试示例, 如果发送了“ping”,它将检查回复“Pong!” 在使用pytest调用脚本之前,我运行需要测试的bot from discord.ext import commands from dotenv import load_dot

编写单元测试/Pytests

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

我有第二个bot,它发送消息并检查响应,但它不能与Unittests或Pytest一起工作

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

在使用pytest调用脚本之前,我运行需要测试的bot

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时,它只是挂起,什么也没做

您在运行bot后尝试注册ping命令<代码>bot.run(令牌)必须是代码的结尾。此外,您还必须将一个装饰程序放入重新注册命令。因此,代码如下所示:

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

我想你不明白我在问什么。我正在尝试测试我的机器人,而不是用命令运行它。我已经有一个bot正在运行,第二个bot将尝试使用pytest进行这些测试