10

我正在尝试使用 webapp2 对处理程序进行单元测试,并且遇到了一个愚蠢的小错误。

我希望能够在测试中使用 webapp2.uri_for,但我似乎不能这样做:

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

如果我只是这样做main.app.get_response('/'),它就可以了。

收到的异常是:

   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

我缺少一些愚蠢的设置吗?

4

2 回答 2

14

我认为唯一的选择是设置一个虚拟请求,以便能够为测试创建 URI:

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)

切勿set_globals()在测试之外使用。WSGI 应用程序调用 Is 以线程安全的方式设置活动应用程序和请求。

于 2011-09-18T13:47:51.840 回答
0

webapp2.uri_for()假设您在 Web 请求上下文中,并且由于找不到request对象而失败。

除了解决这个问题,您可以将您的应用程序视为一个黑盒子,并使用文字 URI 调用它,就像'/'您提到的那样。毕竟,你想模拟一个普通的 Web 请求,Web 浏览器也会使用 URI,而不是内部路由快捷方式。

于 2011-09-18T10:18:14.153 回答