How to get uri_for with webapp2 in unit test?

梦想与她 提交于 2019-12-06 20:17:25

问题


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?


回答1:


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.




回答2:


webapp2.uri_for() assumes that you are in a web request context and it fails because it cannot find the request object.

Instead of working around this you could think of your application as a black box and call it using literal URIs, like '/' as you mention it. After all, you want to simulate a normal web request, and a web browser will also use URIs and not internal routing shortcuts.



来源:https://stackoverflow.com/questions/7454590/how-to-get-uri-for-with-webapp2-in-unit-test

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