[英]Flask, flask_login, pytest: How do I set flask_login's current_user?
[英]How to set current_user for pytest?
我正在為在查詢中使用當前登錄用戶的視圖編寫單元測試:
@app.route('/vendors/create', methods=['GET', 'POST'])
@login_required
def create_vendors():
vendor_form = VendorForm(request.form)
if vendor_form.validate_on_submit():
vendor = db.session.query(Vendors).filter(Vendors.name == vendor_form.name.data,
Vendors.users.contains(g.user)).first()
if vendor:
flash('There is a vendor with this name already.')
return redirect(url_for('create_vendors', vendor_form=vendor_form))
vendor = Vendors(name=vendor_form.name.data, aws_access_key=vendor_form.aws_access_key.data,
merchant_key=vendor_form.merchant_key.data, secret_key=vendor_form.secret_key.data)
vendor.users.append(current_user)
db.session.add(vendor)
db.session.commit()
return redirect(url_for('vendors'))
return render_template('edit_vendor.html', vendor_form=vendor_form)
和測試:
def test_create_vendor(self):
response = TestViews.client.post('/vendors/create', follow_redirects=True,
data=dict(name='Name', aws_access_key='aws_access_key',
merchant_key='merchant_key',
secret_key='secret_key'))
assert response.status_code == 200
vendors = db.session.query(Vendors).filter(Vendors.aws_access_key == 'aws_access_key').all()
assert len(vendors) == 1
assert vendors[0].name == 'Name'
在我的設置中LOGIN_DISABLED = True
。
我的問題是,在運行測試時,永遠不會設置current_user 。
我已經嘗試使用測試客戶端登錄並使用with TestLogin.client:
包裝我的測試with TestLogin.client:
但是current_user
從未設置過。 關於如何設置它的任何想法?
考慮我為此問題創建的以下示例應用
from flask import Flask, request,
from flask_login import LoginManager
from flask_login.utils import login_required, current_user, login_user
app = Flask(__name__)
app.secret_key = 'super secret key'
app.config['SESSION_TYPE'] = 'filesystem'
login_manager = LoginManager()
login_manager.init_app(app)
class MyUser():
name = "tarun"
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return 10
@login_manager.user_loader
def load_user(user_id):
return MyUser()
@app.route("/login", methods=["POST"])
def login():
login_user(MyUser())
return "Authenticated"
@app.route("/", methods=["GET", "POST"])
@login_required
def index():
return "Authenticated " # + current_user
if __name__ == "__main__":
app.run(debug=True)
有不同的方法來測試登錄的流程。
禁用登錄和@login_required
在此,您不要在請求調用中使用current_user
,只是保護流向經過身份驗證的用戶。 在這種情況下,您可以使用以下方法
import flasktest as flaskr
class FlaskrTestCase(unittest.TestCase):
def setUp(self):
flaskr.app.testing = True
flaskr.app.config['LOGIN_DISABLED'] = True
flaskr.app.login_manager.init_app(flaskr.app)
self.app = flaskr.app.test_client()
def test_without_login(self):
res = self.app.post("/")
assert "Unauthorized" in res.data
在這種情況下,測試將失敗,因為用戶將允許訪問經過身份驗證的流。 並且current_user
將設置為匿名用戶。 它與禁用@login_required
一樣好。
用實際登錄進行測試
為此,您需要確保可以使用POST登錄到您實際登錄的端點的應用程序
import unittest
import flasktest as flaskr
class FlaskrTestCase(unittest.TestCase):
def setUp(self):
flaskr.app.testing = True
self.app = flaskr.app.test_client()
def tearDown(self):
pass
def test_login(self):
self.app.post("/login")
res = self.app.get("/")
assert "Authenticated" in res.data
def test_without_login(self):
res = self.app.post("/")
assert "Unauthorized" in res.data
這甚至可以正確設置current_user
。 在我的情況下,我沒有采取任何表單數據參數,在您的情況下,您將使用類似下面的內容
self.app.post('/login', data=dict(
username=username,
password=password
), follow_redirects=True)
使用會話Cookie
在這種情況下,您設置會話user_id
和_fresh
def test_login_session(self):
with self.app.session_transaction() as sess:
sess['user_id'] = '12'
sess['_fresh'] = True # https://flask-login.readthedocs.org/en/latest/#fresh-logins
res = self.app.get("/")
assert "Authenticated" in res.data
這將反過來調用
@login_manager.user_loader
def load_user(user_id):
return MyUser()
根據我們在會話12
提供的user_id
獲取實際用戶
只需模擬flask_login.current_user並設置一個固定的返回值,如'testuser'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.