2014-09-29 7 views
1

공식 hello world 예를 약간의 수정 된 버전 인 다음 토네이도 (V 4.0.2) 응용 프로그램, 고려 :테스트 토네이도 응용 프로그램

import tornado.ioloop 
import tornado.web 

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

application = tornado.web.Application([ 
    (r"/", MainHandler), 
]) 

if __name__ == "__main__": 
    application.listen(8888) 
    tornado.ioloop.IOLoop.instance().start() 

당신이 볼 수 있듯이, 여기에 유일한 차이점을 set_status 전화는 MainHandler입니다. 지금, 나는 그때 tests.py을 열고 내가 거기이 간단한 단위 테스트 넣어 app.py이 코드를 저장 : 분명히

E 
====================================================================== 
ERROR: test_bad_request (tests.SimpleTest) 
---------------------------------------------------------------------- 
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 "/usr/local/lib/python2.7/dist-packages/tornado/testing.py", line 494, in post_coroutine 
    timeout=timeout) 
    File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 418, in run_sync 
    return future_cell[0].result() 
    File "/usr/local/lib/python2.7/dist-packages/tornado/concurrent.py", line 109, in result 
    raise_exc_info(self._exc_info) 
    File "/usr/local/lib/python2.7/dist-packages/tornado/gen.py", line 631, in run 
    yielded = self.gen.throw(*sys.exc_info()) 
    File "tests.py", line 18, in test_bad_request 
    response = yield self.http_client.fetch(request) 
    File "/usr/local/lib/python2.7/dist-packages/tornado/gen.py", line 628, in run 
    value = future.result() 
    File "/usr/local/lib/python2.7/dist-packages/tornado/concurrent.py", line 111, in result 
    raise self._exception 
HTTPError: HTTP 400: Bad Request 

---------------------------------------------------------------------- 
Ran 1 test in 0.022s 

FAILED (errors=1) 
[E 140929 12:55:59 testing:687] FAIL 

: 나는 python -m tornado.test.runtests tests으로이 테스트를 실행하면

import tornado.ioloop 
from tornado.httpclient import HTTPRequest 
from tornado.testing import AsyncHTTPTestCase, gen_test 

from app import application 

class SimpleTest(AsyncHTTPTestCase): 
    def get_app(self): 
     return application 

    def get_new_ioloop(self): 
     return tornado.ioloop.IOLoop.instance() 

    @gen_test 
    def test_bad_request(self): 
     request = HTTPRequest(url=self.get_url('/')) 
     response = yield self.http_client.fetch(request) 
     self.assertEqual(response.code, 400) 

을 나는 다음과 같은 결과를 얻을 수 처리기가 400 상태 코드를 설정하기 때문에 이것은 정확합니다. 그런 경우 어떻게 신청할 수 있습니까? 4xx 코드가 유용하다고 생각하기 때문에 그 코드를 포기하고 싶지 않습니다. 그러나 나는 토네이도에 처음이어서 테스트 할 수있는 방법을 찾지 못했습니다. 있어요?

답변

4

이 시도 :

@gen_test 
    def test_bad_request(self): 
     request = HTTPRequest(url=self.get_url('/')) 
     with self.assertRaises(tornado.httpclient.HTTPError) as context: 
      yield self.http_client.fetch(request) 

     self.assertEqual(context.exception.code, 400) 

assertRaises에 대한 설명서를 참조하십시오.

+2

실제로 작동합니다. 그러나,''context.error.code'' 대신''context.exception.code''가 있어야합니다. ''tornado.web.HTTPError'가 아니라''tornado.httpclient.HTTPError''를 잡아야한다는 것도 언급 할 필요가 있습니다. 솔루션이 나에게 잘 보이지 않지만 (4xx 응답이 예외 인 이유는 무엇입니까?), 그 답은 만족 스럽습니다. 고맙습니다! – piotrekw

+0

수정 해 주셔서 감사합니다. 답변을 업데이트했습니다. Tornado의 HTTP 클라이언트가 서버 오류를 비롯하여 어떤 이유로 든 URL을 다운로드 할 수없는 경우 예외를 발생시키는 것이 합리적이라고 생각합니다. 어쨌든 그것이 그것이 제공하는 API입니다. =) –