Skip to content
Myr

test_helpers.py

This file

Path

tests/test_helpers.py

909 lines · 31.6 KiB · Python

Last changed by

Merge pull request #2695 from pallets/backport-2691-json-encodingDavid Lordbefore adoptionb178e89

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    tests.helpers4    ~~~~~~~~~~~~~~~~~~~~~~~56    Various helpers.78    :copyright: (c) 2015 by Armin Ronacher.9    :license: BSD, see LICENSE for more details.10"""1112import pytest1314import os15import uuid16import datetime1718import flask19from logging import StreamHandler20from werkzeug.datastructures import Range21from werkzeug.exceptions import BadRequest, NotFound22from werkzeug.http import parse_cache_control_header, parse_options_header23from werkzeug.http import http_date2425from flask import json26from flask._compat import StringIO, text_type272829def has_encoding(name):30    try:31        import codecs32        codecs.lookup(name)33        return True34    except LookupError:35        return False363738class TestJSON(object):39    @pytest.mark.parametrize('value', (40        1, 't', True, False, None,41        [], [1, 2, 3],42        {}, {'foo': u'🐍'},43    ))44    @pytest.mark.parametrize('encoding', (45        'utf-8', 'utf-8-sig',46        'utf-16-le', 'utf-16-be', 'utf-16',47        'utf-32-le', 'utf-32-be', 'utf-32',48    ))49    def test_detect_encoding(self, value, encoding):50        data = json.dumps(value).encode(encoding)51        assert json.detect_encoding(data) == encoding52        assert json.loads(data) == value5354    def test_ignore_cached_json(self):55        app = flask.Flask(__name__)56        with app.test_request_context('/', method='POST', data='malformed',57                                      content_type='application/json'):58            assert flask.request.get_json(silent=True, cache=True) is None59            with pytest.raises(BadRequest):60                flask.request.get_json(silent=False, cache=False)6162    def test_post_empty_json_adds_exception_to_response_content_in_debug(self):63        app = flask.Flask(__name__)64        app.config['DEBUG'] = True65        @app.route('/json', methods=['POST'])66        def post_json():67            flask.request.get_json()68            return None69        c = app.test_client()70        rv = c.post('/json', data=None, content_type='application/json')71        assert rv.status_code == 40072        assert b'Failed to decode JSON object' in rv.data7374    def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self):75        app = flask.Flask(__name__)76        app.config['DEBUG'] = False77        @app.route('/json', methods=['POST'])78        def post_json():79            flask.request.get_json()80            return None81        c = app.test_client()82        rv = c.post('/json', data=None, content_type='application/json')83        assert rv.status_code == 40084        assert b'Failed to decode JSON object' not in rv.data8586    def test_json_bad_requests(self):87        app = flask.Flask(__name__)88        @app.route('/json', methods=['POST'])89        def return_json():90            return flask.jsonify(foo=text_type(flask.request.get_json()))91        c = app.test_client()92        rv = c.post('/json', data='malformed', content_type='application/json')93        assert rv.status_code == 4009495    def test_json_custom_mimetypes(self):96        app = flask.Flask(__name__)97        @app.route('/json', methods=['POST'])98        def return_json():99            return flask.request.get_json()100        c = app.test_client()101        rv = c.post('/json', data='"foo"', content_type='application/x+json')102        assert rv.data == b'foo'103104    def test_json_as_unicode(self):105        app = flask.Flask(__name__)106107        app.config['JSON_AS_ASCII'] = True108        with app.app_context():109            rv = flask.json.dumps(u'\N{SNOWMAN}')110            assert rv == '"\\u2603"'111112        app.config['JSON_AS_ASCII'] = False113        with app.app_context():114            rv = flask.json.dumps(u'\N{SNOWMAN}')115            assert rv == u'"\u2603"'116117    def test_json_dump_to_file(self):118        app = flask.Flask(__name__)119        test_data = {'name': 'Flask'}120        out = StringIO()121122        with app.app_context():123            flask.json.dump(test_data, out)124            out.seek(0)125            rv = flask.json.load(out)126            assert rv == test_data127128    @pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None])129    def test_jsonify_basic_types(self, test_value):130        """Test jsonify with basic types."""131        app = flask.Flask(__name__)132        c = app.test_client()133134        url = '/jsonify_basic_types'135        app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))136        rv = c.get(url)137        assert rv.mimetype == 'application/json'138        assert flask.json.loads(rv.data) == test_value139140    def test_jsonify_dicts(self):141        """Test jsonify with dicts and kwargs unpacking."""142        d = dict(143            a=0, b=23, c=3.14, d='t', e='Hi', f=True, g=False,144            h=['test list', 10, False],145            i={'test':'dict'}146        )147        app = flask.Flask(__name__)148        @app.route('/kw')149        def return_kwargs():150            return flask.jsonify(**d)151        @app.route('/dict')152        def return_dict():153            return flask.jsonify(d)154        c = app.test_client()155        for url in '/kw', '/dict':156            rv = c.get(url)157            assert rv.mimetype == 'application/json'158            assert flask.json.loads(rv.data) == d159160    def test_jsonify_arrays(self):161        """Test jsonify of lists and args unpacking."""162        l = [163            0, 42, 3.14, 't', 'hello', True, False,164            ['test list', 2, False],165            {'test':'dict'}166        ]167        app = flask.Flask(__name__)168        @app.route('/args_unpack')169        def return_args_unpack():170            return flask.jsonify(*l)171        @app.route('/array')172        def return_array():173            return flask.jsonify(l)174        c = app.test_client()175        for url in '/args_unpack', '/array':176            rv = c.get(url)177            assert rv.mimetype == 'application/json'178            assert flask.json.loads(rv.data) == l179180    def test_jsonify_date_types(self):181        """Test jsonify with datetime.date and datetime.datetime types."""182        test_dates = (183            datetime.datetime(1973, 3, 11, 6, 30, 45),184            datetime.date(1975, 1, 5)185        )186        app = flask.Flask(__name__)187        c = app.test_client()188189        for i, d in enumerate(test_dates):190            url = '/datetest{0}'.format(i)191            app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))192            rv = c.get(url)193            assert rv.mimetype == 'application/json'194            assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())195196    def test_jsonify_uuid_types(self):197        """Test jsonify with uuid.UUID types"""198199        test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)200        app = flask.Flask(__name__)201        url = '/uuid_test'202        app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))203204        c = app.test_client()205        rv = c.get(url)206207        rv_x = flask.json.loads(rv.data)['x']208        assert rv_x == str(test_uuid)209        rv_uuid = uuid.UUID(rv_x)210        assert rv_uuid == test_uuid211212    def test_json_attr(self):213        app = flask.Flask(__name__)214        @app.route('/add', methods=['POST'])215        def add():216            json = flask.request.get_json()217            return text_type(json['a'] + json['b'])218        c = app.test_client()219        rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),220                            content_type='application/json')221        assert rv.data == b'3'222223    def test_template_escaping(self):224        app = flask.Flask(__name__)225        render = flask.render_template_string226        with app.test_request_context():227            rv = flask.json.htmlsafe_dumps('</script>')228            assert rv == u'"\\u003c/script\\u003e"'229            assert type(rv) == text_type230            rv = render('{{ "</script>"|tojson }}')231            assert rv == '"\\u003c/script\\u003e"'232            rv = render('{{ "<\0/script>"|tojson }}')233            assert rv == '"\\u003c\\u0000/script\\u003e"'234            rv = render('{{ "<!--<script>"|tojson }}')235            assert rv == '"\\u003c!--\\u003cscript\\u003e"'236            rv = render('{{ "&"|tojson }}')237            assert rv == '"\\u0026"'238            rv = render('{{ "\'"|tojson }}')239            assert rv == '"\\u0027"'240            rv = render("<a ng-data='{{ data|tojson }}'></a>",241                data={'x': ["foo", "bar", "baz'"]})242            assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'243244    def test_json_customization(self):245        class X(object):246            def __init__(self, val):247                self.val = val248        class MyEncoder(flask.json.JSONEncoder):249            def default(self, o):250                if isinstance(o, X):251                    return '<%d>' % o.val252                return flask.json.JSONEncoder.default(self, o)253        class MyDecoder(flask.json.JSONDecoder):254            def __init__(self, *args, **kwargs):255                kwargs.setdefault('object_hook', self.object_hook)256                flask.json.JSONDecoder.__init__(self, *args, **kwargs)257            def object_hook(self, obj):258                if len(obj) == 1 and '_foo' in obj:259                    return X(obj['_foo'])260                return obj261        app = flask.Flask(__name__)262        app.testing = True263        app.json_encoder = MyEncoder264        app.json_decoder = MyDecoder265        @app.route('/', methods=['POST'])266        def index():267            return flask.json.dumps(flask.request.get_json()['x'])268        c = app.test_client()269        rv = c.post('/', data=flask.json.dumps({270            'x': {'_foo': 42}271        }), content_type='application/json')272        assert rv.data == b'"<42>"'273274    def test_modified_url_encoding(self):275        class ModifiedRequest(flask.Request):276            url_charset = 'euc-kr'277        app = flask.Flask(__name__)278        app.testing = True279        app.request_class = ModifiedRequest280        app.url_map.charset = 'euc-kr'281282        @app.route('/')283        def index():284            return flask.request.args['foo']285286        rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))287        assert rv.status_code == 200288        assert rv.data == u'정상처리'.encode('utf-8')289290    if not has_encoding('euc-kr'):291        test_modified_url_encoding = None292293    def test_json_key_sorting(self):294        app = flask.Flask(__name__)295        app.testing = True296        assert app.config['JSON_SORT_KEYS'] == True297        d = dict.fromkeys(range(20), 'foo')298299        @app.route('/')300        def index():301            return flask.jsonify(values=d)302303        c = app.test_client()304        rv = c.get('/')305        lines = [x.strip() for x in rv.data.strip().decode('utf-8').splitlines()]306        sorted_by_str = [307            '{',308            '"values": {',309            '"0": "foo",',310            '"1": "foo",',311            '"10": "foo",',312            '"11": "foo",',313            '"12": "foo",',314            '"13": "foo",',315            '"14": "foo",',316            '"15": "foo",',317            '"16": "foo",',318            '"17": "foo",',319            '"18": "foo",',320            '"19": "foo",',321            '"2": "foo",',322            '"3": "foo",',323            '"4": "foo",',324            '"5": "foo",',325            '"6": "foo",',326            '"7": "foo",',327            '"8": "foo",',328            '"9": "foo"',329            '}',330            '}'331        ]332        sorted_by_int = [333            '{',334            '"values": {',335            '"0": "foo",',336            '"1": "foo",',337            '"2": "foo",',338            '"3": "foo",',339            '"4": "foo",',340            '"5": "foo",',341            '"6": "foo",',342            '"7": "foo",',343            '"8": "foo",',344            '"9": "foo",',345            '"10": "foo",',346            '"11": "foo",',347            '"12": "foo",',348            '"13": "foo",',349            '"14": "foo",',350            '"15": "foo",',351            '"16": "foo",',352            '"17": "foo",',353            '"18": "foo",',354            '"19": "foo"',355            '}',356            '}'357        ]358359        try:360            assert lines == sorted_by_int361        except AssertionError:362            assert lines == sorted_by_str363364class TestSendfile(object):365366    def test_send_file_regular(self):367        app = flask.Flask(__name__)368        with app.test_request_context():369            rv = flask.send_file('static/index.html')370            assert rv.direct_passthrough371            assert rv.mimetype == 'text/html'372            with app.open_resource('static/index.html') as f:373                rv.direct_passthrough = False374                assert rv.data == f.read()375            rv.close()376377    def test_send_file_xsendfile(self, catch_deprecation_warnings):378        app = flask.Flask(__name__)379        app.use_x_sendfile = True380        with app.test_request_context():381            rv = flask.send_file('static/index.html')382            assert rv.direct_passthrough383            assert 'x-sendfile' in rv.headers384            assert rv.headers['x-sendfile'] == \385                os.path.join(app.root_path, 'static/index.html')386            assert rv.mimetype == 'text/html'387            rv.close()388389    def test_send_file_last_modified(self):390        app = flask.Flask(__name__)391        last_modified = datetime.datetime(1999, 1, 1)392393        @app.route('/')394        def index():395            return flask.send_file(StringIO("party like it's"),396                                   last_modified=last_modified,397                                   mimetype='text/plain')398399        c = app.test_client()400        rv = c.get('/')401        assert rv.last_modified == last_modified402403    def test_send_file_object_without_mimetype(self):404        app = flask.Flask(__name__)405406        with app.test_request_context():407            with pytest.raises(ValueError) as excinfo:408                flask.send_file(StringIO("LOL"))409            assert 'Unable to infer MIME-type' in str(excinfo)410            assert 'no filename is available' in str(excinfo)411412        with app.test_request_context():413            flask.send_file(StringIO("LOL"), attachment_filename='filename')414415    def test_send_file_object(self):416        app = flask.Flask(__name__)417418        with app.test_request_context():419            with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:420                rv = flask.send_file(f, mimetype='text/html')421                rv.direct_passthrough = False422                with app.open_resource('static/index.html') as f:423                    assert rv.data == f.read()424                assert rv.mimetype == 'text/html'425                rv.close()426427        app.use_x_sendfile = True428429        with app.test_request_context():430            with open(os.path.join(app.root_path, 'static/index.html')) as f:431                rv = flask.send_file(f, mimetype='text/html')432                assert rv.mimetype == 'text/html'433                assert 'x-sendfile' not in rv.headers434                rv.close()435436        app.use_x_sendfile = False437        with app.test_request_context():438            f = StringIO('Test')439            rv = flask.send_file(f, mimetype='application/octet-stream')440            rv.direct_passthrough = False441            assert rv.data == b'Test'442            assert rv.mimetype == 'application/octet-stream'443            rv.close()444445            class PyStringIO(object):446                def __init__(self, *args, **kwargs):447                    self._io = StringIO(*args, **kwargs)448                def __getattr__(self, name):449                    return getattr(self._io, name)450            f = PyStringIO('Test')451            f.name = 'test.txt'452            rv = flask.send_file(f, attachment_filename=f.name)453            rv.direct_passthrough = False454            assert rv.data == b'Test'455            assert rv.mimetype == 'text/plain'456            rv.close()457458            f = StringIO('Test')459            rv = flask.send_file(f, mimetype='text/plain')460            rv.direct_passthrough = False461            assert rv.data == b'Test'462            assert rv.mimetype == 'text/plain'463            rv.close()464465        app.use_x_sendfile = True466467        with app.test_request_context():468            f = StringIO('Test')469            rv = flask.send_file(f, mimetype='text/html')470            assert 'x-sendfile' not in rv.headers471            rv.close()472473    @pytest.mark.skipif(474        not callable(getattr(Range, 'to_content_range_header', None)),475        reason="not implemented within werkzeug"476    )477    def test_send_file_range_request(self):478        app = flask.Flask(__name__)479480        @app.route('/')481        def index():482            return flask.send_file('static/index.html', conditional=True)483484        c = app.test_client()485486        rv = c.get('/', headers={'Range': 'bytes=4-15'})487        assert rv.status_code == 206488        with app.open_resource('static/index.html') as f:489            assert rv.data == f.read()[4:16]490        rv.close()491492        rv = c.get('/', headers={'Range': 'bytes=4-'})493        assert rv.status_code == 206494        with app.open_resource('static/index.html') as f:495            assert rv.data == f.read()[4:]496        rv.close()497498        rv = c.get('/', headers={'Range': 'bytes=4-1000'})499        assert rv.status_code == 206500        with app.open_resource('static/index.html') as f:501            assert rv.data == f.read()[4:]502        rv.close()503504        rv = c.get('/', headers={'Range': 'bytes=-10'})505        assert rv.status_code == 206506        with app.open_resource('static/index.html') as f:507            assert rv.data == f.read()[-10:]508        rv.close()509510        rv = c.get('/', headers={'Range': 'bytes=1000-'})511        assert rv.status_code == 416512        rv.close()513514        rv = c.get('/', headers={'Range': 'bytes=-'})515        assert rv.status_code == 416516        rv.close()517518        rv = c.get('/', headers={'Range': 'somethingsomething'})519        assert rv.status_code == 416520        rv.close()521522        last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime(523            os.path.join(app.root_path, 'static/index.html'))).replace(524            microsecond=0)525526        rv = c.get('/', headers={'Range': 'bytes=4-15',527                                 'If-Range': http_date(last_modified)})528        assert rv.status_code == 206529        rv.close()530531        rv = c.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(532            datetime.datetime(1999, 1, 1))})533        assert rv.status_code == 200534        rv.close()535536    @pytest.mark.skipif(537        not callable(getattr(Range, 'to_content_range_header', None)),538        reason="not implemented within werkzeug"539    )540    def test_send_file_range_request_xsendfile_invalid(self):541        # https://github.com/pallets/flask/issues/2526542        app = flask.Flask(__name__)543        app.use_x_sendfile = True544545        @app.route('/')546        def index():547            return flask.send_file('static/index.html', conditional=True)548549        c = app.test_client()550551        rv = c.get('/', headers={'Range': 'bytes=1000-'})552        assert rv.status_code == 416553        rv.close()554555    def test_attachment(self):556        app = flask.Flask(__name__)557        with app.test_request_context():558            with open(os.path.join(app.root_path, 'static/index.html')) as f:559                rv = flask.send_file(f, as_attachment=True,560                                     attachment_filename='index.html')561                value, options = \562                    parse_options_header(rv.headers['Content-Disposition'])563                assert value == 'attachment'564                rv.close()565566        with app.test_request_context():567            assert options['filename'] == 'index.html'568            rv = flask.send_file('static/index.html', as_attachment=True)569            value, options = parse_options_header(rv.headers['Content-Disposition'])570            assert value == 'attachment'571            assert options['filename'] == 'index.html'572            rv.close()573574        with app.test_request_context():575            rv = flask.send_file(StringIO('Test'), as_attachment=True,576                                 attachment_filename='index.txt',577                                 add_etags=False)578            assert rv.mimetype == 'text/plain'579            value, options = parse_options_header(rv.headers['Content-Disposition'])580            assert value == 'attachment'581            assert options['filename'] == 'index.txt'582            rv.close()583584    def test_static_file(self):585        app = flask.Flask(__name__)586        # default cache timeout is 12 hours587        with app.test_request_context():588            # Test with static file handler.589            rv = app.send_static_file('index.html')590            cc = parse_cache_control_header(rv.headers['Cache-Control'])591            assert cc.max_age == 12 * 60 * 60592            rv.close()593            # Test again with direct use of send_file utility.594            rv = flask.send_file('static/index.html')595            cc = parse_cache_control_header(rv.headers['Cache-Control'])596            assert cc.max_age == 12 * 60 * 60597            rv.close()598        app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600599        with app.test_request_context():600            # Test with static file handler.601            rv = app.send_static_file('index.html')602            cc = parse_cache_control_header(rv.headers['Cache-Control'])603            assert cc.max_age == 3600604            rv.close()605            # Test again with direct use of send_file utility.606            rv = flask.send_file('static/index.html')607            cc = parse_cache_control_header(rv.headers['Cache-Control'])608            assert cc.max_age == 3600609            rv.close()610        class StaticFileApp(flask.Flask):611            def get_send_file_max_age(self, filename):612                return 10613        app = StaticFileApp(__name__)614        with app.test_request_context():615            # Test with static file handler.616            rv = app.send_static_file('index.html')617            cc = parse_cache_control_header(rv.headers['Cache-Control'])618            assert cc.max_age == 10619            rv.close()620            # Test again with direct use of send_file utility.621            rv = flask.send_file('static/index.html')622            cc = parse_cache_control_header(rv.headers['Cache-Control'])623            assert cc.max_age == 10624            rv.close()625626    def test_send_from_directory(self):627        app = flask.Flask(__name__)628        app.testing = True629        app.root_path = os.path.join(os.path.dirname(__file__),630                                     'test_apps', 'subdomaintestmodule')631        with app.test_request_context():632            rv = flask.send_from_directory('static', 'hello.txt')633            rv.direct_passthrough = False634            assert rv.data.strip() == b'Hello Subdomain'635            rv.close()636637    def test_send_from_directory_bad_request(self):638        app = flask.Flask(__name__)639        app.testing = True640        app.root_path = os.path.join(os.path.dirname(__file__),641                                     'test_apps', 'subdomaintestmodule')642        with app.test_request_context():643            with pytest.raises(BadRequest):644                flask.send_from_directory('static', 'bad\x00')645646class TestLogging(object):647648    def test_logger_cache(self):649        app = flask.Flask(__name__)650        logger1 = app.logger651        assert app.logger is logger1652        assert logger1.name == __name__653        app.logger_name = __name__ + '/test_logger_cache'654        assert app.logger is not logger1655656    def test_debug_log(self, capsys):657        app = flask.Flask(__name__)658        app.debug = True659660        @app.route('/')661        def index():662            app.logger.warning('the standard library is dead')663            app.logger.debug('this is a debug statement')664            return ''665666        @app.route('/exc')667        def exc():668            1 // 0669670        with app.test_client() as c:671            c.get('/')672            out, err = capsys.readouterr()673            assert 'WARNING in test_helpers [' in err674            assert os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in err675            assert 'the standard library is dead' in err676            assert 'this is a debug statement' in err677678            with pytest.raises(ZeroDivisionError):679                c.get('/exc')680681    def test_debug_log_override(self):682        app = flask.Flask(__name__)683        app.debug = True684        app.logger_name = 'flask_tests/test_debug_log_override'685        app.logger.level = 10686        assert app.logger.level == 10687688    def test_exception_logging(self):689        out = StringIO()690        app = flask.Flask(__name__)691        app.config['LOGGER_HANDLER_POLICY'] = 'never'692        app.logger_name = 'flask_tests/test_exception_logging'693        app.logger.addHandler(StreamHandler(out))694695        @app.route('/')696        def index():697            1 // 0698699        rv = app.test_client().get('/')700        assert rv.status_code == 500701        assert b'Internal Server Error' in rv.data702703        err = out.getvalue()704        assert 'Exception on / [GET]' in err705        assert 'Traceback (most recent call last):' in err706        assert '1 // 0' in err707        assert 'ZeroDivisionError:' in err708709    def test_processor_exceptions(self):710        app = flask.Flask(__name__)711        app.config['LOGGER_HANDLER_POLICY'] = 'never'712        @app.before_request713        def before_request():714            if trigger == 'before':715                1 // 0716        @app.after_request717        def after_request(response):718            if trigger == 'after':719                1 // 0720            return response721        @app.route('/')722        def index():723            return 'Foo'724        @app.errorhandler(500)725        def internal_server_error(e):726            return 'Hello Server Error', 500727        for trigger in 'before', 'after':728            rv = app.test_client().get('/')729            assert rv.status_code == 500730            assert rv.data == b'Hello Server Error'731732    def test_url_for_with_anchor(self):733        app = flask.Flask(__name__)734        @app.route('/')735        def index():736            return '42'737        with app.test_request_context():738            assert flask.url_for('index', _anchor='x y') == '/#x%20y'739740    def test_url_for_with_scheme(self):741        app = flask.Flask(__name__)742        @app.route('/')743        def index():744            return '42'745        with app.test_request_context():746            assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'747748    def test_url_for_with_scheme_not_external(self):749        app = flask.Flask(__name__)750        @app.route('/')751        def index():752            return '42'753        with app.test_request_context():754            pytest.raises(ValueError,755                               flask.url_for,756                               'index',757                               _scheme='https')758759    def test_url_for_with_alternating_schemes(self):760        app = flask.Flask(__name__)761        @app.route('/')762        def index():763            return '42'764        with app.test_request_context():765            assert flask.url_for('index', _external=True) == 'http://localhost/'766            assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'767            assert flask.url_for('index', _external=True) == 'http://localhost/'768769    def test_url_with_method(self):770        from flask.views import MethodView771        app = flask.Flask(__name__)772        class MyView(MethodView):773            def get(self, id=None):774                if id is None:775                    return 'List'776                return 'Get %d' % id777            def post(self):778                return 'Create'779        myview = MyView.as_view('myview')780        app.add_url_rule('/myview/', methods=['GET'],781                         view_func=myview)782        app.add_url_rule('/myview/<int:id>', methods=['GET'],783                         view_func=myview)784        app.add_url_rule('/myview/create', methods=['POST'],785                         view_func=myview)786787        with app.test_request_context():788            assert flask.url_for('myview', _method='GET') == '/myview/'789            assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'790            assert flask.url_for('myview', _method='POST') == '/myview/create'791792793class TestNoImports(object):794    """Test Flasks are created without import.795796    Avoiding ``__import__`` helps create Flask instances where there are errors797    at import time.  Those runtime errors will be apparent to the user soon798    enough, but tools which build Flask instances meta-programmatically benefit799    from a Flask which does not ``__import__``.  Instead of importing to800    retrieve file paths or metadata on a module or package, use the pkgutil and801    imp modules in the Python standard library.802    """803804    def test_name_with_import_error(self, modules_tmpdir):805        modules_tmpdir.join('importerror.py').write('raise NotImplementedError()')806        try:807            flask.Flask('importerror')808        except NotImplementedError:809            assert False, 'Flask(import_name) is importing import_name.'810811812class TestStreaming(object):813814    def test_streaming_with_context(self):815        app = flask.Flask(__name__)816        app.testing = True817        @app.route('/')818        def index():819            def generate():820                yield 'Hello '821                yield flask.request.args['name']822                yield '!'823            return flask.Response(flask.stream_with_context(generate()))824        c = app.test_client()825        rv = c.get('/?name=World')826        assert rv.data == b'Hello World!'827828    def test_streaming_with_context_as_decorator(self):829        app = flask.Flask(__name__)830        app.testing = True831        @app.route('/')832        def index():833            @flask.stream_with_context834            def generate(hello):835                yield hello836                yield flask.request.args['name']837                yield '!'838            return flask.Response(generate('Hello '))839        c = app.test_client()840        rv = c.get('/?name=World')841        assert rv.data == b'Hello World!'842843    def test_streaming_with_context_and_custom_close(self):844        app = flask.Flask(__name__)845        app.testing = True846        called = []847        class Wrapper(object):848            def __init__(self, gen):849                self._gen = gen850            def __iter__(self):851                return self852            def close(self):853                called.append(42)854            def __next__(self):855                return next(self._gen)856            next = __next__857        @app.route('/')858        def index():859            def generate():860                yield 'Hello '861                yield flask.request.args['name']862                yield '!'863            return flask.Response(flask.stream_with_context(864                Wrapper(generate())))865        c = app.test_client()866        rv = c.get('/?name=World')867        assert rv.data == b'Hello World!'868        assert called == [42]869870871class TestSafeJoin(object):872    def test_safe_join(self):873        # Valid combinations of *args and expected joined paths.874        passing = (875            (('a/b/c',), 'a/b/c'),876            (('/', 'a/', 'b/', 'c/'), '/a/b/c'),877            (('a', 'b', 'c'), 'a/b/c'),878            (('/a', 'b/c'), '/a/b/c'),879            (('a/b', 'X/../c'), 'a/b/c'),880            (('/a/b', 'c/X/..'), '/a/b/c'),881            # If last path is '' add a slash882            (('/a/b/c', ''), '/a/b/c/'),883            # Preserve dot slash884            (('/a/b/c', './'), '/a/b/c/.'),885            (('a/b/c', 'X/..'), 'a/b/c/.'),886            # Base directory is always considered safe887            (('../', 'a/b/c'), '../a/b/c'),888            (('/..', ), '/..'),889        )890891        for args, expected in passing:892            assert flask.safe_join(*args) == expected893894    def test_safe_join_exceptions(self):895        # Should raise werkzeug.exceptions.NotFound on unsafe joins.896        failing = (897            # path.isabs and ``..'' checks898            ('/a', 'b', '/c'),899            ('/a', '../b/c'),900            ('/a', '..', 'b/c'),901            # Boundaries violations after path normalization902            ('/a', 'b/../b/../../c'),903            ('/a', 'b', 'c/../..'),904            ('/a', 'b/../../c'),905        )906907        for args in failing:908            with pytest.raises(NotFound):909                print(flask.safe_join(*args))