How to override the self.request.host in a webapp2 handler unit test?

279 views Asked by At

I have a webapp2 server that has two different URL's pointing to it. In my handler's dispatch function I check to see what host the request has come in from:

class MyHandler(webapp2.RequestHandler):

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

In my unit test I am spinning up a local test app and using webapp2.Request.blank to make requests to it:

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

I was wondering if it's possible to override the request.host in this context to match one of my urls? Right now it's always coming through as localhost:80 no matter what I've tried. Thanks.

1

There are 1 answers

0
MilkyC On

I'm still not sure if what I was asking is possible but I found a workaround by extending my handler and overriding the request.host value:

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)