模拟渲染以响应金字塔 [英] Mocking render to response with Pyramid

查看:90
本文介绍了模拟渲染以响应金字塔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的装饰器:

I have a decorator that looks like so:

def validate_something(func):
    def validate_s(request):
        if request.property:
            render_to_response('template.jinja', 'error'
        return func(request)
    return validate_something

我正在尝试像这样进行测试.我将本地WSGI堆栈作为应用程序加载.

I'm trying to test it like so. I load the local WSGI stack as an app.

from webtest import TestApp 
def setUp(self):
     self.app = TestApp(target_app())
     self.config = testing.setUp(request=testing.DummyRequest)   


def test_something(self):
    def test_func(request):
         return 1
    request = testing.DummyRequest()
    resp = validate_something(test_func(request))
    result = resp(request)

我得到的错误是(在最里面的render_to_response生成):

The error I'm getting is (being generated at the innermost render_to_response):

ValueError: no such renderer factory .jinja

我知道我需要模拟render_to_response,但是我对如何准确地做到这一点有些茫然.如果有人有任何建议,我将不胜感激.

I understand that I need to mock render_to_response, but I'm at a bit of a loss as to how to exactly do that. If anyone has any suggestions, I would greatly appreciate it.

推荐答案

模拟库很棒:

mock提供了一个核心的Mock类,从而消除了创建主机的需求. 测试套件中的存根.执行动作后,您可以 断言使用了哪些方法/属性,以及 他们被称为的论点.您还可以指定返回值 并以常规方式设置所需的属性.

mock provides a core Mock class removing the need to create a host of stubs throughout your test suite. After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with. You can also specify return values and set needed attributes in the normal way.

此外,mock提供了一个用于处理补丁的patch()装饰器 测试范围内的模块和类级别属性

Additionally, mock provides a patch() decorator that handles patching module and class level attributes within the scope of a test

Youc代码如下:

def test_something(self):
    test_func = Mock.MagicMock(return_value=1)  # replaced stub function with a mock
    request = testing.DummyRequest()
    # patching a Pyramid method with a mock
    with mock.patch('pyramid.renderers.render_to_response' as r2r:
        resp = validate_something(test_func(request))
        result = resp(request)
        assert r2r.assert_called_with('template.jinja', 'error')

这篇关于模拟渲染以响应金字塔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆