【发布时间】:2017-03-20 07:52:46
【问题描述】:
我有一个 python 模块security.py,它定义了一个装饰器authorized()。
我想测试装饰器。装饰器将收到一个烧瓶请求标头。 装饰器是这样的:
def authorized():
def _authorized(wrapped_func):
def _wrap(*args, **kwargs):
if 'token' not in request.headers:
LOG.warning("warning")
abort(401)
return None
return wrapped_func(*args, **kwargs)
return _wrap
return _authorized
我想使用@patch 装饰器模拟烧瓶请求头。我写的测试是这样的:
@patch('security.request.headers', Mock(side_effect=lambda *args, **kwargs: MockHeaders({})))
def test_no_authorization_token_in_header(self):
@security.authorized()
def decorated_func(token='abc'):
return access_token
result = decorated_func()
self.assertEqual(result, None)
class MockHeaders(object):
def __init__(self, json_data):
self.json_data=json_data
但我总是收到以下错误:
name = 'request'
def _lookup_req_object(name):
top = _request_ctx_stack.top
if top is None:
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
我应该怎么做才对?
【问题讨论】:
-
@MartijnPieters 是的,该类就在补丁修饰的方法之后
-
糟糕,错过了。过错。
标签: python unit-testing flask