基本アプリにテストを追加しようとしています。すべてにアクセスするにはログインが必要です。
これが私のテストケースクラスです:
class MyAppTestCase(FlaskTestCaseMixin):
def _create_app(self):
raise NotImplementedError
def _create_fixtures(self):
self.user = EmployeeFactory()
def setUp(self):
super(MyAppTestCase, self).setUp()
self.app = self._create_app()
self.client = self.app.test_client()
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
self._create_fixtures()
self._create_csrf_token()
def tearDown(self):
super(MyAppTestCase, self).tearDown()
db.drop_all()
self.app_context.pop()
def _post(self, route, data=None, content_type=None, follow_redirects=True, headers=None):
content_type = content_type or 'application/x-www-form-urlencoded'
return self.client.post(route, data=data, follow_redirects=follow_redirects, content_type=content_type, headers=headers)
def _login(self, email=None, password=None):
email = email or self.user.email
password = password or 'password'
data = {
'email': email,
'password': password,
'remember': 'y'
}
return self._post('/login', data=data)
class MyFrontendTestCase(MyAppTestCase):
def _create_app(self):
return create_app(settings)
def setUp(self):
super(MyFrontendTestCase, self).setUp()
self._login()
次のように、ターミナルでノーズテストを使用してテストを実行しています。source my_env/bin/activate && nosetests --exe
次のような基本的なテストは失敗します。
class CoolTestCase(MyFrontendTestCase):
def test_logged_in(self):
r = self._login()
self.assertIn('MyAppName', r.data)
def test_authenticated_access(self):
r = self.get('/myroute/')
self.assertIn('MyAppName', r.data)
r.data
出力から、エラー (ユーザー名やパスワードが間違っているなど) やアラート (「このページにアクセスするにはログインしてください」) のないログイン ページの HTML だけであることがわかります。
setUp
プロセス中にログインしているので、「このページにアクセスするにはログインしてください」というフラッシュメッセージが表示されたログインページにアクセスするか、ログインページにリダイレクトするtest_authenticated_access
必要がありました。/myroute/
しかし、そうではありませんでした。
何が悪いのかわかりません。Flask のドキュメントとこのアプリのボイラープレートで見つけたものに基づいてテストを行いました