Flask-Testing: 单元测试中的会话管理问题

1 投票
1 回答
626 浏览
提问于 2025-04-18 10:10

这是我的路由设置:

@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)不存在。我在网上找不到好的资源来说明如何在 Flask-Tests 中处理会话管理... 有没有人有好的方法可以分享一下?

1 个回答

2

你可以在之前发起登录请求:

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')

或者通过会话事务来设置会话(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')

撰写回答