[英]Can't create test client during unit test of Flask app
我試圖找出如何對一個從session['user_id']
抓取變量值的函數運行測試。 這是具體的測試方法:
def test_myProfile_page(self):
with app.test_client() as c:
with c.session_transaction() as sess:
sess['user_id'] = '1'
rv = c.get('/myProfile')
assert 'My Profile' in rv.data
這是正在測試的視圖:
@app.route('/myProfile')
def myProfile():
if not session.get('logged_in'):
return render_template('login.html')
else:
profileID = session['user_id']
userList = users.query.filter_by(id=profileID).all()
flash('My Profile')
return render_template('myProfile.html', userList=userList)
這是整個測試文件:
import os
import app
import unittest
import tempfile
class AppTestCase(unittest.TestCase):
def setUp(self):
self.db_fd, app.app.config['DATABASE'] = tempfile.mkstemp()
app.app.config['TESTING'] = True
self.app = app.app.test_client()
def tearDown(self):
os.close(self.db_fd)
os.unlink(app.app.config['DATABASE'])
def test_profile_page(self):
rv = self.app.get('/profile1')
assert 'Profile' in rv.data
def login(self, username, password):
return self.app.post('/login', data=dict(
username=username,
password=password
), follow_redirects=True)
def logout(self):
return self.app.get('/logout', follow_redirects=True)
def test_login_logout(self):
rv = self.login('Alex', 'passwordAlex')
assert 'Welcome' in rv.data
rv = self.logout()
assert 'You have been logged out' in rv.data
rv = self.login('Alex', 'noPassword')
assert 'You have to Login' in rv.data
rv = self.login('WrongName', 'passwordAlex')
assert 'You have to Login' in rv.data
def test_myProfile_page(self):
with app.test_client() as c:
with c.session_transaction() as sess:
sess['user_id'] = '1'
rv = c.get('/myProfile')
assert 'My Profile' in rv.data
if __name__ == '__main__':
unittest.main()
運行測試時顯示以下錯誤:
ERROR: test_myProfile_page (__main__.AppTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "app_tests.py", line 46, in test_myProfile_page
with app.test_client() as c:
AttributeError: 'module' object has no attribute 'test_client'
----------------------------------------------------------------------
Ran 3 tests in 0.165s
FAILED (errors=1)
為什么我會收到此錯誤,如何解決?
您已經在setUp
方法中創建了一個測試客戶端: self.app
。 app
是您在頂部導入的模塊,您需要在app.app
上引用app對象才能訪問Flask應用。 既然您已經創建了一個測試客戶端,您可以將測試更改為:
def test_myProfile_page(self):
with self.app as c:
with self.app.session_transaction() as sess:
sess['user_id'] = 1
sess['logged_in'] = True
rv = self.app.get('myProfile')
assert 'My Profile' in rv.data
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.