运行Tornado AsyncHTTPTestCase时获取错误的文件描述符

时间:2012-04-01 17:25:52

标签: python unit-testing tornado

使用Tornado AsyncHTTPTestCase运行测试时,我得到的堆栈跟踪与测试无关。测试正在通过,所以这可能发生在测试清理上?

我正在使用Python 2.7.2,Tornado 2.2。

测试代码是:

class AllServersHandlerTest(AsyncHTTPTestCase):

    def get_app(self):
        return Application([('/rest/test/', AllServersHandler)])

    def test_server_status_with_advertiser(self):
        on_new_host(None, '127.0.0.1')
        response = self.fetch('/rest/test/', method='GET')
        result = json.loads(response.body, 'utf8').get('data')
        self.assertEquals(['127.0.0.1'], result)

测试通过正常,但我从Tornado服务器获得以下堆栈跟踪。

OSError: [Errno 9] Bad file descriptor
INFO:root:200 POST /rest/serverStatuses (127.0.0.1) 0.00ms
DEBUG:root:error closing fd 688
Traceback (most recent call last):
  File "C:\Python27\Lib\site-packages\tornado-2.2-py2.7.egg\tornado\ioloop.py", line 173, in close
    os.close(fd)
OSError: [Errno 9] Bad file descriptor

如何干净地关闭测试用例?

1 个答案:

答案 0 :(得分:2)

我在龙卷风代码中挖掘并发现此代码将all_fds设置为True,然后导致io_loop.close()中的堆栈跟踪:

def tearDown(self):
    if (not IOLoop.initialized() or
        self.io_loop is not IOLoop.instance()):
        # Try to clean up any file descriptors left open in the ioloop.
        # This avoids leaks, especially when tests are run repeatedly
        # in the same process with autoreload (because curl does not
        # set FD_CLOEXEC on its file descriptors)
        self.io_loop.close(all_fds=True)
    super(AsyncTestCase, self).tearDown()

因此,覆盖测试类中的tearDown()会停止堆栈跟踪。

class AllServersHandlerTest(AsyncHTTPTestCase):

    def tearDown(self):
        pass

    def get_app(self):
        return Application([('/rest/test/', AllServersHandler)])

    def test_server_status_with_advertiser(self):
        on_new_host(None, '127.0.0.1')
        response = self.fetch('/rest/test/', method='GET')
        result = json.loads(response.body, 'utf8').get('data')
        self.assertEquals(['127.0.0.1'], result)

我不确定这种方法可能带来什么损害,所以如果其他人有更好的建议,请告诉我!