unittestを使用していくつかのハンドラを持つ竜巻アプリをテストしていますが、そのうちの1つは例外を発生させます。私はpython test.py
と、次のテストコードを実行した場合:ユニットテスト竜巻アプリケーション:エラーメッセージの表示を改善するには
# test.py
import unittest
import tornado.web
import tornado.testing
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write('Hello World') # handler works correctly
class HandlerWithError(tornado.web.RequestHandler):
def get(self):
raise Exception('Boom') # handler raises an exception
self.write('Hello World')
def make_app():
return tornado.web.Application([
(r'/main/', MainHandler),
(r'/error/', HandlerWithError),
])
class TornadoTestCase(tornado.testing.AsyncHTTPTestCase):
def get_app(self):
return make_app()
def test_main_handler(self):
response = self.fetch('/main/')
self.assertEqual(response.code, 200) # test should pass
def test_handler_with_error(self):
response = self.fetch('/error/')
self.assertEqual(response.code, 200) # test should fail with error
if __name__ == '__main__':
unittest.main()
テスト出力は次のようになります。しかし
ERROR:tornado.application:Uncaught exception GET /error/ (127.0.0.1)
HTTPServerRequest(protocol='http', host='localhost:36590', method='GET', uri='/error/', version='HTTP/1.1', remote_ip='127.0.0.1', headers={'Connection': 'close', 'Host': 'localhost:3
6590', 'Accept-Encoding': 'gzip'})
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado/web.py", line 1332, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "test.py", line 13, in get
raise Exception('Boom') # handler raises an exception
Exception: Boom
ERROR:tornado.access:500 GET /error/ (127.0.0.1) 19.16ms
F.
======================================================================
FAIL: test_handler_with_error (__main__.TornadoTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado/testing.py", line 118, in __call__
result = self.orig_method(*args, **kwargs)
File "test.py", line 33, in test_handler_with_error
self.assertEqual(response.code, 200) # test should fail with error
AssertionError: 500 != 200
----------------------------------------------------------------------
Ran 2 tests in 0.034s
FAILED (failures=1)
、私の代わりに失敗アサーションの、第二のテストのためにエラーを報告しunittestの期待します。さらに、 'Boom'例外のトレースバックがunittestテストレポートの前に表示され、失敗したテスト関数への参照が含まれていないという事実は、例外の原因を見つけるのを困難にします。
この状況をどのように処理するかについてのご意見はありますか?
ありがとうございます!
EDIT
私が予期しない見つけることtest_handler_with_error
が実際にassertEqual
主張を作るのではなく、エラーをスローに到着したという事実です。たとえば、次のコードは、self.assertEqual
文を実行し、その結果ERROR
代わりのテスト出力でFAIL
を報告していません:
# simple_test.py
import unittest
def foo():
raise Exception('Boom')
return 'bar'
class SimpleTestCase(unittest.TestCase):
def test_failing_function(self):
result = foo()
self.assertEqual(result, 'bar')
if __name__ == '__main__':
unittest.main()
お返事ありがとうございます。私は混乱の原因を明らかにするために質問を編集しました。 –
私の答えを編集する:あなたのテスト関数は例外を発生させる関数を直接呼び出していません。 –