Python 使用pytest.raises(例外)不使用flask app.post

Python 使用pytest.raises(例外)不使用flask app.post,python,unit-testing,flask,pytest,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类似于

我有一个这样的文件夹

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 test client是一个测试客户端,用于测试当您向端点发出请求时,用户端将发生什么。pytest没有并且应该捕获异常的原因是错误发生在服务器端,用户不应该有服务器端异常


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

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


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

很有意义,谢谢您的回复!如果我打算在flask应用程序(一个服务器)上进行单元测试,那么创建test_客户机是这样做的吗?或者这已经是集成测试的级别了……使用test_客户端是正确的方法。从某种意义上说,你是对的,这是一个集成测试。如果您在该端点中有复杂的逻辑,也许您可以为该端点中的函数编写unittest,并使用test_client仅用于用户响应检查。这很有意义,感谢您的回复!如果我打算在flask应用程序(一个服务器)上进行单元测试,那么创建test_客户机是这样做的吗?或者这已经是集成测试的级别了……使用test_客户端是正确的方法。从某种意义上说,你是对的,这是一个集成测试。如果您在该端点中有复杂的逻辑,那么您可以为该端点中的函数编写unittest,并使用test_client仅用于用户响应检查。