我正在使用Rethinkdb和Tornado与rethinkdb.set_loop_type("tornado")
我正在使用python单元测试来测试我的服务器路由。
这是我的unittest基类:
class ServerTest(AsyncHTTPTestCase):
def setUp(self):
super(ServerTest, self).setUp()
def get_app(self):
return Application(self.routes, debug = False)
def post(self, route, data):
result = self.fetch("/%s" % route, method = "POST",
body = json.dumps(data)).body
return json.loads(result)
def tearDown(self):
super(ServerTest, self).tearDown()
conn = yield r.connect()
yield r.db("test").table("test_table").delete().run(conn)
conn.close()
我注意到setUp
正常运行,但tearDown
没有。我的所有单元测试都正常传递,但是不会调用tearDown中的print语句。
编辑:将@ gen.coroutine添加到tearDown会显示print语句,但不会对数据库执行删除
答案 0 :(得分:4)
使用yield
和@gen.coroutine
使函数异步,从而更改其接口:调用者必须知道此更改。 unittest
框架对协同程序一无所知,因此unittest
调用的方法不一定是协程。
您可以使用@tornado.testing.gen_test
代替@gen.coroutine
,这可以让您在测试中使用yield
,也可以使用setUp
和tearDown
调用的方法,但是不是setUp
和tearDown
本身(因为生成器机制在super().setUp()
之前或super().tearDown()
之后无法工作。请使用gen_test
的辅助方法并将其命名为在yield
中没有 tearDown
:
def tearDown(self):
self.tearDownHelper()
super(ServerTest, self).tearDown()
@tornado.testing.gen_test
def tearDownHelper(self):
conn = yield r.connect()
yield r.db("test").table("test_table").delete().run(conn)
conn.close()