Flask-Testing:使用单元测试进行会话管理的问题

时间:2014-06-18 04:25:17

标签: python flask

这是我的路线:

@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失败,因为重定向发生是因为会话不存在。我无法在线找到任何好的资源,显示如何将会话管理与Flask-Tests合并......任何人都有这样做的好方法吗?

1 个答案:

答案 0 :(得分: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')