如何使用Mock对Google Cloud Functions进行单元测试时处理abort()

问题描述 投票:0回答:1

我正在测试的云函数调用abort(410),我想测试我的单元测试中是否收到了正确的HTTP错误代码。

在简单地发出请求时,我收到以下错误:

/usr/lib/python3.7/site-packages/werkzeug/exceptions.py:707: in abort
    return _aborter(status, *args, **kwargs)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <werkzeug.exceptions.Aborter object at 0x7fd474096b00>, code = 410, args = (), kwargs = {}

    def __call__(self, code, *args, **kwargs):
        if not args and not kwargs and not isinstance(code, integer_types):
            raise HTTPException(response=code)
        if code not in self.mapping:
            raise LookupError('no exception for %r' % code)
>       raise self.mapping[code](*args, **kwargs)
E       werkzeug.exceptions.Gone: 410 Gone: The requested URL is no longer available on this server and there is no forwarding address. If you followed a link from a foreign page, please contact the author of this page.

/usr/lib/python3.7/site-packages/werkzeug/exceptions.py:687: Gone

这是我制作Mock请求的代码:

from unittest.mock import Mock
from cloud_functions import main

data = { ... }
headers = { ... }

req = Mock(get_json=Mock(return_value=data), args=data, headers=headers)
resp = main.my_function(req)
python unit-testing mocking http-error werkzeug
1个回答
0
投票

使用HTTPExceptionwerkzeug.exceptions模块来捕获错误代码对我来说很好。

将我的代码更改为此使其现在可以正常工作。

from unittest.mock import Mock
from cloud_functions import main
from werkzeug.exceptions import HTTPException

data = { ... }
headers = { ... }

req = Mock(get_json=Mock(return_value=data), args=data, headers=headers)
try:
    resp = main.get_url_full(req)
    assert False
except HTTPException as e:
    assert e.code == 410
© www.soinside.com 2019 - 2024. All rights reserved.