如何向在单独线程上运行的flask服务器发出post请求



我正试图用pytest编写一个测试,测试给定post请求的返回。我想在相同的功能中隔离烧瓶服务器和测试。这是我的代码:

import threading
import requests
from flask import Flask
from flask_restful import Api
from . import UserAuthentication
def test_user_authentication():
app = Flask(__name__)
api = Api(app)
api.add_resource(UserAuthentication, "/<string:stage>/api/user/authentication")
def app_thread_function():
app.run(port=5000, host="0.0.0.0")
app_thread = threading.Thread(target=app_thread_function)
app_thread.start()
data = {"username": "xxxxxxx.xxxxxxx@xxxxxxx.com.br", "password": "xxxxxxxxxxxxxx"}
request = requests.post(url = "http://localhost:5000/dev/api/user/authentication", data = data) 
print("request")
print(request)

当我运行pytest时,我会得到以下错误:

urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=5000): Max retries exceeded with url: /dev/api/user/authentication (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f3a7eeb7280>: Failed to establish a new connection: [Errno 111] Connection refused'))
../web-python/lib/python3.8/site-packages/urllib3/util/retry.py:439: MaxRetryError

端口5000上没有任何运行,为什么我不能调用服务器并同时运行它?

要为每个测试函数隔离应用程序,应该使用@pytest.fixture装饰器

首先,您应该阅读官方文档中的Testing Flask Applications。

开始在conftest.py中为您的应用程序定义一个新的固定装置,带有一个函数范围(默认(和其他范围。

from myapp import create_app
@pytest.fixture
def app():
app = create_app()
return app

然后,在测试函数中,您可以调用应用程序fixture。

def test_my_function(app):
# Here you have a fresh app object.
pass

这里开始另一部分。您需要一个test_client来进行请求请注意,如果您正在测试应用程序代码中的断言或异常,则必须将app.testing=True设置为使异常传播到测试客户端

一个更简单的方法是使用pytest烧瓶,它将为您创建所需的其他固定装置,如客户端、配置和其他。。。

比重瓶示例:

def test_my_function(client):
rv = client.get('/')
assert b'No entries here so far' in rv.data

如果你看一下github上的pytest-flack/fixture.py,你可以看到客户端fixture只是依赖于一个应用程序fixture,并从中返回一个text_client。

您仍然可以尝试使用线程来完成此操作,但这种方法要简单得多。您不必关心如何结束线程。启动主线程以控制实际应用程序的调试模式可能会出现另一个问题。

最后,对于每个调用客户端fixture的测试函数,您将拥有一个新的、全新的、独立的应用程序,这正是您想要的。

最新更新