为 Flask 应用单元测试设置(模拟)请求标头 [英] Setting (mocking) request headers for Flask app unit test
问题描述
有谁知道在单元测试期间设置(模拟)由 FLask (Werkzeug) 提供的请求对象的 User-Agent 的方法吗?
Does anyone know of a way to set (mock) the User-Agent of the request object provided by FLask (Werkzeug) during unit testing?
就目前而言,当我尝试获取诸如 request.headers['User-Agent'] 之类的详细信息时,会引发 KeyError,因为 Flask test_client() 未设置这些信息.(见下面的部分堆栈跟踪)
As it currently stands, when I attempt to obtain details such as the request.headers['User-Agent'] a KeyError is raised as the Flask test_client() doesn't set these up. (See partial stack trace below)
在单元测试期间尝试从 Flask 项目中的请求对象获取 User-Agent 时,会引发 KeyError.
When attempting to get the User-Agent from the request object in a Flask project during unit testing, a KeyError is raised.
File "/Users/me/app/rest/app.py", line 515, in login
if request.headers['User-Agent']:
File "/Users/me/.virtualenvs/app/lib/python2.7/site-packages/werkzeug/datastructures.py", line 1229, in __getitem__
return self.environ['HTTP_' + key]
KeyError: 'HTTP_USER_AGENT'
-- 更新 --
连同下面的(接受的)解决方案,environ_base 提示引导我到另一个 SO 解决方案.这个方案的前提是为Flask app创建一个包装类,覆盖call方法来自动设置环境变量.这样,为所有调用设置了变量.所以,我最终实现的解决方案是创建这个代理类:
Along with the (accepted) solution below, the environ_base hint lead me to this other SO solution. The premise of this solution is to create a wrapper class for the Flask app and override the call method to automatically set the environment variables. This way, the variables are set for all calls. So, the solution I ended up implementing is creating this proxy class:
class FlaskTestClientProxy(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
environ['REMOTE_ADDR'] = environ.get('REMOTE_ADDR', '127.0.0.1')
environ['HTTP_USER_AGENT'] = environ.get('HTTP_USER_AGENT', 'Chrome')
return self.app(environ, start_response)
然后使用该代理包装 WSGI 容器:
And then wrapping the WSGI container with that proxy:
app.wsgi_app = FlaskTestClientProxy(app.wsgi_app)
test_client = app.test_client()
推荐答案
调用get()
或post()时需要传入
environ_base
代码>.例如,
You need to pass in environ_base
when you call get()
or post()
. E.g.,
client = app.test_client()
response = client.get('/your/url/',
environ_base={'HTTP_USER_AGENT': 'Chrome, etc'})
那么你的 request.user_agent
应该是你传入的任何东西,你可以通过 request.headers['User-Agent']
访问它.
Then your request.user_agent
should be whatever you pass in, and you can access it via request.headers['User-Agent']
.
见http://werkzeug.pocoo.org/docs/test/#testing-api 了解更多信息.
这篇关于为 Flask 应用单元测试设置(模拟)请求标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!