2017-03-02 6 views
0

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() 

答えて

0

をこれは正常な動作です。テスト自体は、リターンコードがHTTP 200であることを主張しています。正式なアサートであるため、結果は「エラー」ではなく「失敗」になります。 kwaranukの答えで述べたようにログを抑制することはできますが、実際にHTTP 500エラーの原因に関する情報は失われます。

なぜあなたのコードは投げるのではなく、アサートに到達するのですか?これは、テストコード HandlerWithError.getを呼び出さないためです。テストコードは、AsyncHTTPTestCaseクラスによって提供されるHTTPクライアントとの非同期HTTP GET操作を開始します。詳細については、そのクラスのソースコードを確認してください。イベントループは、HandlerWithError.getがローカルホストソケット経由でリクエストを受信し、そのソケットでHTTP 500で応答するまで実行されます。HandlerWithError.getが失敗すると、あなたのテスト機能の例外は、Googleの失敗以上のものです。comは例外を発生させます。単にHTTP 500になります。

ようこそasyncの世界へ!アサーションエラーとHandlerWithError.get()からのトレースバックをきれいに関連付ける簡単な方法はありません。

+0

お返事ありがとうございます。私は混乱の原因を明らかにするために質問を編集しました。 –

+0

私の答えを編集する:あなたのテスト関数は例外を発生させる関数を直接呼び出していません。 –

1

あなたはloggingを無効にすることができますし、唯一のテストレポートが表示されます。

logging.disable(logging.CRITICAL) 

あなたが

  • 作成のTestCaseサブクラス
  • 例のためにそれを置くことができます
  • テストランナー

詳細情報How can I disable logging while running unit tests in Python Django?

CI/CDシステムは、実際に、例えば正規化されたレポートを使用することに注意してくださいJUnitのと、より読みやすい/エレガントな方法でそれを提示 - 詳細:

関連する問題