2016-08-03 3 views
1

私はスクリプトを使用して単体テストに慣れています。私は、ポストデータ内の引数でログインを検証しようとしたが、私は、ログインせずに他の機能にアクセスすることはできません@tornado.web.authenticatedのin.Becauseを記録し得る応答としてログインページを取得していないですし、それがページtornado.testingを使って `@ authenticated`ハンドラをテストするには?

import tornado 
from tornado.testing import AsyncTestCase 
from tornado.web import Application, RequestHandler 
import app 
import urllib 

class MyTestCase(AsyncTestCase): 
    @tornado.testing.gen_test 
    def test_http_fetch_login(self): 
     data = urllib.urlencode(dict(username='admin', password='')) 
     client = AsyncHTTPClient(self.io_loop) 
     response = yield client.fetch("http://localhost:8888/console/login/?", method="POST",body=data) 
     # Test contents of response 
     self.assertIn("Automaton web console", response.body) 

    @tornado.testing.gen_test 
    def test_http_fetch_config(self): 
     client = AsyncHTTPClient(self.io_loop) 
     response = yield client.fetch("http://localhost:8888/console/configuration/?") 
     self.assertIn("server-version",response.body) 

答えて

0

にログインする応答します@authenticatedを使用するコードをテストするには(ログインページ自体へのリダイレクトをテストしない限り)、get_current_userメソッドで受け入れられるCookie(または使用している認証の形式)を渡す必要があります。これの詳細は、あなたがあなたの認証をどのようにしているかによって変わりますが、Tornadoのセキュアなクッキーを使用している場合は、おそらくcreate_signed_value関数を使ってクッキーをエンコードします。

0

ドキュメントから:

あなたが認証されたデコレータ付きポスト()メソッドを飾る、そしてユーザーがログインしていない場合、サーバーは403応答を送信します。 @authenticatedデコレータは、self.current_user:self.redirect()ではない場合には単純に短縮され、ブラウザ以外のログインスキームには適切でない場合があります。

だからmockはこの回答で指摘のように行う使用することができます:あなたはsecure_cookies=Trueのアプリのparamを持っている場合は、別の403のステータスがPOSTにスローされますhttps://stackoverflow.com/a/18286742/1090700

を呼び出します。あなたは非デバッグファッションのコードをテストする場合は、このように、secure_cookies=Trueアプリケーションパラメータを維持しながらも、モックPOSTアクションを使用して、ちょうど同様check_xsrf_cookieハンドラメソッドを模擬することができます

# Some previous stuff... 
    with mock.patch.object(YourSecuredHandler, 'get_secure_cookie') as mget: 
     mget.return_value = 'user_email' 
     response = self.fetch('/', method='GET')  
    with mock.patch.object(
      YourSecuredHandler, 'check_xsrf_cookie') as mpost: 
     mpost.return_value = None 
     response = self.fetch(
      url, method="POST", body=parse.urlencode(body1), 
      headers=headers) 
     self.assertEqual(response.code, 201) 
関連する問題