提供fixture和marker的py.test插件可以简化异步tornado应用程序的测试。
pytest-tornado的Python项目详细描述
提供夹具和标记以简化测试的py.test插件 异步龙卷风的应用。
安装
pip install pytest-tornado
示例
importpytestimporttornado.webclassMainHandler(tornado.web.RequestHandler):defget(self):self.write("Hello, world")application=tornado.web.Application([(r"/",MainHandler),])@pytest.fixturedefapp():returnapplication@pytest.mark.gen_testdeftest_hello_world(http_client,base_url):response=yieldhttp_client.fetch(base_url)assertresponse.code==200
运行测试
py.test
固定装置
- IO U回路
- 为每个测试用例创建tornado.ioloop.IOLoop的实例
- HTTP端口
- 获取测试服务器使用的端口
- 基本URL
- 获取测试服务器的绝对基url, 例如http://localhost:59828。 也可以在使用https fixture的测试中使用,然后将返回 相应的url,例如http://localhost:48372.
- HTTP服务器
- 启动Tornado HTTP服务器,必须创建appfixture, 返回要测试的tornado.web.Application
- http_客户端
- 获取异步http客户端
还可以使用https测试应用程序。 使用https运行服务器需要证书。
- https\u端口
- 获取测试服务器使用的端口。
- https\u服务器
- 启动Tornado https服务器。必须创建一个appfixture, 它返回要测试的tornado.web.Application,并且 一个ssl_optionsfixture,它返回 tornado.httpserver.HTTPServer.
- https\u客户端
- 获取异步http客户端。 如果测试使用自签名证书,则可以设置 verify=False关于fetch方法。
显示插件提供的设备:
py.test --fixtures
标记
使用gen_test标记可以编写与 tornado.gen模块:
@pytest.mark.gen_testdeftest_tornado(http_client):response=yieldhttp_client.fetch('http://www.tornadoweb.org/')assertresponse.code==200
此标记还支持使用异步/等待语法编写测试:
@pytest.mark.gen_testasyncdeftest_tornado(http_client):response=awaithttp_client.fetch('http://www.tornadoweb.org/')assertresponse.code==200
标记的测试将在5秒后超时。超时可以修改为 设置ASYNC_TEST_TIMEOUT环境变量, --async-test-timeout命令行参数或标记参数。
@pytest.mark.gen_test(timeout=5)deftest_tornado(http_client):yieldhttp_client.fetch('http://www.tornadoweb.org/')
标记还可以接收一个run_sync标志,如果关闭该标志,它将添加为协同程序并运行ioloop(直到超时),而不是同步运行测试。例如,这允许同时在客户机和服务器上测试东西。
@pytest.mark.gen_test(run_sync=False)deftest_tornado(http_server,http_client):response=yieldhttp_client.fetch('http://localhost:5555/my_local_server_test/')assertresponse.body=='Run on the same IOLoop!'
显示插件提供的标记:
py.test --markers