Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get uri_for with webapp2 in unit test?

I'm trying to unit test a handler with webapp2 and am running into what has to be just a stupid little error.

I'd like to be able to use webapp2.uri_for in the test, but I can't seem to do that:

    def test_returns_200_on_home_page(self):
        response = main.app.get_response(webapp2.uri_for('index'))
        self.assertEqual(200, response.status_int)

If I just do main.app.get_response('/') it works just fine.

The exception received is:

   Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 318, in run
    testMethod()
  File "tests.py", line 27, in test_returns_200_on_home_page
    webapp2.uri_for('index')
  File "/Users/.../webapp2_example/lib/webapp2.py", line 1671, in uri_for
    return request.app.router.build(request, _name, args, kwargs)
  File "/Users/.../webapp2_example/lib/webapp2_extras/local.py", line 173, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/Users/.../webapp2_example/lib/webapp2_extras/local.py", line 136, in _get_current_object
    raise RuntimeError('no object bound to %s' % self.__name__)
RuntimeError: no object bound to request

Is there some silly setup I'm missing?

like image 597
Aaron Avatar asked Sep 17 '11 12:09

Aaron


1 Answers

I think the only option is to set a dummy request just to be able to create URIs for the test:

def test_returns_200_on_home_page(self):
    // Set a dummy request just to be able to use uri_for().
    req = webapp2.Request.blank('/')
    req.app = main.app
    main.app.set_globals(app=main.app, request=req)

    response = main.app.get_response(webapp2.uri_for('index'))
    self.assertEqual(200, response.status_int)

Never use set_globals() outside of tests. Is is called by the WSGI application to set the active app and request in a thread-safe manner.

like image 121
moraes Avatar answered Nov 13 '22 22:11

moraes