我的应用程序要求登录到Google,以便以后使用Google API。我已经进行了烧瓶跳舞,烧瓶安全,烧瓶sqlalchemy工作,可以在开发系统中登录和注销。
我一直在努力的是使用pytest对登录进行测试。我正在尝试通过调用flask_security.login_user强制登录,但test_login失败,好像没有人登录。我怀疑由于上下文设置而导致此问题,但是我尝试了很多不同的方法,但没有找到魔药。
不幸的是,虽然我在软件开发方面特别是在python方面有很多经验,但是我没有pytest / flask-dance / flask-security的背景知识来解决这个问题。
在settings.py
class Testing():
# default database
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
TESTING = True
WTF_CSRF_ENABLED = False
# need to set SERVER_NAME to something, else get a RuntimeError about not able to create URL adapter
SERVER_NAME = 'dev.localhost'
# need a default secret key - in production replace by config file
SECRET_KEY = "<test secret key>"
# fake credentials
GOOGLE_OAUTH_CLIENT_ID = 'fake-client-id'
GOOGLE_OAUTH_CLIENT_SECRET = 'fake-client-secret'
# need to allow logins in flask-security. see https://github.com/mattupstate/flask-security/issues/259
LOGIN_DISABLED = False
在conftest.py
import pytest
from racesupportcontracts import create_app
from racesupportcontracts.dbmodel import db
from racesupportcontracts.settings import Testing
@pytest.fixture
def app():
app = create_app(Testing)
yield app
@pytest.fixture
def dbapp(app):
db.drop_all()
db.create_all()
yield app
在test_basic.py
中def login_test_user(email):
from racesupportcontracts.dbmodel import db, User
from flask_security import login_user
user = User.query.filter_by(email=email).one()
login_user(user)
db.session.commit()
def test_login(dbapp):
app = dbapp
from racesupportcontracts.dbmodel import db, init_db
from racesupportcontracts import user_datastore
from flask import url_for
# init_db should create at least superadmin, admin roles
init_db(defineowner=False)
useremail = 'testuser@example.com'
with app.test_client() as client:
create_user(useremail, 'superadmin')
login_test_user(useremail)
resp = client.get('/', follow_redirects=True)
assert resp.status_code == 200
assert url_for('admin.logout') in resp.data
答案 0 :(得分:0)
调用login_user()
时,将修改flask.session
对象。但是,使用测试客户端时,you can only modify flask.session
inside of a session transaction。如果这样做,它应该可以工作:
with app.test_client() as client:
with client.session_transaction() as sess:
sess["user_id"] = 1 # if you want user 1 to be logged in for this test
resp = client.get('/', follow_redirects=True)
# make whatever assertions you want
如果您从GitHub安装了最新版本的Flask-Login,则还可以使用FlaskLoginClient
类来使其更具可读性:
# in conftest.py
from flask_login import FlaskLoginClient
@pytest.fixture
def app():
app = create_app(Testing)
app.test_client_class = FlaskLoginClient
yield app
# in test_basic.py
def test_login(app):
user = User.query.filter_by(email='testuser@example.com').one()
with app.test_client(user=user) as client:
resp = client.get('/', follow_redirects=True)
# make whatever assertions you want
不幸的是,the author of Flask-Dance refuses to publish an update of the package to PyPI,所以您不能使用PyPI上的Flask-Dance版本,您必须 从GitHub安装。 (我不知道他为什么拒绝发布更新。)