当对一个 bottle py 路由函数进行单元测试时:
from bottle import request, run, post
@post("/blah/<boo>")
def blah(boo):
body = request.body.readline()
return "body is %s" % body
blah("booooo!")
引发了以下异常:
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'
如果通过 bottle 的 run
函数作为服务器运行,代码将工作,这纯粹是当我将它作为一个普通的 Python 函数调用时,例如在单元测试中。
我错过了什么?我如何在单元测试中将其作为普通的 python func 调用?
最佳答案
我最终弄清楚了问题所在。我需要“伪造” Bottle 的请求环境才能正常播放:
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
关于python - 使用请求正文的单元测试 bottle py 应用程序导致 KeyError : 'wsgi.input' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28857520/