Merge branch 'master' into routes-command

This commit is contained in:
David Lord 2017-04-25 13:13:10 -07:00
commit 717e45ab15
No known key found for this signature in database
GPG key ID: 7A1C87E3F5BC42A8
119 changed files with 1977 additions and 1019 deletions

View file

@ -0,0 +1,7 @@
from __future__ import absolute_import, print_function
from flask import Flask
raise ImportError()
testapp = Flask('testapp')

View file

@ -50,7 +50,7 @@ def test_options_on_multiple_rules():
assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']
def test_options_handling_disabled():
def test_provide_automatic_options_attr():
app = flask.Flask(__name__)
def index():
@ -70,6 +70,54 @@ def test_options_handling_disabled():
assert sorted(rv.allow) == ['OPTIONS']
def test_provide_automatic_options_kwarg():
app = flask.Flask(__name__)
def index():
return flask.request.method
def more():
return flask.request.method
app.add_url_rule('/', view_func=index, provide_automatic_options=False)
app.add_url_rule(
'/more', view_func=more, methods=['GET', 'POST'],
provide_automatic_options=False
)
c = app.test_client()
assert c.get('/').data == b'GET'
rv = c.post('/')
assert rv.status_code == 405
assert sorted(rv.allow) == ['GET', 'HEAD']
# Older versions of Werkzeug.test.Client don't have an options method
if hasattr(c, 'options'):
rv = c.options('/')
else:
rv = c.open('/', method='OPTIONS')
assert rv.status_code == 405
rv = c.head('/')
assert rv.status_code == 200
assert not rv.data # head truncates
assert c.post('/more').data == b'POST'
assert c.get('/more').data == b'GET'
rv = c.delete('/more')
assert rv.status_code == 405
assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']
if hasattr(c, 'options'):
rv = c.options('/more')
else:
rv = c.open('/more', method='OPTIONS')
assert rv.status_code == 405
def test_request_dispatching():
app = flask.Flask(__name__)
@ -333,7 +381,7 @@ def test_session_expiration():
client = app.test_client()
rv = client.get('/')
assert 'set-cookie' in rv.headers
match = re.search(r'\bexpires=([^;]+)(?i)', rv.headers['set-cookie'])
match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])
expires = parse_date(match.group())
expected = datetime.utcnow() + app.permanent_session_lifetime
assert expires.year == expected.year
@ -768,6 +816,46 @@ def test_error_handling():
assert b'forbidden' == rv.data
def test_error_handling_processing():
app = flask.Flask(__name__)
app.config['LOGGER_HANDLER_POLICY'] = 'never'
@app.errorhandler(500)
def internal_server_error(e):
return 'internal server error', 500
@app.route('/')
def broken_func():
1 // 0
@app.after_request
def after_request(resp):
resp.mimetype = 'text/x-special'
return resp
with app.test_client() as c:
resp = c.get('/')
assert resp.mimetype == 'text/x-special'
assert resp.data == b'internal server error'
def test_baseexception_error_handling():
app = flask.Flask(__name__)
app.config['LOGGER_HANDLER_POLICY'] = 'never'
@app.route('/')
def broken_func():
raise KeyboardInterrupt()
with app.test_client() as c:
with pytest.raises(KeyboardInterrupt):
c.get('/')
ctx = flask._request_ctx_stack.top
assert ctx.preserved
assert type(ctx._preserved_exc) is KeyboardInterrupt
def test_before_request_and_routing_errors():
app = flask.Flask(__name__)
@ -887,64 +975,129 @@ def test_enctype_debug_helper():
assert 'This was submitted: "index.txt"' in str(e.value)
def test_response_creation():
def test_response_types():
app = flask.Flask(__name__)
app.testing = True
@app.route('/unicode')
def from_unicode():
@app.route('/text')
def from_text():
return u'Hällo Wörld'
@app.route('/string')
def from_string():
@app.route('/bytes')
def from_bytes():
return u'Hällo Wörld'.encode('utf-8')
@app.route('/args')
def from_tuple():
@app.route('/full_tuple')
def from_full_tuple():
return 'Meh', 400, {
'X-Foo': 'Testing',
'Content-Type': 'text/plain; charset=utf-8'
}
@app.route('/two_args')
def from_two_args_tuple():
@app.route('/text_headers')
def from_text_headers():
return 'Hello', {
'X-Foo': 'Test',
'Content-Type': 'text/plain; charset=utf-8'
}
@app.route('/args_status')
def from_status_tuple():
@app.route('/text_status')
def from_text_status():
return 'Hi, status!', 400
@app.route('/args_header')
def from_response_instance_status_tuple():
return flask.Response('Hello world', 404), {
@app.route('/response_headers')
def from_response_headers():
return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {
"X-Foo": "Bar",
"X-Bar": "Foo"
}
@app.route('/response_status')
def from_response_status():
return app.response_class('Hello world', 400), 500
@app.route('/wsgi')
def from_wsgi():
return NotFound()
c = app.test_client()
assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8')
assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8')
rv = c.get('/args')
assert c.get('/text').data == u'Hällo Wörld'.encode('utf-8')
assert c.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')
rv = c.get('/full_tuple')
assert rv.data == b'Meh'
assert rv.headers['X-Foo'] == 'Testing'
assert rv.status_code == 400
assert rv.mimetype == 'text/plain'
rv2 = c.get('/two_args')
assert rv2.data == b'Hello'
assert rv2.headers['X-Foo'] == 'Test'
assert rv2.status_code == 200
assert rv2.mimetype == 'text/plain'
rv3 = c.get('/args_status')
assert rv3.data == b'Hi, status!'
assert rv3.status_code == 400
assert rv3.mimetype == 'text/html'
rv4 = c.get('/args_header')
assert rv4.data == b'Hello world'
assert rv4.headers['X-Foo'] == 'Bar'
assert rv4.headers['X-Bar'] == 'Foo'
assert rv4.status_code == 404
rv = c.get('/text_headers')
assert rv.data == b'Hello'
assert rv.headers['X-Foo'] == 'Test'
assert rv.status_code == 200
assert rv.mimetype == 'text/plain'
rv = c.get('/text_status')
assert rv.data == b'Hi, status!'
assert rv.status_code == 400
assert rv.mimetype == 'text/html'
rv = c.get('/response_headers')
assert rv.data == b'Hello world'
assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']
assert rv.headers['X-Bar'] == 'Foo'
assert rv.status_code == 404
rv = c.get('/response_status')
assert rv.data == b'Hello world'
assert rv.status_code == 500
rv = c.get('/wsgi')
assert b'Not Found' in rv.data
assert rv.status_code == 404
def test_response_type_errors():
app = flask.Flask(__name__)
app.testing = True
@app.route('/none')
def from_none():
pass
@app.route('/small_tuple')
def from_small_tuple():
return 'Hello',
@app.route('/large_tuple')
def from_large_tuple():
return 'Hello', 234, {'X-Foo': 'Bar'}, '???'
@app.route('/bad_type')
def from_bad_type():
return True
@app.route('/bad_wsgi')
def from_bad_wsgi():
return lambda: None
c = app.test_client()
with pytest.raises(TypeError) as e:
c.get('/none')
assert 'returned None' in str(e)
with pytest.raises(TypeError) as e:
c.get('/small_tuple')
assert 'tuple must have the form' in str(e)
pytest.raises(TypeError, c.get, '/large_tuple')
with pytest.raises(TypeError) as e:
c.get('/bad_type')
assert 'it was a bool' in str(e)
pytest.raises(TypeError, c.get, '/bad_wsgi')
def test_make_response():
@ -972,7 +1125,7 @@ def test_make_response_with_response_instance():
rv = flask.make_response(
flask.jsonify({'msg': 'W00t'}), 400)
assert rv.status_code == 400
assert rv.data == b'{\n "msg": "W00t"\n}\n'
assert rv.data == b'{"msg":"W00t"}\n'
assert rv.mimetype == 'application/json'
rv = flask.make_response(
@ -1091,6 +1244,23 @@ def test_build_error_handler_reraise():
pytest.raises(BuildError, flask.url_for, 'not.existing')
def test_url_for_passes_special_values_to_build_error_handler():
app = flask.Flask(__name__)
@app.url_build_error_handlers.append
def handler(error, endpoint, values):
assert values == {
'_external': False,
'_anchor': None,
'_method': None,
'_scheme': None,
}
return 'handled'
with app.test_request_context():
flask.url_for('/')
def test_custom_converters():
from werkzeug.routing import BaseConverter
@ -1148,20 +1318,23 @@ def test_static_url_path():
assert flask.url_for('static', filename='index.html') == '/foo/index.html'
def test_none_response():
app = flask.Flask(__name__)
app.testing = True
@app.route('/')
def test():
return None
try:
app.test_client().get('/')
except ValueError as e:
assert str(e) == 'View function did not return a response'
pass
else:
assert "Expected ValueError"
def test_static_route_with_host_matching():
app = flask.Flask(__name__, host_matching=True, static_host='example.com')
c = app.test_client()
rv = c.get('http://example.com/static/index.html')
assert rv.status_code == 200
rv.close()
with app.test_request_context():
rv = flask.url_for('static', filename='index.html', _external=True)
assert rv == 'http://example.com/static/index.html'
# Providing static_host without host_matching=True should error.
with pytest.raises(Exception):
flask.Flask(__name__, static_host='example.com')
# Providing host_matching=True with static_folder but without static_host should error.
with pytest.raises(Exception):
flask.Flask(__name__, host_matching=True)
# Providing host_matching=True without static_host but with static_folder=None should not error.
flask.Flask(__name__, host_matching=True, static_folder=None)
def test_request_locals():
@ -1268,8 +1441,6 @@ def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,
monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)
app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions
app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)
# make sure werkzeug always passes errors through
assert rv['passthrough_errors']
def test_max_content_length():
@ -1660,3 +1831,20 @@ def test_run_server_port(monkeypatch):
hostname, port = 'localhost', 8000
app.run(hostname, port, debug=True)
assert rv['result'] == 'running on %s:%s ...' % (hostname, port)
@pytest.mark.parametrize('host,port,expect_host,expect_port', (
(None, None, 'pocoo.org', 8080),
('localhost', None, 'localhost', 8080),
(None, 80, 'pocoo.org', 80),
('localhost', 80, 'localhost', 80),
))
def test_run_from_config(monkeypatch, host, port, expect_host, expect_port):
def run_simple_mock(hostname, port, *args, **kwargs):
assert hostname == expect_host
assert port == expect_port
monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)
app = flask.Flask(__name__)
app.config['SERVER_NAME'] = 'pocoo.org:8080'
app.run(host, port)

View file

@ -355,6 +355,25 @@ def test_route_decorator_custom_endpoint_with_dots():
rv = c.get('/py/bar/123')
assert rv.status_code == 404
def test_endpoint_decorator():
from werkzeug.routing import Rule
app = flask.Flask(__name__)
app.url_map.add(Rule('/foo', endpoint='bar'))
bp = flask.Blueprint('bp', __name__)
@bp.endpoint('bar')
def foobar():
return flask.request.endpoint
app.register_blueprint(bp, url_prefix='/bp_prefix')
c = app.test_client()
assert c.get('/foo').data == b'bar'
assert c.get('/bp_prefix/bar').status_code == 404
def test_template_filter():
bp = flask.Blueprint('bp', __name__)
@bp.app_template_filter()

View file

@ -22,7 +22,7 @@ from flask import Flask, current_app
from flask.cli import cli, AppGroup, FlaskGroup, NoAppException, ScriptInfo, \
find_best_app, locate_app, with_appcontext, prepare_exec_for_file, \
find_default_import_path
find_default_import_path, get_version
@pytest.fixture
@ -37,24 +37,27 @@ def test_cli_name(test_apps):
def test_find_best_app(test_apps):
"""Test of find_best_app."""
class mod:
"""Test if `find_best_app` behaves as expected with different combinations of input."""
class Module:
app = Flask('appname')
assert find_best_app(mod) == mod.app
assert find_best_app(Module) == Module.app
class mod:
class Module:
application = Flask('appname')
assert find_best_app(mod) == mod.application
assert find_best_app(Module) == Module.application
class mod:
class Module:
myapp = Flask('appname')
assert find_best_app(mod) == mod.myapp
assert find_best_app(Module) == Module.myapp
class mod:
myapp = Flask('appname')
class Module:
pass
pytest.raises(NoAppException, find_best_app, Module)
class Module:
myapp1 = Flask('appname1')
myapp2 = Flask('appname2')
pytest.raises(NoAppException, find_best_app, mod)
pytest.raises(NoAppException, find_best_app, Module)
def test_prepare_exec_for_file(test_apps):
@ -82,7 +85,10 @@ def test_locate_app(test_apps):
assert locate_app("cliapp.app").name == "testapp"
assert locate_app("cliapp.app:testapp").name == "testapp"
assert locate_app("cliapp.multiapp:app1").name == "app1"
pytest.raises(NoAppException, locate_app, "notanpp.py")
pytest.raises(NoAppException, locate_app, "cliapp/app")
pytest.raises(RuntimeError, locate_app, "cliapp.app:notanapp")
pytest.raises(NoAppException, locate_app, "cliapp.importerrorapp")
def test_find_default_import_path(test_apps, monkeypatch, tmpdir):
@ -98,6 +104,21 @@ def test_find_default_import_path(test_apps, monkeypatch, tmpdir):
assert find_default_import_path() == expect_rv
def test_get_version(test_apps, capsys):
"""Test of get_version."""
from flask import __version__ as flask_ver
from sys import version as py_ver
class MockCtx(object):
resilient_parsing = False
color = None
def exit(self): return
ctx = MockCtx()
get_version(ctx, None, "test")
out, err = capsys.readouterr()
assert flask_ver in out
assert py_ver in out
def test_scriptinfo(test_apps):
"""Test of ScriptInfo."""
obj = ScriptInfo(app_import_path="cliapp.app:testapp")
@ -174,6 +195,23 @@ def test_flaskgroup(runner):
assert result.output == 'flaskgroup\n'
def test_print_exceptions():
"""Print the stacktrace if the CLI."""
def create_app(info):
raise Exception("oh no")
return Flask("flaskgroup")
@click.group(cls=FlaskGroup, create_app=create_app)
def cli(**params):
pass
runner = CliRunner()
result = runner.invoke(cli, ['--help'])
assert result.exit_code == 0
assert 'Exception: oh no' in result.output
assert 'Traceback' in result.output
class TestRoutes:
def test_no_route(self, runner, monkeypatch):
monkeypatch.setitem(os.environ, 'FLASK_APP', 'cliapp.routesapp:noroute_app')

View file

@ -7,11 +7,14 @@
:license: BSD, see LICENSE for more details.
"""
import pytest
import os
from datetime import timedelta
import os
import textwrap
import flask
from flask._compat import PY2
import pytest
# config keys used for the TestConfig
@ -187,3 +190,18 @@ def test_get_namespace():
assert 2 == len(bar_options)
assert 'bar stuff 1' == bar_options['BAR_STUFF_1']
assert 'bar stuff 2' == bar_options['BAR_STUFF_2']
@pytest.mark.parametrize('encoding', ['utf-8', 'iso-8859-15', 'latin-1'])
def test_from_pyfile_weird_encoding(tmpdir, encoding):
f = tmpdir.join('my_config.py')
f.write_binary(textwrap.dedent(u'''
# -*- coding: {0} -*-
TEST_VALUE = "föö"
'''.format(encoding)).encode(encoding))
app = flask.Flask(__name__)
app.config.from_pyfile(str(f))
value = app.config['TEST_VALUE']
if PY2:
value = value.decode(encoding)
assert value == u'föö'

View file

@ -179,8 +179,8 @@ def test_flaskext_broken_package_no_module_caching(flaskext_broken):
def test_no_error_swallowing(flaskext_broken):
with pytest.raises(ImportError) as excinfo:
import flask.ext.broken
assert excinfo.type is ImportError
# python3.6 raises a subclass of ImportError: 'ModuleNotFoundError'
assert issubclass(excinfo.type, ImportError)
if PY2:
message = 'No module named missing_module'
else:

View file

@ -12,13 +12,16 @@
import pytest
import os
import uuid
import datetime
import flask
from logging import StreamHandler
from werkzeug.datastructures import Range
from werkzeug.exceptions import BadRequest, NotFound
from werkzeug.http import parse_cache_control_header, parse_options_header
from werkzeug.http import http_date
from flask._compat import StringIO, text_type, PY2
from flask._compat import StringIO, text_type
def has_encoding(name):
@ -32,6 +35,14 @@ def has_encoding(name):
class TestJSON(object):
def test_ignore_cached_json(self):
app = flask.Flask(__name__)
with app.test_request_context('/', method='POST', data='malformed',
content_type='application/json'):
assert flask.request.get_json(silent=True, cache=True) is None
with pytest.raises(BadRequest):
flask.request.get_json(silent=False, cache=False)
def test_post_empty_json_adds_exception_to_response_content_in_debug(self):
app = flask.Flask(__name__)
app.config['DEBUG'] = True
@ -99,20 +110,28 @@ class TestJSON(object):
rv = flask.json.dumps(u'\N{SNOWMAN}')
assert rv == u'"\u2603"'
def test_jsonify_basic_types(self):
def test_json_dump_to_file(self):
app = flask.Flask(__name__)
test_data = {'name': 'Flask'}
out = StringIO()
with app.app_context():
flask.json.dump(test_data, out)
out.seek(0)
rv = flask.json.load(out)
assert rv == test_data
@pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None])
def test_jsonify_basic_types(self, test_value):
"""Test jsonify with basic types."""
# Should be able to use pytest parametrize on this, but I couldn't
# figure out the correct syntax
# https://pytest.org/latest/parametrize.html#pytest-mark-parametrize-parametrizing-test-functions
test_data = (0, 1, 23, 3.14, 's', "longer string", True, False,)
app = flask.Flask(__name__)
c = app.test_client()
for i, d in enumerate(test_data):
url = '/jsonify_basic_types{0}'.format(i)
app.add_url_rule(url, str(i), lambda x=d: flask.jsonify(x))
rv = c.get(url)
assert rv.mimetype == 'application/json'
assert flask.json.loads(rv.data) == d
url = '/jsonify_basic_types'
app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))
rv = c.get(url)
assert rv.mimetype == 'application/json'
assert flask.json.loads(rv.data) == test_value
def test_jsonify_dicts(self):
"""Test jsonify with dicts and kwargs unpacking."""
@ -156,12 +175,10 @@ class TestJSON(object):
def test_jsonify_date_types(self):
"""Test jsonify with datetime.date and datetime.datetime types."""
test_dates = (
datetime.datetime(1973, 3, 11, 6, 30, 45),
datetime.date(1975, 1, 5)
)
app = flask.Flask(__name__)
c = app.test_client()
@ -172,6 +189,22 @@ class TestJSON(object):
assert rv.mimetype == 'application/json'
assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())
def test_jsonify_uuid_types(self):
"""Test jsonify with uuid.UUID types"""
test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)
app = flask.Flask(__name__)
url = '/uuid_test'
app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))
c = app.test_client()
rv = c.get(url)
rv_x = flask.json.loads(rv.data)['x']
assert rv_x == str(test_uuid)
rv_uuid = uuid.UUID(rv_x)
assert rv_uuid == test_uuid
def test_json_attr(self):
app = flask.Flask(__name__)
@app.route('/add', methods=['POST'])
@ -234,6 +267,47 @@ class TestJSON(object):
}), content_type='application/json')
assert rv.data == b'"<42>"'
def test_blueprint_json_customization(self):
class X(object):
def __init__(self, val):
self.val = val
class MyEncoder(flask.json.JSONEncoder):
def default(self, o):
if isinstance(o, X):
return '<%d>' % o.val
return flask.json.JSONEncoder.default(self, o)
class MyDecoder(flask.json.JSONDecoder):
def __init__(self, *args, **kwargs):
kwargs.setdefault('object_hook', self.object_hook)
flask.json.JSONDecoder.__init__(self, *args, **kwargs)
def object_hook(self, obj):
if len(obj) == 1 and '_foo' in obj:
return X(obj['_foo'])
return obj
bp = flask.Blueprint('bp', __name__)
bp.json_encoder = MyEncoder
bp.json_decoder = MyDecoder
@bp.route('/bp', methods=['POST'])
def index():
return flask.json.dumps(flask.request.get_json()['x'])
app = flask.Flask(__name__)
app.testing = True
app.register_blueprint(bp)
c = app.test_client()
rv = c.post('/bp', data=flask.json.dumps({
'x': {'_foo': 42}
}), content_type='application/json')
assert rv.data == b'"<42>"'
def test_modified_url_encoding(self):
class ModifiedRequest(flask.Request):
url_charset = 'euc-kr'
@ -256,6 +330,8 @@ class TestJSON(object):
def test_json_key_sorting(self):
app = flask.Flask(__name__)
app.testing = True
app.debug = True
assert app.config['JSON_SORT_KEYS'] == True
d = dict.fromkeys(range(20), 'foo')
@ -355,18 +431,32 @@ class TestSendfile(object):
@app.route('/')
def index():
return flask.send_file(StringIO("party like it's"), last_modified=last_modified)
return flask.send_file(StringIO("party like it's"),
last_modified=last_modified,
mimetype='text/plain')
c = app.test_client()
rv = c.get('/')
assert rv.last_modified == last_modified
def test_send_file_object_without_mimetype(self):
app = flask.Flask(__name__)
with app.test_request_context():
with pytest.raises(ValueError) as excinfo:
flask.send_file(StringIO("LOL"))
assert 'Unable to infer MIME-type' in str(excinfo)
assert 'no filename is available' in str(excinfo)
with app.test_request_context():
flask.send_file(StringIO("LOL"), attachment_filename='filename')
def test_send_file_object(self):
app = flask.Flask(__name__)
with app.test_request_context():
with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:
rv = flask.send_file(f)
rv = flask.send_file(f, mimetype='text/html')
rv.direct_passthrough = False
with app.open_resource('static/index.html') as f:
assert rv.data == f.read()
@ -377,17 +467,15 @@ class TestSendfile(object):
with app.test_request_context():
with open(os.path.join(app.root_path, 'static/index.html')) as f:
rv = flask.send_file(f)
rv = flask.send_file(f, mimetype='text/html')
assert rv.mimetype == 'text/html'
assert 'x-sendfile' in rv.headers
assert rv.headers['x-sendfile'] == \
os.path.join(app.root_path, 'static/index.html')
assert 'x-sendfile' not in rv.headers
rv.close()
app.use_x_sendfile = False
with app.test_request_context():
f = StringIO('Test')
rv = flask.send_file(f)
rv = flask.send_file(f, mimetype='application/octet-stream')
rv.direct_passthrough = False
assert rv.data == b'Test'
assert rv.mimetype == 'application/octet-stream'
@ -400,7 +488,7 @@ class TestSendfile(object):
return getattr(self._io, name)
f = PyStringIO('Test')
f.name = 'test.txt'
rv = flask.send_file(f)
rv = flask.send_file(f, attachment_filename=f.name)
rv.direct_passthrough = False
assert rv.data == b'Test'
assert rv.mimetype == 'text/plain'
@ -417,22 +505,87 @@ class TestSendfile(object):
with app.test_request_context():
f = StringIO('Test')
rv = flask.send_file(f)
rv = flask.send_file(f, mimetype='text/html')
assert 'x-sendfile' not in rv.headers
rv.close()
@pytest.mark.skipif(
not callable(getattr(Range, 'to_content_range_header', None)),
reason="not implement within werkzeug"
)
def test_send_file_range_request(self):
app = flask.Flask(__name__)
@app.route('/')
def index():
return flask.send_file('static/index.html', conditional=True)
c = app.test_client()
rv = c.get('/', headers={'Range': 'bytes=4-15'})
assert rv.status_code == 206
with app.open_resource('static/index.html') as f:
assert rv.data == f.read()[4:16]
rv.close()
rv = c.get('/', headers={'Range': 'bytes=4-'})
assert rv.status_code == 206
with app.open_resource('static/index.html') as f:
assert rv.data == f.read()[4:]
rv.close()
rv = c.get('/', headers={'Range': 'bytes=4-1000'})
assert rv.status_code == 206
with app.open_resource('static/index.html') as f:
assert rv.data == f.read()[4:]
rv.close()
rv = c.get('/', headers={'Range': 'bytes=-10'})
assert rv.status_code == 206
with app.open_resource('static/index.html') as f:
assert rv.data == f.read()[-10:]
rv.close()
rv = c.get('/', headers={'Range': 'bytes=1000-'})
assert rv.status_code == 416
rv.close()
rv = c.get('/', headers={'Range': 'bytes=-'})
assert rv.status_code == 416
rv.close()
rv = c.get('/', headers={'Range': 'somethingsomething'})
assert rv.status_code == 416
rv.close()
last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime(
os.path.join(app.root_path, 'static/index.html'))).replace(
microsecond=0)
rv = c.get('/', headers={'Range': 'bytes=4-15',
'If-Range': http_date(last_modified)})
assert rv.status_code == 206
rv.close()
rv = c.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(
datetime.datetime(1999, 1, 1))})
assert rv.status_code == 200
rv.close()
def test_attachment(self):
app = flask.Flask(__name__)
with app.test_request_context():
with open(os.path.join(app.root_path, 'static/index.html')) as f:
rv = flask.send_file(f, as_attachment=True)
rv = flask.send_file(f, as_attachment=True,
attachment_filename='index.html')
value, options = \
parse_options_header(rv.headers['Content-Disposition'])
assert value == 'attachment'
assert options['filename'] == 'index.html'
assert 'filename*' not in rv.headers['Content-Disposition']
rv.close()
with app.test_request_context():
assert options['filename'] == 'index.html'
rv = flask.send_file('static/index.html', as_attachment=True)
value, options = parse_options_header(rv.headers['Content-Disposition'])
assert value == 'attachment'
@ -449,6 +602,19 @@ class TestSendfile(object):
assert options['filename'] == 'index.txt'
rv.close()
def test_attachment_with_utf8_filename(self):
app = flask.Flask(__name__)
with app.test_request_context():
rv = flask.send_file('static/index.html', as_attachment=True, attachment_filename=u'Ñandúpingüino.txt')
content_disposition = set(rv.headers['Content-Disposition'].split('; '))
assert content_disposition == set((
'attachment',
'filename="Nandu/pinguino.txt"',
"filename*=UTF-8''%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt"
))
rv.close()
def test_static_file(self):
app = flask.Flask(__name__)
# default cache timeout is 12 hours

View file

@ -12,6 +12,7 @@
import pytest
import flask
from flask.sessions import SessionInterface
try:
from greenlet import greenlet
@ -193,3 +194,27 @@ def test_greenlet_context_copying_api():
result = greenlets[0].run()
assert result == 42
def test_session_error_pops_context():
class SessionError(Exception):
pass
class FailingSessionInterface(SessionInterface):
def open_session(self, app, request):
raise SessionError()
class CustomFlask(flask.Flask):
session_interface = FailingSessionInterface()
app = CustomFlask(__name__)
@app.route('/')
def index():
# shouldn't get here
assert False
response = app.test_client().get('/')
assert response.status_code == 500
assert not flask.request
assert not flask.current_app

View file

@ -11,6 +11,7 @@
import pytest
import flask
import werkzeug
from flask._compat import text_type
@ -43,6 +44,40 @@ def test_environ_defaults():
rv = c.get('/')
assert rv.data == b'http://localhost/'
def test_environ_base_default():
app = flask.Flask(__name__)
app.testing = True
@app.route('/')
def index():
flask.g.user_agent = flask.request.headers["User-Agent"]
return flask.request.remote_addr
with app.test_client() as c:
rv = c.get('/')
assert rv.data == b'127.0.0.1'
assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__
def test_environ_base_modified():
app = flask.Flask(__name__)
app.testing = True
@app.route('/')
def index():
flask.g.user_agent = flask.request.headers["User-Agent"]
return flask.request.remote_addr
with app.test_client() as c:
c.environ_base['REMOTE_ADDR'] = '0.0.0.0'
c.environ_base['HTTP_USER_AGENT'] = 'Foo'
rv = c.get('/')
assert rv.data == b'0.0.0.0'
assert flask.g.user_agent == 'Foo'
c.environ_base['REMOTE_ADDR'] = '0.0.0.1'
c.environ_base['HTTP_USER_AGENT'] = 'Bar'
rv = c.get('/')
assert rv.data == b'0.0.0.1'
assert flask.g.user_agent == 'Bar'
def test_redirect_keep_session():
app = flask.Flask(__name__)
app.secret_key = 'testing'

View file

@ -160,3 +160,45 @@ def test_endpoint_override():
# But these tests should still pass. We just log a warning.
common_test(app)
def test_multiple_inheritance():
app = flask.Flask(__name__)
class GetView(flask.views.MethodView):
def get(self):
return 'GET'
class DeleteView(flask.views.MethodView):
def delete(self):
return 'DELETE'
class GetDeleteView(GetView, DeleteView):
pass
app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))
c = app.test_client()
assert c.get('/').data == b'GET'
assert c.delete('/').data == b'DELETE'
assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']
def test_remove_method_from_parent():
app = flask.Flask(__name__)
class GetView(flask.views.MethodView):
def get(self):
return 'GET'
class OtherView(flask.views.MethodView):
def post(self):
return 'POST'
class View(GetView, OtherView):
methods = ['GET']
app.add_url_rule('/', view_func=View.as_view('index'))
c = app.test_client()
assert c.get('/').data == b'GET'
assert c.post('/').status_code == 405
assert sorted(View.methods) == ['GET']