Clicquot the Dog Clicquot the Dog - 1 year ago 102
Python Question

Mocking render to response with Pyramid

I have a decorator that looks like so:

def validate_something(func):
def validate_s(request):
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): = 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.

Answer Source

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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download