How to get uri_for with webapp2 in unit test?

这一生的挚爱 提交于 2019-12-05 01:18:36

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.

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.

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