You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PytestCollectionWarning:无法收集Quart实例test_app问题求解

解决PytestCollectionWarning:无法收集'test_app'的方案

问题原因

pytest会自动收集所有以test_开头的对象(包括变量、函数、类)作为测试用例,你的test_app是Quart应用实例,不是可执行的测试函数,因此被误收集触发警告。你之前设置的test=False是Quart应用的参数,和pytest的收集规则无关,所以无法解决问题。

可行解决方案

方案1:重命名变量(最简单直接)

把test_app改成不以test_开头的名称,彻底避免被pytest误收集:

# Create the Quart app
app_instance = app.create_app()

def event_runner():
    policy = asyncio.get_event_loop_policy()
    loop = policy.new_event_loop()
    yield loop
    loop.close()

方案2:将test_app移至非测试模块

把应用实例的创建代码放到单独的配置模块(比如conftest.py或app_setup.py)中,在测试文件里导入使用,这样测试模块中就不会存在test_开头的实例变量:

# 在conftest.py中
import app
import asyncio

app_instance = app.create_app()

def event_runner():
    policy = asyncio.get_event_loop_policy()
    loop = policy.new_event_loop()
    yield loop
    loop.close()

之后在测试文件中直接导入app_instance即可。

方案3:通过pytest配置过滤收集项

在项目根目录的conftest.py中添加自定义收集规则,过滤掉名为test_app的对象:

def pytest_collection_modifyitems(session, config, items):
    # 移除名为test_app的收集项
    items[:] = [item for item in items if item.name != "test_app"]

方案4:用pytest标记跳过该变量

在test_app定义后添加标记,告诉pytest不要将其作为测试用例:

import pytest
import app
import asyncio

# Create the Quart app
test_app = app.create_app()
# 标记该变量不是测试用例
pytest.mark.skip(test_app, reason="Quart app instance, not a test function")

def event_runner():
    policy = asyncio.get_event_loop_policy()
    loop = policy.new_event_loop()
    yield loop
    loop.close()

内容的提问来源于stack exchange,提问作者Harish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 15:52:25