Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

236 lines · 6.2 KiB · Python

Last changed by

Use pytest.raises() instead of try/catch with asser 0Reuvenbefore adoption4dc2ef1

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    tests.testing4    ~~~~~~~~~~~~~56    Test client and more.78    :copyright: (c) 2015 by Armin Ronacher.9    :license: BSD, see LICENSE for more details.10"""11import pytest1213import flask1415from flask._compat import text_type161718def test_environ_defaults_from_config():19    app = flask.Flask(__name__)20    app.testing = True21    app.config['SERVER_NAME'] = 'example.com:1234'22    app.config['APPLICATION_ROOT'] = '/foo'23    @app.route('/')24    def index():25        return flask.request.url2627    ctx = app.test_request_context()28    assert ctx.request.url == 'http://example.com:1234/foo/'29    with app.test_client() as c:30        rv = c.get('/')31        assert rv.data == b'http://example.com:1234/foo/'3233def test_environ_defaults():34    app = flask.Flask(__name__)35    app.testing = True36    @app.route('/')37    def index():38        return flask.request.url3940    ctx = app.test_request_context()41    assert ctx.request.url == 'http://localhost/'42    with app.test_client() as c:43        rv = c.get('/')44        assert rv.data == b'http://localhost/'4546def test_redirect_keep_session():47    app = flask.Flask(__name__)48    app.secret_key = 'testing'4950    @app.route('/', methods=['GET', 'POST'])51    def index():52        if flask.request.method == 'POST':53            return flask.redirect('/getsession')54        flask.session['data'] = 'foo'55        return 'index'5657    @app.route('/getsession')58    def get_session():59        return flask.session.get('data', '<missing>')6061    with app.test_client() as c:62        rv = c.get('/getsession')63        assert rv.data == b'<missing>'6465        rv = c.get('/')66        assert rv.data == b'index'67        assert flask.session.get('data') == 'foo'68        rv = c.post('/', data={}, follow_redirects=True)69        assert rv.data == b'foo'7071        # This support requires a new Werkzeug version72        if not hasattr(c, 'redirect_client'):73            assert flask.session.get('data') == 'foo'7475        rv = c.get('/getsession')76        assert rv.data == b'foo'7778def test_session_transactions():79    app = flask.Flask(__name__)80    app.testing = True81    app.secret_key = 'testing'8283    @app.route('/')84    def index():85        return text_type(flask.session['foo'])8687    with app.test_client() as c:88        with c.session_transaction() as sess:89            assert len(sess) == 090            sess['foo'] = [42]91            assert len(sess) == 192        rv = c.get('/')93        assert rv.data == b'[42]'94        with c.session_transaction() as sess:95            assert len(sess) == 196            assert sess['foo'] == [42]9798def test_session_transactions_no_null_sessions():99    app = flask.Flask(__name__)100    app.testing = True101102    with app.test_client() as c:103        with pytest.raises(RuntimeError) as e:104            with c.session_transaction() as sess:105                pass106        assert 'Session backend did not open a session' in str(e.value)107108def test_session_transactions_keep_context():109    app = flask.Flask(__name__)110    app.testing = True111    app.secret_key = 'testing'112113    with app.test_client() as c:114        rv = c.get('/')115        req = flask.request._get_current_object()116        assert req is not None117        with c.session_transaction():118            assert req is flask.request._get_current_object()119120def test_session_transaction_needs_cookies():121    app = flask.Flask(__name__)122    app.testing = True123    c = app.test_client(use_cookies=False)124    with pytest.raises(RuntimeError) as e:125        with c.session_transaction() as s:126            pass127    assert 'cookies' in str(e.value)128129def test_test_client_context_binding():130    app = flask.Flask(__name__)131    app.config['LOGGER_HANDLER_POLICY'] = 'never'132    @app.route('/')133    def index():134        flask.g.value = 42135        return 'Hello World!'136137    @app.route('/other')138    def other():139        1 // 0140141    with app.test_client() as c:142        resp = c.get('/')143        assert flask.g.value == 42144        assert resp.data == b'Hello World!'145        assert resp.status_code == 200146147        resp = c.get('/other')148        assert not hasattr(flask.g, 'value')149        assert b'Internal Server Error' in resp.data150        assert resp.status_code == 500151        flask.g.value = 23152153    try:154        flask.g.value155    except (AttributeError, RuntimeError):156        pass157    else:158        raise AssertionError('some kind of exception expected')159160def test_reuse_client():161    app = flask.Flask(__name__)162    c = app.test_client()163164    with c:165        assert c.get('/').status_code == 404166167    with c:168        assert c.get('/').status_code == 404169170def test_test_client_calls_teardown_handlers():171    app = flask.Flask(__name__)172    called = []173    @app.teardown_request174    def remember(error):175        called.append(error)176177    with app.test_client() as c:178        assert called == []179        c.get('/')180        assert called == []181    assert called == [None]182183    del called[:]184    with app.test_client() as c:185        assert called == []186        c.get('/')187        assert called == []188        c.get('/')189        assert called == [None]190    assert called == [None, None]191192def test_full_url_request():193    app = flask.Flask(__name__)194    app.testing = True195196    @app.route('/action', methods=['POST'])197    def action():198        return 'x'199200    with app.test_client() as c:201        rv = c.post('http://domain.com/action?vodka=42', data={'gin': 43})202        assert rv.status_code == 200203        assert 'gin' in flask.request.form204        assert 'vodka' in flask.request.args205206def test_subdomain():207    app = flask.Flask(__name__)208    app.config['SERVER_NAME'] = 'example.com'209    @app.route('/', subdomain='<company_id>')210    def view(company_id):211        return company_id212213    with app.test_request_context():214        url = flask.url_for('view', company_id='xxx')215216    with app.test_client() as c:217        response = c.get(url)218219    assert 200 == response.status_code220    assert b'xxx' == response.data221222def test_nosubdomain():223    app = flask.Flask(__name__)224    app.config['SERVER_NAME'] = 'example.com'225    @app.route('/<company_id>')226    def view(company_id):227        return company_id228229    with app.test_request_context():230        url = flask.url_for('view', company_id='xxx')231232    with app.test_client() as c:233        response = c.get(url)234235    assert 200 == response.status_code236    assert b'xxx' == response.data