python - 使用请求正文的单元测试 bottle py 应用程序导致 KeyError : 'wsgi.input'

标签 python unit-testing bottle

当对一个 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/

相关文章:

python - python代码中的相对路径 - 最佳实践

javascript - 注入(inject) Controller 和模拟 AngularJS 服务

python - 让 Beaker 与 GAE 一起工作

python - 当Python Bottle准备好文件时,如何实现自动更新的 “Your file is being prepared. Please wait 1 minute.”?

java - 使用 requests Restful 客户端时出现阿拉伯编码错误

python - python中的素数生成代码

python - 如何在 python 中存储和检索数据

angularjs - 错误 : Unexpected value 'undefined' declared by the module 'DynamicTestModule'

java - Run As JUnit 未出现在 Eclipse 中 - 使用 JUnit4

Python Bottle - 模板中的内联 IF 语句