2024-05-14 16:38:43 发布
网友
我试图为我的包做一个可用的测试,但是使用Flask.test_client与requestsAPI有很大的不同,我发现很难使用。在
Flask.test_client
requests
我试图让requests.adapters.HTTPAdapter包装响应,但是看起来werkzeug没有使用httplib(或者urllib)来构建它自己的Response对象。在
requests.adapters.HTTPAdapter
werkzeug
httplib
urllib
Response
你知道怎么做吗?参考现有的代码将是最好的(google werkzeug+请求没有给出任何有用的结果)
非常感谢!!在
您可以使用下面代码部分中定义的requests方法。 要使用它,还需要定义下面代码中显示的get_auth_headers方法。在
get_auth_headers
特点:
自动设置请求头。在
Content-Type: Application/json
Basic Authentication
json
requests.Response
代码:
class MyTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.client = self.app.test_client() self.app_context = self.app.app_context() self.app_context.push() db.create_all() def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def get_auth_headers(self, username, password): return { 'Authorization': 'Basic ' + base64.b64encode( (username + ':' + password).encode('utf-8')).decode('utf-8'), 'Accept': 'application/json', 'Content-Type': 'application/json' } def requests(self, method, url, json={}, auth=(), **kwargs): """Wrapper around Flask test client to automatically set headers if JSON data is passed + dump JSON data as string.""" if not hasattr(self.client, method): print("Method %s not supported" % method) return fun = getattr(self.client, method) # Set headers headers = {} if auth: username, password = auth headers = self.get_auth_headers(username, password) # Prepare JSON if needed if json: import json as _json headers.update({'Content-Type': 'application/json'}) response = fun(url, data=_json.dumps(json), headers=headers, **kwargs) else: response = fun(url, **kwargs) self.assertTrue(response.headers['Content-Type'] == 'application/json') return response
用法(在测试用例中):
与requests的唯一区别是,与键入requests.get(...)不同的是,您必须键入self.request('get', ...)。在
requests.get(...)
self.request('get', ...)
如果你真的想要requests行为,你需要定义你自己的get,put,post,delete的包装
get
put
post
delete
注意:
最好的方法是将FlaskClient子类化,如Flask API documentation所述
FlaskClient
据我所知,您需要的是一个嘲弄(参见What is Mocking?和Mock Object)。好吧,下面列出几个选项:
如果您打算只模拟请求包,请使用requests-mock library,它旨在模拟请求包中的响应。
另一个选择是使用pythonmock libary来模拟requests模块,另请参见An Introduction to Mocking in Python 。
您可以使用下面代码部分中定义的
requests
方法。 要使用它,还需要定义下面代码中显示的get_auth_headers
方法。在特点:
自动设置请求头。在
Content-Type: Application/json
传递时{Basic Authentication
在传递{json
数据作为字符串转储到Flask测试客户端。在requests.Response
对象中代码:
用法(在测试用例中):
^{pr2}$与
requests
的唯一区别是,与键入requests.get(...)
不同的是,您必须键入self.request('get', ...)
。在如果你真的想要
requests
行为,你需要定义你自己的get
,put
,post
,delete
的包装注意:
最好的方法是将
FlaskClient
子类化,如Flask API documentation所述据我所知,您需要的是一个嘲弄(参见What is Mocking?和Mock Object)。好吧,下面列出几个选项:
如果您打算只模拟请求包,请使用requests-mock library,它旨在模拟请求包中的响应。
另一个选择是使用pythonmock libary来模拟
requests
模块,另请参见An Introduction to Mocking in Python 。相关问题 更多 >
编程相关推荐