这是由于 Werkzeug 测试客户端共用全局应用实例所致。解决方法是使用不同的应用实例来创建不同的测试客户端。以下是示例代码:
from flask import Flask
from flask.testing import FlaskClient
from werkzeug.test import Client, EnvironBuilder
app = Flask(__name__)
class CustomClient(FlaskClient):
def __init__(self, *args, **kwargs):
with app.app_context():
super().__init__(*args, **kwargs)
with app.app_context():
# create separate application instances for each client
app1 = Flask(__name__)
app2 = Flask(__name__)
@app1.route('/')
def index1():
return "hello from app1"
@app2.route('/')
def index2():
return "hello from app2"
# create separate clients using respective application instances
client1 = CustomClient(app1, response_wrapper=app1.make_response)
client2 = CustomClient(app2, response_wrapper=app2.make_response)
# test each client individually
response1 = client1.get('/')
assert response1.data == b"hello from app1"
response2 = client2.get('/')
assert response2.data == b"hello from app2"
在这个示例中,我们创建了两个不同的 Flask 应用实例(app1 和 app2),并使用其分别创建了两个测试客户端(client1 和 client2)。每个测试客户端都在其构造函数中获得了所属应用实例的上下文。这确保了每个客户端都在独立的应用环境中运行,从而消除了客户端之间的影响。