Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

1,366 lines · 43.9 KiB · Python

Last changed by

Remove flask superclassMarkus Unterwaditzerbefore adoptionaf4cb0f

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    tests.basic4    ~~~~~~~~~~~~~~~~~~~~~56    The basic functionality.78    :copyright: (c) 2014 by Armin Ronacher.9    :license: BSD, see LICENSE for more details.10"""1112import pytest1314import re15import uuid16import time17import flask18import pickle19import unittest20from datetime import datetime21from threading import Thread22from tests import emits_module_deprecation_warning23from flask._compat import text_type24from werkzeug.exceptions import BadRequest, NotFound, Forbidden25from werkzeug.http import parse_date26from werkzeug.routing import BuildError272829class TestBasicFunctionality(object):3031    def test_options_work(self):32        app = flask.Flask(__name__)33        @app.route('/', methods=['GET', 'POST'])34        def index():35            return 'Hello World'36        rv = app.test_client().open('/', method='OPTIONS')37        assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']38        assert rv.data == b''3940    def test_options_on_multiple_rules(self):41        app = flask.Flask(__name__)42        @app.route('/', methods=['GET', 'POST'])43        def index():44            return 'Hello World'45        @app.route('/', methods=['PUT'])46        def index_put():47            return 'Aha!'48        rv = app.test_client().open('/', method='OPTIONS')49        assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']5051    def test_options_handling_disabled(self):52        app = flask.Flask(__name__)53        def index():54            return 'Hello World!'55        index.provide_automatic_options = False56        app.route('/')(index)57        rv = app.test_client().open('/', method='OPTIONS')58        assert rv.status_code == 4055960        app = flask.Flask(__name__)61        def index2():62            return 'Hello World!'63        index2.provide_automatic_options = True64        app.route('/', methods=['OPTIONS'])(index2)65        rv = app.test_client().open('/', method='OPTIONS')66        assert sorted(rv.allow) == ['OPTIONS']6768    def test_request_dispatching(self):69        app = flask.Flask(__name__)70        @app.route('/')71        def index():72            return flask.request.method73        @app.route('/more', methods=['GET', 'POST'])74        def more():75            return flask.request.method7677        c = app.test_client()78        assert c.get('/').data == b'GET'79        rv = c.post('/')80        assert rv.status_code == 40581        assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']82        rv = c.head('/')83        assert rv.status_code == 20084        assert not rv.data # head truncates85        assert c.post('/more').data == b'POST'86        assert c.get('/more').data == b'GET'87        rv = c.delete('/more')88        assert rv.status_code == 40589        assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']9091    def test_disallow_string_for_allowed_methods(self):92        app = flask.Flask(__name__)93        with pytest.raises(TypeError):94            @app.route('/', methods='GET POST')95            def index():96                return "Hey"9798    def test_url_mapping(self):99        app = flask.Flask(__name__)100        def index():101            return flask.request.method102        def more():103            return flask.request.method104105        app.add_url_rule('/', 'index', index)106        app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])107108        c = app.test_client()109        assert c.get('/').data == b'GET'110        rv = c.post('/')111        assert rv.status_code == 405112        assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']113        rv = c.head('/')114        assert rv.status_code == 200115        assert not rv.data # head truncates116        assert c.post('/more').data == b'POST'117        assert c.get('/more').data == b'GET'118        rv = c.delete('/more')119        assert rv.status_code == 405120        assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']121122    def test_werkzeug_routing(self):123        from werkzeug.routing import Submount, Rule124        app = flask.Flask(__name__)125        app.url_map.add(Submount('/foo', [126            Rule('/bar', endpoint='bar'),127            Rule('/', endpoint='index')128        ]))129        def bar():130            return 'bar'131        def index():132            return 'index'133        app.view_functions['bar'] = bar134        app.view_functions['index'] = index135136        c = app.test_client()137        assert c.get('/foo/').data == b'index'138        assert c.get('/foo/bar').data == b'bar'139140    def test_endpoint_decorator(self):141        from werkzeug.routing import Submount, Rule142        app = flask.Flask(__name__)143        app.url_map.add(Submount('/foo', [144            Rule('/bar', endpoint='bar'),145            Rule('/', endpoint='index')146        ]))147148        @app.endpoint('bar')149        def bar():150            return 'bar'151152        @app.endpoint('index')153        def index():154            return 'index'155156        c = app.test_client()157        assert c.get('/foo/').data == b'index'158        assert c.get('/foo/bar').data == b'bar'159160    def test_session(self):161        app = flask.Flask(__name__)162        app.secret_key = 'testkey'163        @app.route('/set', methods=['POST'])164        def set():165            flask.session['value'] = flask.request.form['value']166            return 'value set'167        @app.route('/get')168        def get():169            return flask.session['value']170171        c = app.test_client()172        assert c.post('/set', data={'value': '42'}).data == b'value set'173        assert c.get('/get').data == b'42'174175    def test_session_using_server_name(self):176        app = flask.Flask(__name__)177        app.config.update(178            SECRET_KEY='foo',179            SERVER_NAME='example.com'180        )181        @app.route('/')182        def index():183            flask.session['testing'] = 42184            return 'Hello World'185        rv = app.test_client().get('/', 'http://example.com/')186        assert 'domain=.example.com' in rv.headers['set-cookie'].lower()187        assert 'httponly' in rv.headers['set-cookie'].lower()188189    def test_session_using_server_name_and_port(self):190        app = flask.Flask(__name__)191        app.config.update(192            SECRET_KEY='foo',193            SERVER_NAME='example.com:8080'194        )195        @app.route('/')196        def index():197            flask.session['testing'] = 42198            return 'Hello World'199        rv = app.test_client().get('/', 'http://example.com:8080/')200        assert 'domain=.example.com' in rv.headers['set-cookie'].lower()201        assert 'httponly' in rv.headers['set-cookie'].lower()202203    def test_session_using_server_name_port_and_path(self):204        app = flask.Flask(__name__)205        app.config.update(206            SECRET_KEY='foo',207            SERVER_NAME='example.com:8080',208            APPLICATION_ROOT='/foo'209        )210        @app.route('/')211        def index():212            flask.session['testing'] = 42213            return 'Hello World'214        rv = app.test_client().get('/', 'http://example.com:8080/foo')215        assert 'domain=example.com' in rv.headers['set-cookie'].lower()216        assert 'path=/foo' in rv.headers['set-cookie'].lower()217        assert 'httponly' in rv.headers['set-cookie'].lower()218219    def test_session_using_application_root(self):220        class PrefixPathMiddleware(object):221            def __init__(self, app, prefix):222                self.app = app223                self.prefix = prefix224            def __call__(self, environ, start_response):225                environ['SCRIPT_NAME'] = self.prefix226                return self.app(environ, start_response)227228        app = flask.Flask(__name__)229        app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')230        app.config.update(231            SECRET_KEY='foo',232            APPLICATION_ROOT='/bar'233        )234        @app.route('/')235        def index():236            flask.session['testing'] = 42237            return 'Hello World'238        rv = app.test_client().get('/', 'http://example.com:8080/')239        assert 'path=/bar' in rv.headers['set-cookie'].lower()240241    def test_session_using_session_settings(self):242        app = flask.Flask(__name__)243        app.config.update(244            SECRET_KEY='foo',245            SERVER_NAME='www.example.com:8080',246            APPLICATION_ROOT='/test',247            SESSION_COOKIE_DOMAIN='.example.com',248            SESSION_COOKIE_HTTPONLY=False,249            SESSION_COOKIE_SECURE=True,250            SESSION_COOKIE_PATH='/'251        )252        @app.route('/')253        def index():254            flask.session['testing'] = 42255            return 'Hello World'256        rv = app.test_client().get('/', 'http://www.example.com:8080/test/')257        cookie = rv.headers['set-cookie'].lower()258        assert 'domain=.example.com' in cookie259        assert 'path=/' in cookie260        assert 'secure' in cookie261        assert 'httponly' not in cookie262263    def test_missing_session(self):264        app = flask.Flask(__name__)265        def expect_exception(f, *args, **kwargs):266            try:267                f(*args, **kwargs)268            except RuntimeError as e:269                assert e.args and 'session is unavailable' in e.args[0]270            else:271                assert False, 'expected exception'272        with app.test_request_context():273            assert flask.session.get('missing_key') is None274            expect_exception(flask.session.__setitem__, 'foo', 42)275            expect_exception(flask.session.pop, 'foo')276277    def test_session_expiration(self):278        permanent = True279        app = flask.Flask(__name__)280        app.secret_key = 'testkey'281        @app.route('/')282        def index():283            flask.session['test'] = 42284            flask.session.permanent = permanent285            return ''286287        @app.route('/test')288        def test():289            return text_type(flask.session.permanent)290291        client = app.test_client()292        rv = client.get('/')293        assert 'set-cookie' in rv.headers294        match = re.search(r'\bexpires=([^;]+)(?i)', rv.headers['set-cookie'])295        expires = parse_date(match.group())296        expected = datetime.utcnow() + app.permanent_session_lifetime297        assert expires.year == expected.year298        assert expires.month == expected.month299        assert expires.day == expected.day300301        rv = client.get('/test')302        assert rv.data == b'True'303304        permanent = False305        rv = app.test_client().get('/')306        assert 'set-cookie' in rv.headers307        match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])308        assert match is None309310    def test_session_stored_last(self):311        app = flask.Flask(__name__)312        app.secret_key = 'development-key'313        app.testing = True314315        @app.after_request316        def modify_session(response):317            flask.session['foo'] = 42318            return response319        @app.route('/')320        def dump_session_contents():321            return repr(flask.session.get('foo'))322323        c = app.test_client()324        assert c.get('/').data == b'None'325        assert c.get('/').data == b'42'326327    def test_session_special_types(self):328        app = flask.Flask(__name__)329        app.secret_key = 'development-key'330        app.testing = True331        now = datetime.utcnow().replace(microsecond=0)332        the_uuid = uuid.uuid4()333334        @app.after_request335        def modify_session(response):336            flask.session['m'] = flask.Markup('Hello!')337            flask.session['u'] = the_uuid338            flask.session['dt'] = now339            flask.session['b'] = b'\xff'340            flask.session['t'] = (1, 2, 3)341            return response342343        @app.route('/')344        def dump_session_contents():345            return pickle.dumps(dict(flask.session))346347        c = app.test_client()348        c.get('/')349        rv = pickle.loads(c.get('/').data)350        assert rv['m'] == flask.Markup('Hello!')351        assert type(rv['m']) == flask.Markup352        assert rv['dt'] == now353        assert rv['u'] == the_uuid354        assert rv['b'] == b'\xff'355        assert type(rv['b']) == bytes356        assert rv['t'] == (1, 2, 3)357358    def test_session_cookie_setting(self):359        app = flask.Flask(__name__)360        app.testing = True361        app.secret_key = 'dev key'362        is_permanent = True363364        @app.route('/bump')365        def bump():366            rv = flask.session['foo'] = flask.session.get('foo', 0) + 1367            flask.session.permanent = is_permanent368            return str(rv)369370        @app.route('/read')371        def read():372            return str(flask.session.get('foo', 0))373374        def run_test(expect_header):375            with app.test_client() as c:376                assert c.get('/bump').data == b'1'377                assert c.get('/bump').data == b'2'378                assert c.get('/bump').data == b'3'379380                rv = c.get('/read')381                set_cookie = rv.headers.get('set-cookie')382                assert (set_cookie is not None) == expect_header383                assert rv.data == b'3'384385        is_permanent = True386        app.config['SESSION_REFRESH_EACH_REQUEST'] = True387        run_test(expect_header=True)388389        is_permanent = True390        app.config['SESSION_REFRESH_EACH_REQUEST'] = False391        run_test(expect_header=False)392393        is_permanent = False394        app.config['SESSION_REFRESH_EACH_REQUEST'] = True395        run_test(expect_header=False)396397        is_permanent = False398        app.config['SESSION_REFRESH_EACH_REQUEST'] = False399        run_test(expect_header=False)400401    def test_flashes(self):402        app = flask.Flask(__name__)403        app.secret_key = 'testkey'404405        with app.test_request_context():406            assert not flask.session.modified407            flask.flash('Zap')408            flask.session.modified = False409            flask.flash('Zip')410            assert flask.session.modified411            assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']412413    def test_extended_flashing(self):414        # Be sure app.testing=True below, else tests can fail silently.415        #416        # Specifically, if app.testing is not set to True, the AssertionErrors417        # in the view functions will cause a 500 response to the test client418        # instead of propagating exceptions.419420        app = flask.Flask(__name__)421        app.secret_key = 'testkey'422        app.testing = True423424        @app.route('/')425        def index():426            flask.flash(u'Hello World')427            flask.flash(u'Hello World', 'error')428            flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')429            return ''430431        @app.route('/test/')432        def test():433            messages = flask.get_flashed_messages()434            assert list(messages) == [435                u'Hello World',436                u'Hello World',437                flask.Markup(u'<em>Testing</em>')438            ]439            return ''440441        @app.route('/test_with_categories/')442        def test_with_categories():443            messages = flask.get_flashed_messages(with_categories=True)444            assert len(messages) == 3445            assert list(messages) == [446                ('message', u'Hello World'),447                ('error', u'Hello World'),448                ('warning', flask.Markup(u'<em>Testing</em>'))449            ]450            return ''451452        @app.route('/test_filter/')453        def test_filter():454            messages = flask.get_flashed_messages(category_filter=['message'], with_categories=True)455            assert list(messages) == [('message', u'Hello World')]456            return ''457458        @app.route('/test_filters/')459        def test_filters():460            messages = flask.get_flashed_messages(category_filter=['message', 'warning'], with_categories=True)461            assert list(messages) == [462                ('message', u'Hello World'),463                ('warning', flask.Markup(u'<em>Testing</em>'))464            ]465            return ''466467        @app.route('/test_filters_without_returning_categories/')468        def test_filters2():469            messages = flask.get_flashed_messages(category_filter=['message', 'warning'])470            assert len(messages) == 2471            assert messages[0] == u'Hello World'472            assert messages[1] == flask.Markup(u'<em>Testing</em>')473            return ''474475        # Create new test client on each test to clean flashed messages.476477        c = app.test_client()478        c.get('/')479        c.get('/test/')480481        c = app.test_client()482        c.get('/')483        c.get('/test_with_categories/')484485        c = app.test_client()486        c.get('/')487        c.get('/test_filter/')488489        c = app.test_client()490        c.get('/')491        c.get('/test_filters/')492493        c = app.test_client()494        c.get('/')495        c.get('/test_filters_without_returning_categories/')496497    def test_request_processing(self):498        app = flask.Flask(__name__)499        evts = []500        @app.before_request501        def before_request():502            evts.append('before')503        @app.after_request504        def after_request(response):505            response.data += b'|after'506            evts.append('after')507            return response508        @app.route('/')509        def index():510            assert 'before' in evts511            assert 'after' not in evts512            return 'request'513        assert 'after' not in evts514        rv = app.test_client().get('/').data515        assert 'after' in evts516        assert rv == b'request|after'517518    def test_after_request_processing(self):519        app = flask.Flask(__name__)520        app.testing = True521        @app.route('/')522        def index():523            @flask.after_this_request524            def foo(response):525                response.headers['X-Foo'] = 'a header'526                return response527            return 'Test'528        c = app.test_client()529        resp = c.get('/')530        assert resp.status_code == 200531        assert resp.headers['X-Foo'] == 'a header'532533    def test_teardown_request_handler(self):534        called = []535        app = flask.Flask(__name__)536        @app.teardown_request537        def teardown_request(exc):538            called.append(True)539            return "Ignored"540        @app.route('/')541        def root():542            return "Response"543        rv = app.test_client().get('/')544        assert rv.status_code == 200545        assert b'Response' in rv.data546        assert len(called) == 1547548    def test_teardown_request_handler_debug_mode(self):549        called = []550        app = flask.Flask(__name__)551        app.testing = True552        @app.teardown_request553        def teardown_request(exc):554            called.append(True)555            return "Ignored"556        @app.route('/')557        def root():558            return "Response"559        rv = app.test_client().get('/')560        assert rv.status_code == 200561        assert b'Response' in rv.data562        assert len(called) == 1563564    def test_teardown_request_handler_error(self):565        called = []566        app = flask.Flask(__name__)567        app.config['LOGGER_HANDLER_POLICY'] = 'never'568        @app.teardown_request569        def teardown_request1(exc):570            assert type(exc) == ZeroDivisionError571            called.append(True)572            # This raises a new error and blows away sys.exc_info(), so we can573            # test that all teardown_requests get passed the same original574            # exception.575            try:576                raise TypeError()577            except:578                pass579        @app.teardown_request580        def teardown_request2(exc):581            assert type(exc) == ZeroDivisionError582            called.append(True)583            # This raises a new error and blows away sys.exc_info(), so we can584            # test that all teardown_requests get passed the same original585            # exception.586            try:587                raise TypeError()588            except:589                pass590        @app.route('/')591        def fails():592            1 // 0593        rv = app.test_client().get('/')594        assert rv.status_code == 500595        assert b'Internal Server Error' in rv.data596        assert len(called) == 2597598    def test_before_after_request_order(self):599        called = []600        app = flask.Flask(__name__)601        @app.before_request602        def before1():603            called.append(1)604        @app.before_request605        def before2():606            called.append(2)607        @app.after_request608        def after1(response):609            called.append(4)610            return response611        @app.after_request612        def after2(response):613            called.append(3)614            return response615        @app.teardown_request616        def finish1(exc):617            called.append(6)618        @app.teardown_request619        def finish2(exc):620            called.append(5)621        @app.route('/')622        def index():623            return '42'624        rv = app.test_client().get('/')625        assert rv.data == b'42'626        assert called == [1, 2, 3, 4, 5, 6]627628    def test_error_handling(self):629        app = flask.Flask(__name__)630        app.config['LOGGER_HANDLER_POLICY'] = 'never'631        @app.errorhandler(404)632        def not_found(e):633            return 'not found', 404634        @app.errorhandler(500)635        def internal_server_error(e):636            return 'internal server error', 500637        @app.errorhandler(Forbidden)638        def forbidden(e):639            return 'forbidden', 403640        @app.route('/')641        def index():642            flask.abort(404)643        @app.route('/error')644        def error():645            1 // 0646        @app.route('/forbidden')647        def error2():648            flask.abort(403)649        c = app.test_client()650        rv = c.get('/')651        assert rv.status_code == 404652        assert rv.data == b'not found'653        rv = c.get('/error')654        assert rv.status_code == 500655        assert b'internal server error' == rv.data656        rv = c.get('/forbidden')657        assert rv.status_code == 403658        assert b'forbidden' == rv.data659660    def test_before_request_and_routing_errors(self):661        app = flask.Flask(__name__)662        @app.before_request663        def attach_something():664            flask.g.something = 'value'665        @app.errorhandler(404)666        def return_something(error):667            return flask.g.something, 404668        rv = app.test_client().get('/')669        assert rv.status_code == 404670        assert rv.data == b'value'671672    def test_user_error_handling(self):673        class MyException(Exception):674            pass675676        app = flask.Flask(__name__)677        @app.errorhandler(MyException)678        def handle_my_exception(e):679            assert isinstance(e, MyException)680            return '42'681        @app.route('/')682        def index():683            raise MyException()684685        c = app.test_client()686        assert c.get('/').data == b'42'687688    def test_http_error_subclass_handling(self):689        class ForbiddenSubclass(Forbidden):690            pass691692        app = flask.Flask(__name__)693        @app.errorhandler(ForbiddenSubclass)694        def handle_forbidden_subclass(e):695            assert isinstance(e, ForbiddenSubclass)696            return 'banana'697        @app.errorhandler(403)698        def handle_forbidden_subclass(e):699            assert not isinstance(e, ForbiddenSubclass)700            assert isinstance(e, Forbidden)701            return 'apple'702703        @app.route('/1')704        def index1():705            raise ForbiddenSubclass()706        @app.route('/2')707        def index2():708            flask.abort(403)709        @app.route('/3')710        def index3():711            raise Forbidden()712713        c = app.test_client()714        assert c.get('/1').data == b'banana'715        assert c.get('/2').data == b'apple'716        assert c.get('/3').data == b'apple'717718    def test_trapping_of_bad_request_key_errors(self):719        app = flask.Flask(__name__)720        app.testing = True721        @app.route('/fail')722        def fail():723            flask.request.form['missing_key']724        c = app.test_client()725        assert c.get('/fail').status_code == 400726727        app.config['TRAP_BAD_REQUEST_ERRORS'] = True728        c = app.test_client()729        try:730            c.get('/fail')731        except KeyError as e:732            assert isinstance(e, BadRequest)733        else:734            assert False, 'Expected exception'735736    def test_trapping_of_all_http_exceptions(self):737        app = flask.Flask(__name__)738        app.testing = True739        app.config['TRAP_HTTP_EXCEPTIONS'] = True740        @app.route('/fail')741        def fail():742            flask.abort(404)743744        c = app.test_client()745        try:746            c.get('/fail')747        except NotFound as e:748            pass749        else:750            assert False, 'Expected exception'751752    def test_enctype_debug_helper(self):753        from flask.debughelpers import DebugFilesKeyError754        app = flask.Flask(__name__)755        app.debug = True756        @app.route('/fail', methods=['POST'])757        def index():758            return flask.request.files['foo'].filename759760        # with statement is important because we leave an exception on the761        # stack otherwise and we want to ensure that this is not the case762        # to not negatively affect other tests.763        with app.test_client() as c:764            try:765                c.post('/fail', data={'foo': 'index.txt'})766            except DebugFilesKeyError as e:767                assert 'no file contents were transmitted' in str(e)768                assert 'This was submitted: "index.txt"' in str(e)769            else:770                assert False, 'Expected exception'771772    def test_response_creation(self):773        app = flask.Flask(__name__)774        @app.route('/unicode')775        def from_unicode():776            return u'Hällo Wörld'777        @app.route('/string')778        def from_string():779            return u'Hällo Wörld'.encode('utf-8')780        @app.route('/args')781        def from_tuple():782            return 'Meh', 400, {783                'X-Foo': 'Testing',784                'Content-Type': 'text/plain; charset=utf-8'785            } 786        @app.route('/two_args')787        def from_two_args_tuple():788            return 'Hello', {789                'X-Foo': 'Test',790                'Content-Type': 'text/plain; charset=utf-8'791            }792        @app.route('/args_status')793        def from_status_tuple():794            return 'Hi, status!', 400795        @app.route('/args_header')796        def from_response_instance_status_tuple():797            return flask.Response('Hello world', 404), {798                "X-Foo": "Bar",799                "X-Bar": "Foo"800            }801802        c = app.test_client()803        assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8')804        assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8')805        rv = c.get('/args')806        assert rv.data == b'Meh'807        assert rv.headers['X-Foo'] == 'Testing'808        assert rv.status_code == 400809        assert rv.mimetype == 'text/plain'810        rv2 = c.get('/two_args')811        assert rv2.data == b'Hello'812        assert rv2.headers['X-Foo'] == 'Test'813        assert rv2.status_code == 200814        assert rv2.mimetype == 'text/plain'815        rv3 = c.get('/args_status')816        assert rv3.data == b'Hi, status!'817        assert rv3.status_code == 400818        assert rv3.mimetype == 'text/html'819        rv4 = c.get('/args_header')820        assert rv4.data == b'Hello world'821        assert rv4.headers['X-Foo'] == 'Bar'822        assert rv4.headers['X-Bar'] == 'Foo'823        assert rv4.status_code == 404824825    def test_make_response(self):826        app = flask.Flask(__name__)827        with app.test_request_context():828            rv = flask.make_response()829            assert rv.status_code == 200830            assert rv.data == b''831            assert rv.mimetype == 'text/html'832833            rv = flask.make_response('Awesome')834            assert rv.status_code == 200835            assert rv.data == b'Awesome'836            assert rv.mimetype == 'text/html'837838            rv = flask.make_response('W00t', 404)839            assert rv.status_code == 404840            assert rv.data == b'W00t'841            assert rv.mimetype == 'text/html'842843    def test_make_response_with_response_instance(self):844        app = flask.Flask(__name__)845        with app.test_request_context():846            rv = flask.make_response(847                flask.jsonify({'msg': 'W00t'}), 400)848            assert rv.status_code == 400849            assert rv.data == b'{\n  "msg": "W00t"\n}'850            assert rv.mimetype == 'application/json'851852            rv = flask.make_response(853                flask.Response(''), 400)854            assert rv.status_code == 400855            assert rv.data == b''856            assert rv.mimetype == 'text/html'857858            rv = flask.make_response(859                flask.Response('', headers={'Content-Type': 'text/html'}),860                400, [('X-Foo', 'bar')])861            assert rv.status_code == 400862            assert rv.headers['Content-Type'] == 'text/html'863            assert rv.headers['X-Foo'] == 'bar'864865    def test_url_generation(self):866        app = flask.Flask(__name__)867        @app.route('/hello/<name>', methods=['POST'])868        def hello():869            pass870        with app.test_request_context():871            assert flask.url_for('hello', name='test x') == '/hello/test%20x'872            assert flask.url_for('hello', name='test x', _external=True) == \873                'http://localhost/hello/test%20x'874875    def test_build_error_handler(self):876        app = flask.Flask(__name__)877878        # Test base case, a URL which results in a BuildError.879        with app.test_request_context():880            pytest.raises(BuildError, flask.url_for, 'spam')881882        # Verify the error is re-raised if not the current exception.883        try:884            with app.test_request_context():885                flask.url_for('spam')886        except BuildError as err:887            error = err888        try:889            raise RuntimeError('Test case where BuildError is not current.')890        except RuntimeError:891            pytest.raises(BuildError, app.handle_url_build_error, error, 'spam', {})892893        # Test a custom handler.894        def handler(error, endpoint, values):895            # Just a test.896            return '/test_handler/'897        app.url_build_error_handlers.append(handler)898        with app.test_request_context():899            assert flask.url_for('spam') == '/test_handler/'900901    def test_custom_converters(self):902        from werkzeug.routing import BaseConverter903        class ListConverter(BaseConverter):904            def to_python(self, value):905                return value.split(',')906            def to_url(self, value):907                base_to_url = super(ListConverter, self).to_url908                return ','.join(base_to_url(x) for x in value)909        app = flask.Flask(__name__)910        app.url_map.converters['list'] = ListConverter911        @app.route('/<list:args>')912        def index(args):913            return '|'.join(args)914        c = app.test_client()915        assert c.get('/1,2,3').data == b'1|2|3'916917    def test_static_files(self):918        app = flask.Flask(__name__)919        app.testing = True920        rv = app.test_client().get('/static/index.html')921        assert rv.status_code == 200922        assert rv.data.strip() == b'<h1>Hello World!</h1>'923        with app.test_request_context():924            assert flask.url_for('static', filename='index.html') == \925                '/static/index.html'926        rv.close()927928    def test_none_response(self):929        app = flask.Flask(__name__)930        app.testing = True931        @app.route('/')932        def test():933            return None934        try:935            app.test_client().get('/')936        except ValueError as e:937            assert str(e) == 'View function did not return a response'938            pass939        else:940            assert "Expected ValueError"941942    def test_request_locals(self):943        assert repr(flask.g) == '<LocalProxy unbound>'944        assert not flask.g945946    def test_test_app_proper_environ(self):947        app = flask.Flask(__name__)948        app.config.update(949            SERVER_NAME='localhost.localdomain:5000'950        )951        @app.route('/')952        def index():953            return 'Foo'954955        @app.route('/', subdomain='foo')956        def subdomain():957            return 'Foo SubDomain'958959        rv = app.test_client().get('/')960        assert rv.data == b'Foo'961962        rv = app.test_client().get('/', 'http://localhost.localdomain:5000')963        assert rv.data == b'Foo'964965        rv = app.test_client().get('/', 'https://localhost.localdomain:5000')966        assert rv.data == b'Foo'967968        app.config.update(SERVER_NAME='localhost.localdomain')969        rv = app.test_client().get('/', 'https://localhost.localdomain')970        assert rv.data == b'Foo'971972        try:973            app.config.update(SERVER_NAME='localhost.localdomain:443')974            rv = app.test_client().get('/', 'https://localhost.localdomain')975            # Werkzeug 0.8976            assert rv.status_code == 404977        except ValueError as e:978            # Werkzeug 0.7979            assert str(e) == (980                "the server name provided "981                "('localhost.localdomain:443') does not match the "982                "server name from the WSGI environment ('localhost.localdomain')"983            )984985        try:986            app.config.update(SERVER_NAME='localhost.localdomain')987            rv = app.test_client().get('/', 'http://foo.localhost')988            # Werkzeug 0.8989            assert rv.status_code == 404990        except ValueError as e:991            # Werkzeug 0.7992            assert str(e) == (993                "the server name provided "994                "('localhost.localdomain') does not match the "995                "server name from the WSGI environment ('foo.localhost')"996            )997998        rv = app.test_client().get('/', 'http://foo.localhost.localdomain')999        assert rv.data == b'Foo SubDomain'10001001    def test_exception_propagation(self):1002        def apprunner(configkey):1003            app = flask.Flask(__name__)1004            app.config['LOGGER_HANDLER_POLICY'] = 'never'1005            @app.route('/')1006            def index():1007                1 // 01008            c = app.test_client()1009            if config_key is not None:1010                app.config[config_key] = True1011                try:1012                    c.get('/')1013                except Exception:1014                    pass1015                else:1016                    assert False, 'expected exception'1017            else:1018                assert c.get('/').status_code == 50010191020        # we have to run this test in an isolated thread because if the1021        # debug flag is set to true and an exception happens the context is1022        # not torn down.  This causes other tests that run after this fail1023        # when they expect no exception on the stack.1024        for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1025            t = Thread(target=apprunner, args=(config_key,))1026            t.start()1027            t.join()10281029    def test_max_content_length(self):1030        app = flask.Flask(__name__)1031        app.config['MAX_CONTENT_LENGTH'] = 641032        @app.before_request1033        def always_first():1034            flask.request.form['myfile']1035            assert False1036        @app.route('/accept', methods=['POST'])1037        def accept_file():1038            flask.request.form['myfile']1039            assert False1040        @app.errorhandler(413)1041        def catcher(error):1042            return '42'10431044        c = app.test_client()1045        rv = c.post('/accept', data={'myfile': 'foo' * 100})1046        assert rv.data == b'42'10471048    def test_url_processors(self):1049        app = flask.Flask(__name__)10501051        @app.url_defaults1052        def add_language_code(endpoint, values):1053            if flask.g.lang_code is not None and \1054               app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1055                values.setdefault('lang_code', flask.g.lang_code)10561057        @app.url_value_preprocessor1058        def pull_lang_code(endpoint, values):1059            flask.g.lang_code = values.pop('lang_code', None)10601061        @app.route('/<lang_code>/')1062        def index():1063            return flask.url_for('about')10641065        @app.route('/<lang_code>/about')1066        def about():1067            return flask.url_for('something_else')10681069        @app.route('/foo')1070        def something_else():1071            return flask.url_for('about', lang_code='en')10721073        c = app.test_client()10741075        assert c.get('/de/').data == b'/de/about'1076        assert c.get('/de/about').data == b'/foo'1077        assert c.get('/foo').data == b'/en/about'10781079    def test_inject_blueprint_url_defaults(self):1080        app = flask.Flask(__name__)1081        bp = flask.Blueprint('foo.bar.baz', __name__,1082                       template_folder='template')10831084        @bp.url_defaults1085        def bp_defaults(endpoint, values):1086            values['page'] = 'login'1087        @bp.route('/<page>')1088        def view(page): pass10891090        app.register_blueprint(bp)10911092        values = dict()1093        app.inject_url_defaults('foo.bar.baz.view', values)1094        expected = dict(page='login')1095        assert values == expected10961097        with app.test_request_context('/somepage'):1098            url = flask.url_for('foo.bar.baz.view')1099        expected = '/login'1100        assert url == expected11011102    def test_nonascii_pathinfo(self):1103        app = flask.Flask(__name__)1104        app.testing = True11051106        @app.route(u'/киртест')1107        def index():1108            return 'Hello World!'11091110        c = app.test_client()1111        rv = c.get(u'/киртест')1112        assert rv.data == b'Hello World!'11131114    def test_debug_mode_complains_after_first_request(self):1115        app = flask.Flask(__name__)1116        app.debug = True1117        @app.route('/')1118        def index():1119            return 'Awesome'1120        assert not app.got_first_request1121        assert app.test_client().get('/').data == b'Awesome'1122        try:1123            @app.route('/foo')1124            def broken():1125                return 'Meh'1126        except AssertionError as e:1127            assert 'A setup function was called' in str(e)1128        else:1129            assert False, 'Expected exception'11301131        app.debug = False1132        @app.route('/foo')1133        def working():1134            return 'Meh'1135        assert app.test_client().get('/foo').data == b'Meh'1136        assert app.got_first_request11371138    def test_before_first_request_functions(self):1139        got = []1140        app = flask.Flask(__name__)1141        @app.before_first_request1142        def foo():1143            got.append(42)1144        c = app.test_client()1145        c.get('/')1146        assert got == [42]1147        c.get('/')1148        assert got == [42]1149        assert app.got_first_request11501151    def test_before_first_request_functions_concurrent(self):1152        got = []1153        app = flask.Flask(__name__)11541155        @app.before_first_request1156        def foo():1157            time.sleep(0.2)1158            got.append(42)11591160        c = app.test_client()1161        def get_and_assert():1162            c.get("/")1163            assert got == [42]11641165        t = Thread(target=get_and_assert)1166        t.start()1167        get_and_assert()1168        t.join()1169        assert app.got_first_request11701171    def test_routing_redirect_debugging(self):1172        app = flask.Flask(__name__)1173        app.debug = True1174        @app.route('/foo/', methods=['GET', 'POST'])1175        def foo():1176            return 'success'1177        with app.test_client() as c:1178            try:1179                c.post('/foo', data={})1180            except AssertionError as e:1181                assert 'http://localhost/foo/' in str(e)1182                assert ('Make sure to directly send '1183                        'your POST-request to this URL') in str(e)1184            else:1185                assert False, 'Expected exception'11861187            rv = c.get('/foo', data={}, follow_redirects=True)1188            assert rv.data == b'success'11891190        app.debug = False1191        with app.test_client() as c:1192            rv = c.post('/foo', data={}, follow_redirects=True)1193            assert rv.data == b'success'11941195    def test_route_decorator_custom_endpoint(self):1196        app = flask.Flask(__name__)1197        app.debug = True11981199        @app.route('/foo/')1200        def foo():1201            return flask.request.endpoint12021203        @app.route('/bar/', endpoint='bar')1204        def for_bar():1205            return flask.request.endpoint12061207        @app.route('/bar/123', endpoint='123')1208        def for_bar_foo():1209            return flask.request.endpoint12101211        with app.test_request_context():1212            assert flask.url_for('foo') == '/foo/'1213            assert flask.url_for('bar') == '/bar/'1214            assert flask.url_for('123') == '/bar/123'12151216        c = app.test_client()1217        assert c.get('/foo/').data == b'foo'1218        assert c.get('/bar/').data == b'bar'1219        assert c.get('/bar/123').data == b'123'12201221    def test_preserve_only_once(self):1222        app = flask.Flask(__name__)1223        app.debug = True12241225        @app.route('/fail')1226        def fail_func():1227            1 // 012281229        c = app.test_client()1230        for x in range(3):1231            with pytest.raises(ZeroDivisionError):1232                c.get('/fail')12331234        assert flask._request_ctx_stack.top is not None1235        assert flask._app_ctx_stack.top is not None1236        # implicit appctx disappears too1237        flask._request_ctx_stack.top.pop()1238        assert flask._request_ctx_stack.top is None1239        assert flask._app_ctx_stack.top is None12401241    def test_preserve_remembers_exception(self):1242        app = flask.Flask(__name__)1243        app.debug = True1244        errors = []12451246        @app.route('/fail')1247        def fail_func():1248            1 // 012491250        @app.route('/success')1251        def success_func():1252            return 'Okay'12531254        @app.teardown_request1255        def teardown_handler(exc):1256            errors.append(exc)12571258        c = app.test_client()12591260        # After this failure we did not yet call the teardown handler1261        with pytest.raises(ZeroDivisionError):1262            c.get('/fail')1263        assert errors == []12641265        # But this request triggers it, and it's an error1266        c.get('/success')1267        assert len(errors) == 21268        assert isinstance(errors[0], ZeroDivisionError)12691270        # At this point another request does nothing.1271        c.get('/success')1272        assert len(errors) == 31273        assert errors[1] == None12741275    def test_get_method_on_g(self):1276        app = flask.Flask(__name__)1277        app.testing = True12781279        with app.app_context():1280            assert flask.g.get('x') == None1281            assert flask.g.get('x', 11) == 111282            flask.g.x = 421283            assert flask.g.get('x') == 421284            assert flask.g.x == 4212851286    def test_g_iteration_protocol(self):1287        app = flask.Flask(__name__)1288        app.testing = True12891290        with app.app_context():1291            flask.g.foo = 231292            flask.g.bar = 421293            assert 'foo' in flask.g1294            assert 'foos' not in flask.g1295            assert sorted(flask.g) == ['bar', 'foo']129612971298class TestSubdomain(object):12991300    def test_basic_support(self):1301        app = flask.Flask(__name__)1302        app.config['SERVER_NAME'] = 'localhost'1303        @app.route('/')1304        def normal_index():1305            return 'normal index'1306        @app.route('/', subdomain='test')1307        def test_index():1308            return 'test index'13091310        c = app.test_client()1311        rv = c.get('/', 'http://localhost/')1312        assert rv.data == b'normal index'13131314        rv = c.get('/', 'http://test.localhost/')1315        assert rv.data == b'test index'13161317    def test_subdomain_matching(self):1318        app = flask.Flask(__name__)1319        app.config['SERVER_NAME'] = 'localhost'1320        @app.route('/', subdomain='<user>')1321        def index(user):1322            return 'index for %s' % user13231324        c = app.test_client()1325        rv = c.get('/', 'http://mitsuhiko.localhost/')1326        assert rv.data == b'index for mitsuhiko'13271328    def test_subdomain_matching_with_ports(self):1329        app = flask.Flask(__name__)1330        app.config['SERVER_NAME'] = 'localhost:3000'1331        @app.route('/', subdomain='<user>')1332        def index(user):1333            return 'index for %s' % user13341335        c = app.test_client()1336        rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1337        assert rv.data == b'index for mitsuhiko'13381339    def test_multi_route_rules(self):1340        app = flask.Flask(__name__)13411342        @app.route('/')1343        @app.route('/<test>/')1344        def index(test='a'):1345            return test13461347        rv = app.test_client().open('/')1348        assert rv.data == b'a'1349        rv = app.test_client().open('/b/')1350        assert rv.data == b'b'13511352    def test_multi_route_class_views(self):1353        class View(object):1354            def __init__(self, app):1355                app.add_url_rule('/', 'index', self.index)1356                app.add_url_rule('/<test>/', 'index', self.index)13571358            def index(self, test='a'):1359                return test13601361        app = flask.Flask(__name__)1362        _ = View(app)1363        rv = app.test_client().open('/')1364        assert rv.data == b'a'1365        rv = app.test_client().open('/b/')1366        assert rv.data == b'b'