Skip to content
Myr

test_reqctx.py

This file

Path

tests/test_reqctx.py

227 lines · 5.6 KiB · Python

Last changed by

resolve merge conflictsKenneth Reitzbefore adoption31174fe

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    tests.reqctx4    ~~~~~~~~~~~~56    Tests the request context.78    :copyright: (c) 2015 by Armin Ronacher.9    :license: BSD, see LICENSE for more details.10"""1112import pytest1314import flask15from flask.sessions import SessionInterface1617try:18    from greenlet import greenlet19except ImportError:20    greenlet = None212223def test_teardown_on_pop(app):24    buffer = []2526    @app.teardown_request27    def end_of_request(exception):28        buffer.append(exception)2930    ctx = app.test_request_context()31    ctx.push()32    assert buffer == []33    ctx.pop()34    assert buffer == [None]353637def test_teardown_with_previous_exception(app):38    buffer = []3940    @app.teardown_request41    def end_of_request(exception):42        buffer.append(exception)4344    try:45        raise Exception('dummy')46    except Exception:47        pass4849    with app.test_request_context():50        assert buffer == []51    assert buffer == [None]525354def test_teardown_with_handled_exception(app):55    buffer = []5657    @app.teardown_request58    def end_of_request(exception):59        buffer.append(exception)6061    with app.test_request_context():62        assert buffer == []63        try:64            raise Exception('dummy')65        except Exception:66            pass67    assert buffer == [None]686970def test_proper_test_request_context(app):71    app.config.update(72        SERVER_NAME='localhost.localdomain:5000'73    )7475    @app.route('/')76    def index():77        return None7879    @app.route('/', subdomain='foo')80    def sub():81        return None8283    with app.test_request_context('/'):84        assert flask.url_for('index', _external=True) == \85               'http://localhost.localdomain:5000/'8687    with app.test_request_context('/'):88        assert flask.url_for('sub', _external=True) == \89               'http://foo.localhost.localdomain:5000/'9091    try:92        with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):93            pass94    except ValueError as e:95        assert str(e) == (96            "the server name provided "97            "('localhost.localdomain:5000') does not match the "98            "server name from the WSGI environment ('localhost')"99        )100101    app.config.update(SERVER_NAME='localhost')102    with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):103        pass104105    app.config.update(SERVER_NAME='localhost:80')106    with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):107        pass108109110def test_context_binding(app):111    @app.route('/')112    def index():113        return 'Hello %s!' % flask.request.args['name']114115    @app.route('/meh')116    def meh():117        return flask.request.url118119    with app.test_request_context('/?name=World'):120        assert index() == 'Hello World!'121    with app.test_request_context('/meh'):122        assert meh() == 'http://localhost/meh'123    assert flask._request_ctx_stack.top is None124125126def test_context_test(app):127    assert not flask.request128    assert not flask.has_request_context()129    ctx = app.test_request_context()130    ctx.push()131    try:132        assert flask.request133        assert flask.has_request_context()134    finally:135        ctx.pop()136137138def test_manual_context_binding(app):139    @app.route('/')140    def index():141        return 'Hello %s!' % flask.request.args['name']142143    ctx = app.test_request_context('/?name=World')144    ctx.push()145    assert index() == 'Hello World!'146    ctx.pop()147    with pytest.raises(RuntimeError):148        index()149150151@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')152class TestGreenletContextCopying(object):153154    def test_greenlet_context_copying(self, app, client):155        greenlets = []156157        @app.route('/')158        def index():159            reqctx = flask._request_ctx_stack.top.copy()160161            def g():162                assert not flask.request163                assert not flask.current_app164                with reqctx:165                    assert flask.request166                    assert flask.current_app == app167                    assert flask.request.path == '/'168                    assert flask.request.args['foo'] == 'bar'169                assert not flask.request170                return 42171172            greenlets.append(greenlet(g))173            return 'Hello World!'174175        rv = client.get('/?foo=bar')176        assert rv.data == b'Hello World!'177178        result = greenlets[0].run()179        assert result == 42180181    def test_greenlet_context_copying_api(self, app, client):182        greenlets = []183184        @app.route('/')185        def index():186            reqctx = flask._request_ctx_stack.top.copy()187188            @flask.copy_current_request_context189            def g():190                assert flask.request191                assert flask.current_app == app192                assert flask.request.path == '/'193                assert flask.request.args['foo'] == 'bar'194                return 42195196            greenlets.append(greenlet(g))197            return 'Hello World!'198199        rv = client.get('/?foo=bar')200        assert rv.data == b'Hello World!'201202        result = greenlets[0].run()203        assert result == 42204205206def test_session_error_pops_context():207    class SessionError(Exception):208        pass209210    class FailingSessionInterface(SessionInterface):211        def open_session(self, app, request):212            raise SessionError()213214    class CustomFlask(flask.Flask):215        session_interface = FailingSessionInterface()216217    app = CustomFlask(__name__)218219    @app.route('/')220    def index():221        # shouldn't get here222        assert False223224    response = app.test_client().get('/')225    assert response.status_code == 500226    assert not flask.request227    assert not flask.current_app