与pytest.raises(Exception)不适用于烧瓶app.post

时间:2018-07-11 18:35:24

标签: 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无法捕获此异常?

1 个答案:

答案 0 :(得分:1)

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

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