[英]AttributeError: 'function' object has no attribute 'get' when testing Flask requests
下午好,我正在为我的 Flask 应用程序开发一些单元测试。 这是我第一次尝试为 Flask 应用程序开发单元测试,但我目前在尝试测试 GET 请求时遇到此错误。
def testTagCategories():
> response = client.get("/forum")
E AttributeError: 'function' object has no attribute 'get'
我一直在努力寻找问题所在,因为我已按照 Flask 文档中要求的所有步骤进行操作。 这是代码。
@pytest.fixture(scope='session')
def test_client():
flask_app = app()
testing_client = flask_app.test_client()
ctx = flask_app.app_context()
ctx.push()
yield testing_client
ctx.pop()
@pytest.fixture()
def client(app):
return app.test_client()
@pytest.fixture()
def runner(app):
return app.test_cli_runner()
最后,这是我收到错误的功能之一。 提前致谢。
def test_access():
response = client.get("/")
assert (response.status_code == 200)
我也在学习对 flask controller 进行单元测试,所以请对我的回答持保留态度。
但是在失败的代码中(如下所示)似乎没有客户端实例,因此您无法调用 get 方法。
def test_access():
response = client.get("/")
assert (response.status_code == 200)
我确信有一种更好的方法可以在每次测试之前创建客户端(这就是我用另一种我更熟悉的语言来做的方式,比如 C# 在每次测试之前进行设置/拆卸)。
但是这样的事情对我有用:
from app import application
def test_access():
client = application.test_client()
response = client.get('/')
assert response.status_code == 200
html = response.data.decode()
assert 'xxx' in html
在我的应用程序目录中有一个 __init__.py ,里面有 application = Flask(__name__) 。 这就是 from app import 应用程序正在导入的内容。
不过,很想听听某人提供更好的解决方案。
编辑:在导致错误的 function 上,尝试将签名更改为以下内容:
def test_access(client):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.