Tornado 异步测试 AsyncHTTPTestCase

好风 发表于 2017-03-04T06:45:32.621084Z
引用地址:https://plus.ooclab.com/note/article/1349

Tornado 自带一个实现异步测试的类: tornado.testing.AsyncHTTPTestCase

参考:

application.py

import tornado.httpclient
import tornado.ioloop
import tornado.web


class MainHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        http = tornado.httpclient.AsyncHTTPClient()
        http.fetch("http://httpbin.org/get",
                   callback=self.on_response)

    def on_response(self, response):
        if response.error: raise tornado.web.HTTPError(500)
        self.write(response.body)
        self.finish()

application = tornado.web.Application([
    (r"/", MainHandler),
], debug=True)

if __name__ == "__main__":
    application.listen(12345)
    tornado.ioloop.IOLoop.instance().start()

test_application.py

# -*- coding: utf-8 -*-

import tornado.testing
import unittest

import application


class AsyncAppTestCase(tornado.testing.AsyncHTTPTestCase):
    def get_app(self):
        return application.application

    def get_new_ioloop(self):
        return IOLoop.instance()

    def test_async_response(self):
        self.http_client.fetch(self.get_url('/'), self.stop)
        response = self.wait()
        assert response.body == 'OK'

if __name__ == '__main__':
    unittest.main()

运行 python test_application.py

get_new_ioloop 请查看 http://www.tornadoweb.org/en/stable/testing.html#tornado.testing.AsyncTestCase.get_new_ioloop

FAQ

Async operation timed out after 5 seconds

增加超时机制

class LoginTestCase(MyCustomTestCase):

    @tornado.testing.gen_test(timeout=120)
    def test_login(self):
        # 注意: 此处不能使用 self.fetch
        response = yield self.http_client.fetch(
            self.get_url('/user/login'),
            method='POST',
            body=json.dumps({
                'phonenumber': self.phonenumber,
                'verification_code': self.verification_code,
            })
        )
        print("response = ", response)

AsyncHTTPTestCase, IOLoop is already running

Tornado 4.0.1, AsyncHTTPTestCase, IOLoop is already running

AsyncHTTPTestCase 中, tornado.testing.gen_test 与 self.fetch 不能同时使用

self.http_client.fetch 非200返回 raise HTTPError 异常

参考 tornado/httpclient.py 方法 AsyncHTTPClient.fetch(..., raise_error=True, **kwargs)raise_error 说明