gpt4 book ai didi

python - flask 测试 : issues with session management with unittests

转载 作者:行者123 更新时间:2023-12-01 05:10:47 25 4
gpt4 key购买 nike

这是我的路线:

@blueprint.before_request
def load_session_from_cookie():
if request.endpoint != 'client.me':
try:
cookie = request.cookies.get(settings.COOKIE_NAME, None)

# if cookie does not exist, redirect to login url
if not cookie:
session.pop('accountId', None)
return redirect(settings.LOGIN_URL)

account = check_sso_cookie(cookie)

if 'accountId' in session:
return
elif 'accountId' in account:
session['accountId'] = account.get('accountId')
return
else:
session.pop('accountId', None)
return redirect(settings.LOGIN_URL)
except BadSignature:
session.pop('accountId', None)
return redirect(settings.LOGIN_URL)


@blueprint.route('/')
def home():
session.permanent = True
return render_template('index.html')

这是我的测试:

from flask import Flask
from flask.ext.testing import TestCase
from api.client import blueprint


class TestInitViews(TestCase):

render_templates = False

def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
app.config['SECRET_KEY'] = 'sekrit!'

app.register_blueprint(blueprint)

return app

def setUp(self):
self.app = self.create_app()
self.cookie = '{ "account_id": 100 }'

def test_root_route(self):
resp = self.client.get("/")
self.assert_template_used('index.html')

def test_root_route_404(self):
res = self.client.get('/foo')
self.assertEqual(res.status_code, 404)

问题是测试 test_root_route 失败,因为 session 不存在而发生重定向。我在网上找不到任何好的资源来展示如何将 session 管理与 Flask-Tests 结合起来...有人有这样做的好方法吗?

最佳答案

您可以在此之前发出登录请求:

def create_app(self):
...
app.config['TESTING'] = True # should off csrf
...

def test_root_route(self):
self.client.post(settings.LOGIN_URL, data={'login': 'l', 'password': 'p'})
resp = self.client.get('/')
self.assert_template_used('index.html')

对于一些困难的情况,可以模拟登录路由。

或者手动设置cookie:

def test_root_route(self):
resp = self.client.get('/', headers={'Cookie': 'accountId=test'})
self.assert_template_used('index.html')

或者使用 session 事务设置 session ( http://flask.pocoo.org/docs/testing/#accessing-and-modifying-sessions ):

def test_root_route(self):
with self.client.session_transaction() as session:
session['accountId'] = 'test'
resp = self.client.get('/')
self.assert_template_used('index.html')

关于python - flask 测试 : issues with session management with unittests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24277067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com