edbras
edbras

Reputation: 4404

How to unit test request.json_body in pyramid?

I use the field request.json_body to retrieve the encoded json body like:

@view_config(route_name='reminder', renderer='json', permission='view', xhr=True, request_method='POST')
def reminder(request):
    process(body.request.json_body)
    return {'result':'OK'}

How can I unit test this (I am a python newbie, using 3.4.4). I used DummyRequest() from pyramid testing, but when running the test it complaints:

'DummyRequest' object has no attribute 'json_body'

Which I understand as I read that the DummyRequest is restricted. And how can I fill the "test" request with some json body? I think I am looking in the wrong corners as I can't (google) good info about this :(

Upvotes: 3

Views: 1650

Answers (2)

Madhur
Madhur

Reputation: 86

You can give it as constructor params while creating the object.

testing.DummyRequest(json_body=json_params, method='POST')

This should work. Works fine for me

Upvotes: 7

Iain Duncan
Iain Duncan

Reputation: 1772

There are a few ways of doing this. I like to use WebTest, which allows you to make a test app out of your wsgi callable, and then you can just call this test object to send in and out json. In brief it looks like this:

   # my_app is a wsgi callable
    test_app = webtest.TestApp(my_app)
    # my json post body as a dict
    params = {'name': 'Iain', 'quest': 'find grail'}
    response = test_app.post_json('/cross_bridge', params=params})
    assert response.json['status'] == 'success', "should be a success msg"

We nerds will argue about whether this is a unit test or integration test or functional test, but I think this is what you are looking for. The WebTest docs have further examples. Note that you can also pass in values that will go into the WSGI dict, and there are methods for passing in headers and verifying headers. We use this along with Pyramid's Remote User Auth policy to set which user is logged in for the requests. I wrap the whole thing up in standard unittest classes, with a base class to do my extra boilerplate.

Upvotes: 1

Related Questions