【问题标题】:with pytest.raises(Exception) not working with flask app.postpytest.raises(Exception) 不适用于烧瓶 app.post
【发布时间】:2018-07-11 18:35:24
【问题描述】:

我有一个这样的文件夹

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 没有捕捉到这个异常?

【问题讨论】:

    标签: python unit-testing flask pytest


    【解决方案1】:

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

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

    【讨论】:

    • 有道理,谢谢回复!如果我打算在烧瓶应用程序(这是一个服务器)上进行单元测试,那么创建 test_client() 是不是这样?或者这已经在集成测试的层面上......
    • 使用 test_client() 是正确的方法。你是对的,从某种意义上说,它是一个集成测试。如果您在该端点中有复杂的逻辑,也许您可​​以为该端点中的函数编写单元测试,并将test_client 仅用于用户响应检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 2016-01-08
    • 2018-03-17
    相关资源
    最近更新 更多