gpt4 book ai didi

python - 如何测试使用上下文参数的 Flask API

转载 作者:行者123 更新时间:2023-12-01 07:09:10 28 4
gpt4 key购买 nike

我在编程方面还很陌生,但我无法尝试为此应用程序创建单元测试,它非常简单:

from flask import Flask, request,jsonify,make_response

app = Flask(__name__)


@app.route('/header')
def my_route():
text = request.args.get('text')
tag = request.args.get('tag',default=0,type=int)
if text.find('.')==-1:
if tag==0:
return jsonify(header=text.title())
else:
return jsonify(header= '<h' + str(tag) + '>' + text.title() + '</h' + str(tag) + '>' ) # HTML TAG
else:
return make_response(jsonify(error='Dots are not allowed in headers'),400) #BAD REQUEST ERROR 400


if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')

我尝试过这样的事情:

from main import app
from flask import json

def test_my_route():
response = app.test_client().get(
'/header?text=Hello',
)

assert response.status_code == 200

但它不起作用,它认为问题是我使用查询字符串的上下文参数而不是实际的函数参数。我可以得到任何帮助吗?

谢谢!

最佳答案

问题似乎可能是您尝试在应用程序上下文之外运行测试客户端。

尝试将您的调用包装在应用程序上下文中:

def test_my_route(): 

with app.app_context():

response = app.test_client().get(
'/header?text=Hello',
)

assert response.status_code == 200

如果您正在运行单元测试套件,那么最好将其放入您的设置中 - 这是我的 BaseTestClasssetUptearDown 函数> 我所有其他单元测试都继承自(create_app 只是我常用的应用程序工厂,您可能只需从其他模块导入 app):

from unittest import TestCase
from app.application import create_app, db

class BaseTestCase(TestCase):

def setUp(self):

self.app = create_app()
self.db = db

self.app.config['TESTING'] = True

self.app_context = self.app.app_context()
self.app_context.push()
self.client = self.app.test_client()

def tearDown(self):

self.db.session.remove()
self.db.get_engine(self.app).dispose()
self.app_context.pop()

关于python - 如何测试使用上下文参数的 Flask API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58309745/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com