aiohttp测试库
async-responses的Python项目详细描述
异步响应
Async Responses是一个库,它提供了一种简单的方法来模拟受aioresponses启发的aiohttp响应。在
安装
库在PyPi上可用,您只需使用pip
安装它。在
$ pip install async-responses
使用
作为一个实例
^{pr2}$作为上下文管理器
withAsyncResponses()asar:ar.get(...)
使用dict作为处理程序
将dict作为handler
参数传递给异步响应将导致
作为JSON负载返回。在
importaiohttpfromasync_responsesimportAsyncResponsesasyncdeftest_response():ar=AsyncResponses()payload={'status':'ok'}ar.get('http://mock.url','/v1/status',handler=payload)asyncwithaiohttp.ClientSession()assession:response=awaitsession.get('http://mock.url/v1/status')assertawaitresponse.json()==payload
异常处理程序
调用异常为handler
参数的异步响应将导致
它正在被提起。在
importaiohttpfromasync_responsesimportAsyncResponsesimportpytestasyncdeftest_response():ar=AsyncResponses()ar.get('http://mock.url','/v1/status',handler=ZeroDivisionError)withpytest.raises(ZeroDivisionError):asyncwithaiohttp.ClientSession()assession:awaitsession.get('http://mock.url/v1/status')
使用字符串作为处理程序
importaiohttpfromasync_responsesimportAsyncResponsesasyncdeftest_response():ar=AsyncResponses()payload='ok'ar.get('http://mock.url','/v1/status',handler=payload)asyncwithaiohttp.ClientSession()assession:response=awaitsession.get('http://mock.url/v1/status')assertawaitresponse.text()==payload
可调用作为处理程序
importaiohttpfromasync_responsesimportAsyncResponsesasyncdeftest_response():defhandler(data,**kwargs):return{'status':'ok'}ar=AsyncResponses()ar.get('http://mock.url','/v1/status',handler=payload)asyncwithaiohttp.ClientSession()assession:response=awaitsession.get('http://mock.url/v1/status')assertawaitresponse.json()=={'status':'ok'}
带有自定义状态代码
importaiohttpfromasync_responsesimportAsyncResponsesasyncdeftest_response():payload={'status':'not good'}ar=AsyncResponses()ar.get('http://mock.url','/v1/status',handler=payload,status=500)asyncwithaiohttp.ClientSession()assession:response=awaitsession.get('http://mock.url/v1/status')assertresponse.status==500assertawaitresponse.json()==payload
使用自定义响应类
异步响应将使用作为参数传递给的响应类 ClientSession,因此可以使用自定义JSON序列化程序。在
importaiohttpasyncdeftest_response():classCustomResponse(aiohttp.ClientResponse):asyncdefjson(self,*args,**kwargs):return{'hello':'world'}ar=AsyncResponses()ar.get('http://mock.url','/v1/status',handler='')asyncwithaiohttp.ClientSession(response_class=CustomResponse)assession:response=awaitsession.get('http://mock.url/v1/status')assertawaitresponse.json()=={'hello':'world'}assertisinstance(response,CustomResponse)
- 项目
标签: