“在Tornado中很容易模拟外部HTTP请求。”
flymock的Python项目详细描述
Flymock
在Tornado中很容易模拟外部HTTP请求。
安装
$ pip install --upgrade flymock
创建模拟数据
在测试包中创建一个目录:
$ mkdir __mock__
使用主机名作为配置文件名,假设url是http://example.com/demo, 配置文件名应该是example.com.yaml,配置如下:
-path:/demo# path of the request to matchmethod:GET# method of the request to matchheaders:# Response headersContent-Type:application/jsonbody:Hello world# Response bodycode:200# Response status code-path:/filebody_type:file# Use a file content as the responsebody:demo.json# Filename(same path of the config file)code:202-path:/jsonbody:# If body is an object, that will response JSON content.code:2
使用量
importosfromtornadoimporthttpclientfromtornadoimporttestingfromflymockimportFlyPatcherclassDemoTestCase(testing.AsyncTestCase):defsetUp(self):super(DemoTestCase,self).setUp()path=os.path.join(os.path.dirname(__file__),"__mock__")self.patcher=FlyPatcher(path)self.http_client=httpclient.AsyncHTTPClient()self.patcher.start()deftearDown(self):super(DemoTestCase,self).tearDown()self.patcher.stop()@testing.gen_testdeftest_mocked(self):resp=yieldself.http_client.fetch("http://example.com/demo")self.assertEqual(resp.code,200)
动态调整响应:
patcher=FlyPatcher("/path/to/__mock__")defhook(response):response.patch_json({"a":1})withpatcher.dynamic_hook(hook):# code goes herepass# shortcut to adjust JSONwithpatcher.patch_json({"a":1}):# code goes herepass