我想添加測試到我的基本應用程序。訪問所有內容需要登錄。(unittest)測試瓶安全:無法通過登錄頁
這裏是我的測試用例類:
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()
我正在我的測試使用nosetests在終端像這樣: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/
或重定向我與閃過消息登錄頁面「請登錄訪問此頁面」。但事實並非如此。
我無法弄清楚什麼是錯的。我根據我的測試過的人的我瓶文檔中發現this app boilerplate
我看你使用CSRF令牌 - 你嘗試禁用它們,看是否得到您更遠?我知道他們已經比我記憶中的更多時間讓我受到了考驗。 –
如果您使用(或可以使用)Flask 0.10,我強烈推薦使用新的假上下文:http://flask.pocoo.org/docs/testing/#faking-resources-and-context我們是目前正在做一些與您爲我們的測試所做的非常相似的事情,只要我們可以升級,我就會全力以赴支持這一點。 –
@RachelSanders - 我已經把'WTF_CSRF_ENABLED'設置爲'False' –