unit-testing - 使用 pytest 测试 Flask 应用程序时找不到 404
问题描述
如果我手动运行这个简单的 Web 服务,它就可以工作,但在我的单元测试中,我得到一个 404 not found 页面作为我的响应,阻止我正确测试应用程序。
正常行为:
文件夹结构:
/SRC
--web_application.py
/UNIT_TESTS
--test_wab_application.py
web_application.py
from flask import Flask, request, jsonify, send_from_directory
from python.Greeting import Greeting
application = Flask(__name__)
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='mega_developer',
DATABASE=os.path.join(app.instance_path, 'web_application.sqlite'),
)
try:
os.makedirs(app.instance_path)
except OSError:
pass
return app
@application.route('/greetings', methods=['GET', 'POST'])
def hello():
# GET: for url manipulation #
if request.method == 'GET':
return jsonify(hello = request.args.get('name', 'world', str))
test_web_application.py
import tempfile
import pytest
import web_application
class TestWebApplication:
app = web_application.create_app() # container object for test applications #
@pytest.fixture
def initialize_app(self):
app = web_application.create_app()
app.config['TESTING'] = True
app.config['DEBUG'] = False
app.config['WTF_CSRF_ENABLED'] = False
app.config['DATABASE'] = tempfile.mkstemp()
app.testing = True
self.app = app
def test_hello_get(self, initialize_app):
with self.app.test_client() as client:
response = client.get('/greetings?name=Rick Sanchez')
assert response.status_code == 200
测试结果(仅最相关部分):
Launching pytest with arguments test_web_application.py::TestWebApplication::test_hello_get in C:\Users\Xrenyn\Documents\Projekte\Studium_Anhalt\QA&Chatbots Exercises\Exercise 2 - Web Service Basics\UNIT_TESTS
============================= test session starts =============================
platform win32 -- Python 3.8.0, pytest-5.2.2, py-1.8.0, pluggy-0.13.0 -- C:\Users\Xrenyn\Documents\Projekte\Studium_Anhalt\QA&Chatbots Exercises\Exercise 2 - Web Service Basics\VENV\Scripts\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\Xrenyn\Documents\Projekte\Studium_Anhalt\QA&Chatbots Exercises\Exercise 2 - Web Service Basics\UNIT_TESTS
collecting ... collected 1 item
test_web_application.py::TestWebApplication::test_hello_get FAILED [100%]
test_web_application.py:21 (TestWebApplication.test_hello_get)
404 != 200
Expected :200
Actual :404
到目前为止,我已经为client.get()
in 中的方法测试了各种替代路由路径test-web_application.py
,包括像 '/SRC/greetings?name=Rick Sanchez' 或 '../SRC/greetings?name=Rick Sanchez' 这样的组合,但都没有不同的效果。
您对我可能做错了什么或如何从单元测试中访问我的 Web 服务功能有任何想法吗?
解决方案
我认为问题在于您正在创建两个Flask
实例。一个使用application
您添加hello
路由的名称,第二个使用该create_app
函数。您需要使用application
实例(添加hello
路由的那个)创建一个测试客户端。
您可以导入application
然后获取client
usingapplication.test_client()
吗?
示例解决方案:
import pytest
from web_application import application
@pytest.fixture
def client():
with application.test_client() as client:
yield client
class TestSomething:
def test_this(self, client):
res = client.get('/greetings?name=Rick Sanchez')
assert res.status_code == 200
查看有关测试的官方文档。
推荐阅读
- java - Scala 等价于 Java 的静态块是什么?(没有伴随对象)
- postgresql - 我的 postgresql 语法错误 (%) 符号
- ios - 用户输入 11 位数字后关闭键盘
- node.js - 在 Node/express 静态文件中处理 CORS
- python - 为子图着色
- php - 如何在 Woocommerce 中删除更多负载并显示分页 WordPress
- javascript - 在 chart.js 条形图上限制标签
- android - 按钮按下一次,按钮保持增量值(连续)
- python - 未加载库:/usr/local/opt/mysql/lib/libmysqlclient.21.dylib 和未找到原因图像
- gremlin - 为什么 Gremlin JavaScript 使用“from_”映射而不是“from”?