python - 与 pytest.raises(Exception) 不适用于 Flask app.post

标签 python unit-testing flask pytest

我有一个这样的文件夹

python
├── foo
│   ├── __init__.py
│   └── web
│       ├── __init__.py
│       ├── api
│       │   ├── __init__.py
│       │   └── helper_api.py
│       └── server.py         
└── test_server.py
    ├── test_helper_api.py

helper_api.py 就像

@helper_api.route("/helper", methods=['POST'])
def helper():
    data = request.get_json(force=True, silent=True, cache=True)
    if data is None:
        raise QueryParseException("JSON-formatted query is required, none found")

在 test_helper_api.py 中,我有

import ......
from foo.web.api.helper_api import QueryParseException

class TestClass(object):
    @pytest.fixture
    def client(self, request):
        self.client = server.app.test_client()
        return self.client

    def test_helper_api(self, client):
        with pytest.raises(QueryParseException):
            client.post('/helper')

当我运行测试类时,代码在 client.post 处失败,引发异常,但 pytest 未能捕获它。

    ---------------------------------------------------- Captured log call -----------------------------------------------------
app.py                    1761 ERROR    Exception on /helper [POST]
Traceback (most recent call last):
  File "/Users/...personal path.../flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  .......
  File "/Users/...personal path.../foo-1.0.0-py3.6.egg/foo/web/api/helper_api.py", line 12, in precheck
    raise QueryParseException("JSON-formatted query is required, none found")
foo.web.api.helper_api.QueryParseException: JSON-formatted query is required, none found

为什么 pytest 没有捕获这个异常?

最佳答案

Flask 测试客户端是一个测试客户端,用于测试当您向端点发出请求时用户端会发生什么。 pytest 没有也不应该捕获异常的原因是错误发生在服务器端,用户不应该有服务器端异常。

相反,要测试您的 QueryParseException 在服务器端是否正确引发,您可以断言 client.post('/helper') 的状态代码。同时,在服务器端,您可以给出错误消息和状态代码,让客户端知道发生了什么问题。

关于python - 与 pytest.raises(Exception) 不适用于 Flask app.post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51292186/

相关文章:

列表元素上的python 3.4 UTF 8字符串

python - 优化后我的 Sprite 不再显示了。为什么我的 Sprite 没有显示在我的 pygame 代码中?

python - 匹配逗号或换行符但不能同时匹配两者的正则表达式

python - 导入 flask.ext.wtf

python - 我什么时候会在 monogoengine 的内置 JSON 序列化(from_json 和 to_json)上使用像 marshmallow 这样的外部序列化器?

python - wxPython,我如何触发事件?

java - JUnit 如何使用参数对象的不同值进行模拟?

javascript - Angular Test 不调用 Promise 回调

unit-testing - 如何使用 Jest 仅模拟一个测试文件的模块?

python - chrome 和 flask 的超时问题