Unit testing bottle py application that uses request body results in KeyError: 'wsgi.input'
Question: When unit testing a bottle py route function:

    
    
    from bottle import request, run, post
    @post("/blah/<boo>")
    def blah(boo):
        body = request.body.readline()
        return "body is %s" % body
    blah("booooo!")
    

The following exception is raised:

    
    
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 3, in blah
      File "bottle.py", line 1197, in body
        self._body.seek(0)
      File "bottle.py", line 166, in __get__
        if key not in storage: storage[key] = self.getter(obj)
      File "bottle.py", line 1164, in _body
        read_func = self.environ['wsgi.input'].read
    KeyError: 'wsgi.input'
    

The code will work if running as a server via bottle's `run` function, it's
purely when I call it as a normal Python function e.g. in a unit test.

What am I missing? How can I invoke this as a normal python func inside a unit
test?


Answer: I eventually worked out what the problem is. I needed to "fake" the request
environment for bottle to play nicely:

    
    
    from bottle import request, run, post, tob
    from io import BytesIO
    body = "abc"
    request.environ['CONTENT_LENGTH'] = str(len(tob(body)))
    request.environ['wsgi.input'] = BytesIO()
    request.environ['wsgi.input'].write(tob(body))
    request.environ['wsgi.input'].seek(0)
    # Now call your route function and assert
    

