8

我有一个我正在装饰的基于 django 类的视图。不幸的是,装饰器进行外部调用以进行状态检查,这超出了单元测试的范围,因此我想在单元测试期间覆盖装饰器以不做任何事情。这是我的装饰器:

装饰器.py

def status_check(func):
    @wraps(func)
    def wrapped(request, *args, **kwargs):

        uri = settings.SERVER_URI
        status_code = None
        bad_status = [404, 500]

        try:
            response = requests.head(uri)
        except requests.ConnectionError as err:
            LOGGER.error('Server is hosed! Oh Noes! Error: %s ' % (err))
            raise Http404
        except Exception as err:
            LOGGER.error('Some crazy stuff is happening. Its Bad. '
                         'Error: %s' % (err))
            raise Http404

        status_code = response.status_code
        if not status_code or status_code in bad_status:
            LOGGER.error('Awww Snap! Server is not happy: %s' % (status_code))
            raise Http404
        return func(request, *args, **kwargs)
    return wrapped

视图.py

class HandleFoo(DetailView):
    @method_decorator(status_check)
    def post(self, request):
        # do stuff here

测试.py

class RunTest(TestCase):
    def test_post(self):
        post_data = json.dumps({'stuff': 'vodka', 'things': 'tonic'})
        resp = self.client.post(self.foo_uri,
                                post_data,
                                content_type='application/json',
                               )
        self.assertEqual(resp.status_code, 200)

那么有没有办法让我覆盖装饰器或者我可以完全绕过它?我对此感到很困惑。

编辑 尝试使用来自 krak3n 的以下内容模拟请求:

@patch('app.views.method_decorator.status_check', lambda func: func)
@patch('app.views.status_check', lambda func: func)
@patch('app.decorators.status_check', lambda func: func)
@patch('app.views.HandleFoo.post', lambda func: func)

最后一种方法让我是迄今为止最接近的,但它最终抛出了一个堆栈跟踪:

Traceback (most recent call last):
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/mock.py", line 1201, in patched
    return func(*args, **keywargs)
  File "/Users/squiddly/projects/tests/app/tests.py", line 165, in test_post
    content_type='application/json',
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/test/client.py", line 463, in post
    response = super(Client, self).post(path, data=data, content_type=content_type, **extra)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/test/client.py", line 297, in post
    return self.request(**r)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/test/client.py", line 406, in request
    response = self.handler(environ)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/test/client.py", line 111, in __call__
    response = self.get_response(request)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/core/handlers/base.py", line 178, in get_response
    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/core/handlers/base.py", line 224, in handle_uncaught_exception
    return callback(request, **param_dict)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/utils/decorators.py", line 91, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/views/defaults.py", line 41, in server_error
    return http.HttpResponseServerError(template.render(Context({})))
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/template/base.py", line 140, in render
    return self._render(context)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/test/utils.py", line 65, in instrumented_test_render
    return self.nodelist.render(context)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/template/base.py", line 830, in render
    bit = self.render_node(node, context)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/template/debug.py", line 74, in render_node
    return node.render(context)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/template/loader_tags.py", line 124, in render
    return compiled_parent._render(context)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/test/utils.py", line 65, in instrumented_test_render
    return self.nodelist.render(context)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/template/base.py", line 830, in render
    bit = self.render_node(node, context)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/template/debug.py", line 74, in render_node
    return node.render(context)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/template/loader_tags.py", line 156, in render
    return self.render_template(self.template, context)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/template/loader_tags.py", line 138, in render_template
    output = template.render(context)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/template/base.py", line 140, in render
    return self._render(context)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/test/utils.py", line 65, in instrumented_test_render
    return self.nodelist.render(context)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/template/base.py", line 830, in render
    bit = self.render_node(node, context)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/template/debug.py", line 74, in render_node
    return node.render(context)
  File "/Users/squiddly/envs/testenv/lib/python2.7/site-packages/django/template/base.py", line 1185, in render
    _dict = func(*resolved_args, **resolved_kwargs)
  File "/Users/squiddly/projects/tests/app/templatetags/app_extras.py", line 40, in get_data
    if request.session.has_key('start_time'):
AttributeError: 'str' object has no attribute 'session'
4

1 回答 1

6

我认为你将不得不进入黑暗Mock的地下世界,但一旦你了解它(如果你还没有),黑暗的地下世界就会变成一片明亮的蓝色天堂般的嘲弄天空。

您可以使用 to 的patch模块Mock来修补此装饰器,以便您使用它的视图可以变得更可测试:http ://www.voidspace.org.uk/python/mock/patch.html 。就我个人而言,我以前没有尝试过嘲笑装饰者,但它应该可以工作......

@patch('python.path.to.decorator', new_callable=PropertyMock)
def my_test(self, decorator_mock):
    # your test code

试一试。

您可以在此处阅读有关该patch模块的Mock信息:http ://www.voidspace.org.uk/python/mock/patch.html

编辑

new_callable=PropertyMock修补装饰器可能不是正确的做法。

也许尝试:

@patch('python.path.to.decorator', lambda: func: func)
def my_test(self):
    # your test code

这在理论上应该修补装饰器,所以它只是返回函数而不是你在wrapped.

于 2013-03-29T10:13:56.420 回答