【问题标题】:How to override the self.request.host in a webapp2 handler unit test?如何在 webapp2 处理程序单元测试中覆盖 self.request.host?
【发布时间】:2017-05-06 05:51:13
【问题描述】:

我有一个 webapp2 服务器,它有两个不同的 URL 指向它。在我的处理程序的调度函数中,我检查请求来自哪个主机:

class MyHandler(webapp2.RequestHandler):

  def dispatch(self):
    if self.request.host == 'my url':
      # Do something.
    else:
      # Do something else.

在我的单元测试中,我正在启动一个本地测试应用程序并使用 webapp2.Request.blank 向它发出请求:

test_app = webapp2.WSGIApplication([('/', MyHandler)])
request = webapp2.Request.blank('/')
response = request.get_response(test_app)

我想知道是否可以在这种情况下覆盖 request.host 以匹配我的网址之一?现在,无论我尝试了什么,它总是以 localhost:80 的形式出现。谢谢。

【问题讨论】:

    标签: python unit-testing wsgi webapp2


    【解决方案1】:

    我仍然不确定我的要求是否可行,但我通过扩展我的处理程序并覆盖 request.host 值找到了解决方法:

    class TestHandler(MyHandler):
      def __init__(self, *args, **kwargs):
        super(TestHandler, self).__init__(*args, **kwargs)                                  
        self.request.host = 'my url'
    
    test_app = webapp2.WSGIApplication([('/', TestHandler)])
    request = webapp2.Request.blank('/')
    response = request.get_response(test_app)
    

    【讨论】:

      猜你喜欢
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 2013-07-08
      相关资源
      最近更新 更多