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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With