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

使用pytest测试Flask应用时出现AttributeError错误求助

解决pytest测试Flask应用时的AttributeError错误

错误原因

你的conftest.py中app fixture的定义存在问题:

@pytest.fixture()
def app():
    yield app

这里yield app返回的是fixture函数本身(因为函数名就是app),而不是Flask应用实例。pytest-flask插件尝试修改app.response_class时,发现拿到的是函数对象,自然没有这个属性,所以抛出AttributeError。

修复步骤

1. 修正conftest.py的app fixture

修改conftest.py,先从app.py导入真实的Flask应用实例,再yield它:

import pytest
from app import app  # 导入Flask app实例

@pytest.fixture()
def app():
    yield app  # 现在yield的是Flask应用实例

@pytest.fixture()
def client(app):
    return app.test_client()

@pytest.fixture()
def runner(app):
    return app.test_cli_runner()

2. 调整test_app.py的测试代码

  • 不需要再手动导入app,fixture会注入client
  • response.get_data()返回的是字节串,要么和b"Hello World!"对比,要么用get_data(as_text=True)转成字符串再对比
    修改后的test_app.py:
import pytest

def test_request(client):
    response = client.get("/")
    # 方式1:对比字节串
    assert response.get_data() == b"Hello World!"
    # 方式2:转成字符串对比
    # assert response.get_data(as_text=True) == "Hello World!"
    assert response.status_code == 200

3. 运行测试

现在重新执行pytest,错误应该会消失,测试可以正常通过。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:10:36