tearDown不要求与Tornado进行单元测试

时间:2015-10-07 04:02:38

标签: python-2.7 tornado python-unittest rethinkdb-python

我正在使用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语句。

编辑:我已经把它缩小到我在tearDown中调用yield的事实。

编辑:将@ gen.coroutine添加到tearDown会显示print语句,但不会对数据库执行删除

1 个答案:

答案 0 :(得分:4)

使用yield@gen.coroutine使函数异步,从而更改其接口:调用者必须知道此更改。 unittest框架对协同程序一无所知,因此unittest调用的方法不一定是协程。

您可以使用@tornado.testing.gen_test代替@gen.coroutine,这可以让您在测试中使用yield,也可以使用setUptearDown调用的方法,但是不是setUptearDown本身(因为生成器机制在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()
相关问题