您的位置:

tornado报错Exception("did not get expected exception")怎么办

  发布时间:2025-04-15 11:05:48
对于Tornado出现Exception("did not get expected exception")的问题,通常是因为测试代码中未正确捕获预期的异常。解决方法包括在测试代码中正确捕获期望异常、验证被测代码逻辑是否触发异常、确认断言语句正确。示例代码展示了使用AsyncHTTPTestCase解决这个问题的方法。

问题原因

tornado出现Exception("did not get expected exception")的原因是在进行测试时,代码中预期捕获某个特定的异常,但实际上并未捕获到该异常,从而导致断言失败,抛出了"did not get expected exception"的异常。这可能是由于测试代码逻辑错误、异常处理不完善或者异常类型与预期不一致等原因导致的。

解决方案

当Tornado出现Exception("did not get expected exception")异常时,通常是因为测试代码中期望捕获的异常没有被正确抛出。解决这个问题的方法是在测试代码中检查是否正确捕获了期望的异常。 首先,确保测试代码中的被测代码区块已被包裹在一个捕获异常的块中,例如使用tryexcept语句。在except语句中,应该捕获预期的异常,并且可以对异常进行进一步的验证或处理。 其次,检查被测代码的逻辑确实会触发预期的异常。如果被测代码中没有导致预期异常抛出,那么测试框架就会抛出Exception("did not get expected exception")异常。 最后,确认测试代码中的断言语句是否正确,以确保在预期异常出现时测试会通过。断言语句应该验证预期异常是否被正确捕获,可以使用测试框架提供的断言方法。 举例来说,假设有一个使用Tornado编写的异步Web应用程序,需要测试一个处理函数是否正确捕获了HTTP请求中的错误。在测试代码中应该包含对该处理函数的调用,并在测试代码中捕获并验证是否预期的异常被正确抛出。


import tornado.web
import tornado.testing
from tornado.web import RequestHandler

class TestMyHandler(tornado.testing.AsyncHTTPTestCase):
    def get_app(self):
        class MyHandler(RequestHandler):
            def get(self):
                try:
                    # Some code that may raise exceptions
                    pass
                except Exception as e:
                    raise tornado.web.HTTPError(400, reason=str(e))

        return tornado.web.Application([(r'/', MyHandler)])

    def test_handler(self):
        response = self.fetch('/')
        self.assertEqual(response.code, 400)
        self.assertTrue("expected error message" in response.body.decode())

在上面的测试代码中,test_handler方法通过调用fetch('/')来模拟对处理函数的HTTP请求,并在处理函数中引发异常,最后通过断言来验证是否预期的异常被正确捕获和处理。

具体例子

在使用Tornado框架时,有时可能会遇到 Exception("did not get expected exception") 这个异常。这个异常通常是由于测试代码中的异步操作导致测试无法按照预期顺序执行而引起的。为了正确使用Tornado并避免这个异常,你可以使用 Tornado 提供的 AsyncTestCase 来编写异步测试用例。 下面是一个示例代码,演示了如何正确使用 AsyncTestCase 来解决 Exception("did not get expected exception") 异常:


import tornado.testing
import tornado.web
from tornado.httpclient import AsyncHTTPClient

class MainHandler(tornado.web.RequestHandler):
    async def get(self):
        self.write("Hello, world")

class TestMainHandler(tornado.testing.AsyncHTTPTestCase):
    def get_app(self):
        return tornado.web.Application([(r"/", MainHandler)])

    def test_main_handler(self):
        self.fetch("/", method="GET", callback=self.stop)
        response = self.wait()
        self.assertEqual(response.code, 200)
        self.assertEqual(response.body, "Hello, world")

if __name__ == "__main__":
    tornado.testing.main()

在上面的示例代码中,我们首先定义了一个简单的 MainHandler 处理器,然后定义了一个继承自 AsyncHTTPTestCase 的测试类 TestMainHandler。在 test_main_handler 方法中,我们使用 fetch 方法发起一个异步的 GET 请求,并在回调函数中停止事件循环(self.stop()),然后通过 self.wait() 等待异步操作完成。最后,我们断言返回的响应状态码和响应内容是否符合预期。 通过这种方式,我们可以确保在 Tornado 中编写的异步代码能够正确地按照我们期望的顺序执行,从而避免出现 Exception("did not get expected exception") 这个异常。