Mocking render to response with Pyramid

 ̄綄美尐妖づ 提交于 2020-01-24 22:07:55

问题


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

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)

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

ValueError: no such renderer factory .jinja

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.


回答1:


Mock library is awesome:

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.

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

Youc code would look like this:

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')



回答2:


The following worked for me:

def setUp(self):
    self.app = TestApp(target_app())
    self.config = testing.setUp(request=testing.DummyRequest) 
    self.config.include('pyramid_jinja2')

By setting up the config to include jinja your tests can then find your template and the jinja environment. You may also need to provide a test version of the template in the same folder as your tests. If you get a message such as TemplateNotFound on running the tests then make sure a version of the template is located in the correct place.



来源:https://stackoverflow.com/questions/24373013/mocking-render-to-response-with-pyramid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!