Browse Source

Kill class in test_basic

pull/1165/head
Markus Unterwaditzer 11 years ago
parent
commit
a4931ff3a7
  1. 304
      tests/test_basic.py

304
tests/test_basic.py

@ -16,20 +16,17 @@ import uuid
import time import time
import flask import flask
import pickle import pickle
import unittest
from datetime import datetime from datetime import datetime
from threading import Thread from threading import Thread
from tests import emits_module_deprecation_warning
from flask._compat import text_type from flask._compat import text_type
from werkzeug.exceptions import BadRequest, NotFound, Forbidden from werkzeug.exceptions import BadRequest, NotFound, Forbidden
from werkzeug.http import parse_date from werkzeug.http import parse_date
from werkzeug.routing import BuildError from werkzeug.routing import BuildError
class TestBasicFunctionality(object): def test_options_work():
def test_options_work(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.route('/', methods=['GET', 'POST']) @app.route('/', methods=['GET', 'POST'])
def index(): def index():
return 'Hello World' return 'Hello World'
@ -37,19 +34,24 @@ class TestBasicFunctionality(object):
assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST'] assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']
assert rv.data == b'' assert rv.data == b''
def test_options_on_multiple_rules(self):
def test_options_on_multiple_rules():
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.route('/', methods=['GET', 'POST']) @app.route('/', methods=['GET', 'POST'])
def index(): def index():
return 'Hello World' return 'Hello World'
@app.route('/', methods=['PUT']) @app.route('/', methods=['PUT'])
def index_put(): def index_put():
return 'Aha!' return 'Aha!'
rv = app.test_client().open('/', method='OPTIONS') rv = app.test_client().open('/', method='OPTIONS')
assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'] assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']
def test_options_handling_disabled(self):
def test_options_handling_disabled():
app = flask.Flask(__name__) app = flask.Flask(__name__)
def index(): def index():
return 'Hello World!' return 'Hello World!'
index.provide_automatic_options = False index.provide_automatic_options = False
@ -58,6 +60,7 @@ class TestBasicFunctionality(object):
assert rv.status_code == 405 assert rv.status_code == 405
app = flask.Flask(__name__) app = flask.Flask(__name__)
def index2(): def index2():
return 'Hello World!' return 'Hello World!'
index2.provide_automatic_options = True index2.provide_automatic_options = True
@ -65,11 +68,14 @@ class TestBasicFunctionality(object):
rv = app.test_client().open('/', method='OPTIONS') rv = app.test_client().open('/', method='OPTIONS')
assert sorted(rv.allow) == ['OPTIONS'] assert sorted(rv.allow) == ['OPTIONS']
def test_request_dispatching(self):
def test_request_dispatching():
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.route('/') @app.route('/')
def index(): def index():
return flask.request.method return flask.request.method
@app.route('/more', methods=['GET', 'POST']) @app.route('/more', methods=['GET', 'POST'])
def more(): def more():
return flask.request.method return flask.request.method
@ -88,17 +94,21 @@ class TestBasicFunctionality(object):
assert rv.status_code == 405 assert rv.status_code == 405
assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST'] assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']
def test_disallow_string_for_allowed_methods(self):
def test_disallow_string_for_allowed_methods():
app = flask.Flask(__name__) app = flask.Flask(__name__)
with pytest.raises(TypeError): with pytest.raises(TypeError):
@app.route('/', methods='GET POST') @app.route('/', methods='GET POST')
def index(): def index():
return "Hey" return "Hey"
def test_url_mapping(self):
def test_url_mapping():
app = flask.Flask(__name__) app = flask.Flask(__name__)
def index(): def index():
return flask.request.method return flask.request.method
def more(): def more():
return flask.request.method return flask.request.method
@ -119,15 +129,18 @@ class TestBasicFunctionality(object):
assert rv.status_code == 405 assert rv.status_code == 405
assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST'] assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']
def test_werkzeug_routing(self):
def test_werkzeug_routing():
from werkzeug.routing import Submount, Rule from werkzeug.routing import Submount, Rule
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.url_map.add(Submount('/foo', [ app.url_map.add(Submount('/foo', [
Rule('/bar', endpoint='bar'), Rule('/bar', endpoint='bar'),
Rule('/', endpoint='index') Rule('/', endpoint='index')
])) ]))
def bar(): def bar():
return 'bar' return 'bar'
def index(): def index():
return 'index' return 'index'
app.view_functions['bar'] = bar app.view_functions['bar'] = bar
@ -137,7 +150,8 @@ class TestBasicFunctionality(object):
assert c.get('/foo/').data == b'index' assert c.get('/foo/').data == b'index'
assert c.get('/foo/bar').data == b'bar' assert c.get('/foo/bar').data == b'bar'
def test_endpoint_decorator(self):
def test_endpoint_decorator():
from werkzeug.routing import Submount, Rule from werkzeug.routing import Submount, Rule
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.url_map.add(Submount('/foo', [ app.url_map.add(Submount('/foo', [
@ -157,13 +171,16 @@ class TestBasicFunctionality(object):
assert c.get('/foo/').data == b'index' assert c.get('/foo/').data == b'index'
assert c.get('/foo/bar').data == b'bar' assert c.get('/foo/bar').data == b'bar'
def test_session(self):
def test_session():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.secret_key = 'testkey' app.secret_key = 'testkey'
@app.route('/set', methods=['POST']) @app.route('/set', methods=['POST'])
def set(): def set():
flask.session['value'] = flask.request.form['value'] flask.session['value'] = flask.request.form['value']
return 'value set' return 'value set'
@app.route('/get') @app.route('/get')
def get(): def get():
return flask.session['value'] return flask.session['value']
@ -172,12 +189,14 @@ class TestBasicFunctionality(object):
assert c.post('/set', data={'value': '42'}).data == b'value set' assert c.post('/set', data={'value': '42'}).data == b'value set'
assert c.get('/get').data == b'42' assert c.get('/get').data == b'42'
def test_session_using_server_name(self):
def test_session_using_server_name():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config.update( app.config.update(
SECRET_KEY='foo', SECRET_KEY='foo',
SERVER_NAME='example.com' SERVER_NAME='example.com'
) )
@app.route('/') @app.route('/')
def index(): def index():
flask.session['testing'] = 42 flask.session['testing'] = 42
@ -186,12 +205,14 @@ class TestBasicFunctionality(object):
assert 'domain=.example.com' in rv.headers['set-cookie'].lower() assert 'domain=.example.com' in rv.headers['set-cookie'].lower()
assert 'httponly' in rv.headers['set-cookie'].lower() assert 'httponly' in rv.headers['set-cookie'].lower()
def test_session_using_server_name_and_port(self):
def test_session_using_server_name_and_port():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config.update( app.config.update(
SECRET_KEY='foo', SECRET_KEY='foo',
SERVER_NAME='example.com:8080' SERVER_NAME='example.com:8080'
) )
@app.route('/') @app.route('/')
def index(): def index():
flask.session['testing'] = 42 flask.session['testing'] = 42
@ -200,13 +221,15 @@ class TestBasicFunctionality(object):
assert 'domain=.example.com' in rv.headers['set-cookie'].lower() assert 'domain=.example.com' in rv.headers['set-cookie'].lower()
assert 'httponly' in rv.headers['set-cookie'].lower() assert 'httponly' in rv.headers['set-cookie'].lower()
def test_session_using_server_name_port_and_path(self):
def test_session_using_server_name_port_and_path():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config.update( app.config.update(
SECRET_KEY='foo', SECRET_KEY='foo',
SERVER_NAME='example.com:8080', SERVER_NAME='example.com:8080',
APPLICATION_ROOT='/foo' APPLICATION_ROOT='/foo'
) )
@app.route('/') @app.route('/')
def index(): def index():
flask.session['testing'] = 42 flask.session['testing'] = 42
@ -216,11 +239,14 @@ class TestBasicFunctionality(object):
assert 'path=/foo' in rv.headers['set-cookie'].lower() assert 'path=/foo' in rv.headers['set-cookie'].lower()
assert 'httponly' in rv.headers['set-cookie'].lower() assert 'httponly' in rv.headers['set-cookie'].lower()
def test_session_using_application_root(self):
def test_session_using_application_root():
class PrefixPathMiddleware(object): class PrefixPathMiddleware(object):
def __init__(self, app, prefix): def __init__(self, app, prefix):
self.app = app self.app = app
self.prefix = prefix self.prefix = prefix
def __call__(self, environ, start_response): def __call__(self, environ, start_response):
environ['SCRIPT_NAME'] = self.prefix environ['SCRIPT_NAME'] = self.prefix
return self.app(environ, start_response) return self.app(environ, start_response)
@ -231,6 +257,7 @@ class TestBasicFunctionality(object):
SECRET_KEY='foo', SECRET_KEY='foo',
APPLICATION_ROOT='/bar' APPLICATION_ROOT='/bar'
) )
@app.route('/') @app.route('/')
def index(): def index():
flask.session['testing'] = 42 flask.session['testing'] = 42
@ -238,7 +265,8 @@ class TestBasicFunctionality(object):
rv = app.test_client().get('/', 'http://example.com:8080/') rv = app.test_client().get('/', 'http://example.com:8080/')
assert 'path=/bar' in rv.headers['set-cookie'].lower() assert 'path=/bar' in rv.headers['set-cookie'].lower()
def test_session_using_session_settings(self):
def test_session_using_session_settings():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config.update( app.config.update(
SECRET_KEY='foo', SECRET_KEY='foo',
@ -249,6 +277,7 @@ class TestBasicFunctionality(object):
SESSION_COOKIE_SECURE=True, SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_PATH='/' SESSION_COOKIE_PATH='/'
) )
@app.route('/') @app.route('/')
def index(): def index():
flask.session['testing'] = 42 flask.session['testing'] = 42
@ -260,8 +289,10 @@ class TestBasicFunctionality(object):
assert 'secure' in cookie assert 'secure' in cookie
assert 'httponly' not in cookie assert 'httponly' not in cookie
def test_missing_session(self):
def test_missing_session():
app = flask.Flask(__name__) app = flask.Flask(__name__)
def expect_exception(f, *args, **kwargs): def expect_exception(f, *args, **kwargs):
try: try:
f(*args, **kwargs) f(*args, **kwargs)
@ -274,10 +305,12 @@ class TestBasicFunctionality(object):
expect_exception(flask.session.__setitem__, 'foo', 42) expect_exception(flask.session.__setitem__, 'foo', 42)
expect_exception(flask.session.pop, 'foo') expect_exception(flask.session.pop, 'foo')
def test_session_expiration(self):
def test_session_expiration():
permanent = True permanent = True
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.secret_key = 'testkey' app.secret_key = 'testkey'
@app.route('/') @app.route('/')
def index(): def index():
flask.session['test'] = 42 flask.session['test'] = 42
@ -307,7 +340,8 @@ class TestBasicFunctionality(object):
match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie']) match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])
assert match is None assert match is None
def test_session_stored_last(self):
def test_session_stored_last():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.secret_key = 'development-key' app.secret_key = 'development-key'
app.testing = True app.testing = True
@ -316,6 +350,7 @@ class TestBasicFunctionality(object):
def modify_session(response): def modify_session(response):
flask.session['foo'] = 42 flask.session['foo'] = 42
return response return response
@app.route('/') @app.route('/')
def dump_session_contents(): def dump_session_contents():
return repr(flask.session.get('foo')) return repr(flask.session.get('foo'))
@ -324,7 +359,8 @@ class TestBasicFunctionality(object):
assert c.get('/').data == b'None' assert c.get('/').data == b'None'
assert c.get('/').data == b'42' assert c.get('/').data == b'42'
def test_session_special_types(self):
def test_session_special_types():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.secret_key = 'development-key' app.secret_key = 'development-key'
app.testing = True app.testing = True
@ -355,7 +391,8 @@ class TestBasicFunctionality(object):
assert type(rv['b']) == bytes assert type(rv['b']) == bytes
assert rv['t'] == (1, 2, 3) assert rv['t'] == (1, 2, 3)
def test_session_cookie_setting(self):
def test_session_cookie_setting():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.testing = True app.testing = True
app.secret_key = 'dev key' app.secret_key = 'dev key'
@ -398,7 +435,8 @@ class TestBasicFunctionality(object):
app.config['SESSION_REFRESH_EACH_REQUEST'] = False app.config['SESSION_REFRESH_EACH_REQUEST'] = False
run_test(expect_header=False) run_test(expect_header=False)
def test_flashes(self):
def test_flashes():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.secret_key = 'testkey' app.secret_key = 'testkey'
@ -410,7 +448,8 @@ class TestBasicFunctionality(object):
assert flask.session.modified assert flask.session.modified
assert list(flask.get_flashed_messages()) == ['Zap', 'Zip'] assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']
def test_extended_flashing(self):
def test_extended_flashing():
# Be sure app.testing=True below, else tests can fail silently. # Be sure app.testing=True below, else tests can fail silently.
# #
# Specifically, if app.testing is not set to True, the AssertionErrors # Specifically, if app.testing is not set to True, the AssertionErrors
@ -451,13 +490,15 @@ class TestBasicFunctionality(object):
@app.route('/test_filter/') @app.route('/test_filter/')
def test_filter(): def test_filter():
messages = flask.get_flashed_messages(category_filter=['message'], with_categories=True) messages = flask.get_flashed_messages(
category_filter=['message'], with_categories=True)
assert list(messages) == [('message', u'Hello World')] assert list(messages) == [('message', u'Hello World')]
return '' return ''
@app.route('/test_filters/') @app.route('/test_filters/')
def test_filters(): def test_filters():
messages = flask.get_flashed_messages(category_filter=['message', 'warning'], with_categories=True) messages = flask.get_flashed_messages(
category_filter=['message', 'warning'], with_categories=True)
assert list(messages) == [ assert list(messages) == [
('message', u'Hello World'), ('message', u'Hello World'),
('warning', flask.Markup(u'<em>Testing</em>')) ('warning', flask.Markup(u'<em>Testing</em>'))
@ -466,7 +507,8 @@ class TestBasicFunctionality(object):
@app.route('/test_filters_without_returning_categories/') @app.route('/test_filters_without_returning_categories/')
def test_filters2(): def test_filters2():
messages = flask.get_flashed_messages(category_filter=['message', 'warning']) messages = flask.get_flashed_messages(
category_filter=['message', 'warning'])
assert len(messages) == 2 assert len(messages) == 2
assert messages[0] == u'Hello World' assert messages[0] == u'Hello World'
assert messages[1] == flask.Markup(u'<em>Testing</em>') assert messages[1] == flask.Markup(u'<em>Testing</em>')
@ -494,17 +536,21 @@ class TestBasicFunctionality(object):
c.get('/') c.get('/')
c.get('/test_filters_without_returning_categories/') c.get('/test_filters_without_returning_categories/')
def test_request_processing(self):
def test_request_processing():
app = flask.Flask(__name__) app = flask.Flask(__name__)
evts = [] evts = []
@app.before_request @app.before_request
def before_request(): def before_request():
evts.append('before') evts.append('before')
@app.after_request @app.after_request
def after_request(response): def after_request(response):
response.data += b'|after' response.data += b'|after'
evts.append('after') evts.append('after')
return response return response
@app.route('/') @app.route('/')
def index(): def index():
assert 'before' in evts assert 'before' in evts
@ -515,9 +561,11 @@ class TestBasicFunctionality(object):
assert 'after' in evts assert 'after' in evts
assert rv == b'request|after' assert rv == b'request|after'
def test_after_request_processing(self):
def test_after_request_processing():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.testing = True app.testing = True
@app.route('/') @app.route('/')
def index(): def index():
@flask.after_this_request @flask.after_this_request
@ -530,13 +578,16 @@ class TestBasicFunctionality(object):
assert resp.status_code == 200 assert resp.status_code == 200
assert resp.headers['X-Foo'] == 'a header' assert resp.headers['X-Foo'] == 'a header'
def test_teardown_request_handler(self):
def test_teardown_request_handler():
called = [] called = []
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.teardown_request @app.teardown_request
def teardown_request(exc): def teardown_request(exc):
called.append(True) called.append(True)
return "Ignored" return "Ignored"
@app.route('/') @app.route('/')
def root(): def root():
return "Response" return "Response"
@ -545,14 +596,17 @@ class TestBasicFunctionality(object):
assert b'Response' in rv.data assert b'Response' in rv.data
assert len(called) == 1 assert len(called) == 1
def test_teardown_request_handler_debug_mode(self):
def test_teardown_request_handler_debug_mode():
called = [] called = []
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.testing = True app.testing = True
@app.teardown_request @app.teardown_request
def teardown_request(exc): def teardown_request(exc):
called.append(True) called.append(True)
return "Ignored" return "Ignored"
@app.route('/') @app.route('/')
def root(): def root():
return "Response" return "Response"
@ -561,10 +615,12 @@ class TestBasicFunctionality(object):
assert b'Response' in rv.data assert b'Response' in rv.data
assert len(called) == 1 assert len(called) == 1
def test_teardown_request_handler_error(self):
def test_teardown_request_handler_error():
called = [] called = []
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config['LOGGER_HANDLER_POLICY'] = 'never' app.config['LOGGER_HANDLER_POLICY'] = 'never'
@app.teardown_request @app.teardown_request
def teardown_request1(exc): def teardown_request1(exc):
assert type(exc) == ZeroDivisionError assert type(exc) == ZeroDivisionError
@ -576,6 +632,7 @@ class TestBasicFunctionality(object):
raise TypeError() raise TypeError()
except: except:
pass pass
@app.teardown_request @app.teardown_request
def teardown_request2(exc): def teardown_request2(exc):
assert type(exc) == ZeroDivisionError assert type(exc) == ZeroDivisionError
@ -587,6 +644,7 @@ class TestBasicFunctionality(object):
raise TypeError() raise TypeError()
except: except:
pass pass
@app.route('/') @app.route('/')
def fails(): def fails():
1 // 0 1 // 0
@ -595,29 +653,37 @@ class TestBasicFunctionality(object):
assert b'Internal Server Error' in rv.data assert b'Internal Server Error' in rv.data
assert len(called) == 2 assert len(called) == 2
def test_before_after_request_order(self):
def test_before_after_request_order():
called = [] called = []
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.before_request @app.before_request
def before1(): def before1():
called.append(1) called.append(1)
@app.before_request @app.before_request
def before2(): def before2():
called.append(2) called.append(2)
@app.after_request @app.after_request
def after1(response): def after1(response):
called.append(4) called.append(4)
return response return response
@app.after_request @app.after_request
def after2(response): def after2(response):
called.append(3) called.append(3)
return response return response
@app.teardown_request @app.teardown_request
def finish1(exc): def finish1(exc):
called.append(6) called.append(6)
@app.teardown_request @app.teardown_request
def finish2(exc): def finish2(exc):
called.append(5) called.append(5)
@app.route('/') @app.route('/')
def index(): def index():
return '42' return '42'
@ -625,24 +691,31 @@ class TestBasicFunctionality(object):
assert rv.data == b'42' assert rv.data == b'42'
assert called == [1, 2, 3, 4, 5, 6] assert called == [1, 2, 3, 4, 5, 6]
def test_error_handling(self):
def test_error_handling():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config['LOGGER_HANDLER_POLICY'] = 'never' app.config['LOGGER_HANDLER_POLICY'] = 'never'
@app.errorhandler(404) @app.errorhandler(404)
def not_found(e): def not_found(e):
return 'not found', 404 return 'not found', 404
@app.errorhandler(500) @app.errorhandler(500)
def internal_server_error(e): def internal_server_error(e):
return 'internal server error', 500 return 'internal server error', 500
@app.errorhandler(Forbidden) @app.errorhandler(Forbidden)
def forbidden(e): def forbidden(e):
return 'forbidden', 403 return 'forbidden', 403
@app.route('/') @app.route('/')
def index(): def index():
flask.abort(404) flask.abort(404)
@app.route('/error') @app.route('/error')
def error(): def error():
1 // 0 1 // 0
@app.route('/forbidden') @app.route('/forbidden')
def error2(): def error2():
flask.abort(403) flask.abort(403)
@ -657,11 +730,14 @@ class TestBasicFunctionality(object):
assert rv.status_code == 403 assert rv.status_code == 403
assert b'forbidden' == rv.data assert b'forbidden' == rv.data
def test_before_request_and_routing_errors(self):
def test_before_request_and_routing_errors():
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.before_request @app.before_request
def attach_something(): def attach_something():
flask.g.something = 'value' flask.g.something = 'value'
@app.errorhandler(404) @app.errorhandler(404)
def return_something(error): def return_something(error):
return flask.g.something, 404 return flask.g.something, 404
@ -669,15 +745,18 @@ class TestBasicFunctionality(object):
assert rv.status_code == 404 assert rv.status_code == 404
assert rv.data == b'value' assert rv.data == b'value'
def test_user_error_handling(self):
def test_user_error_handling():
class MyException(Exception): class MyException(Exception):
pass pass
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.errorhandler(MyException) @app.errorhandler(MyException)
def handle_my_exception(e): def handle_my_exception(e):
assert isinstance(e, MyException) assert isinstance(e, MyException)
return '42' return '42'
@app.route('/') @app.route('/')
def index(): def index():
raise MyException() raise MyException()
@ -685,15 +764,18 @@ class TestBasicFunctionality(object):
c = app.test_client() c = app.test_client()
assert c.get('/').data == b'42' assert c.get('/').data == b'42'
def test_http_error_subclass_handling(self):
def test_http_error_subclass_handling():
class ForbiddenSubclass(Forbidden): class ForbiddenSubclass(Forbidden):
pass pass
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.errorhandler(ForbiddenSubclass) @app.errorhandler(ForbiddenSubclass)
def handle_forbidden_subclass(e): def handle_forbidden_subclass(e):
assert isinstance(e, ForbiddenSubclass) assert isinstance(e, ForbiddenSubclass)
return 'banana' return 'banana'
@app.errorhandler(403) @app.errorhandler(403)
def handle_forbidden_subclass(e): def handle_forbidden_subclass(e):
assert not isinstance(e, ForbiddenSubclass) assert not isinstance(e, ForbiddenSubclass)
@ -703,9 +785,11 @@ class TestBasicFunctionality(object):
@app.route('/1') @app.route('/1')
def index1(): def index1():
raise ForbiddenSubclass() raise ForbiddenSubclass()
@app.route('/2') @app.route('/2')
def index2(): def index2():
flask.abort(403) flask.abort(403)
@app.route('/3') @app.route('/3')
def index3(): def index3():
raise Forbidden() raise Forbidden()
@ -715,9 +799,11 @@ class TestBasicFunctionality(object):
assert c.get('/2').data == b'apple' assert c.get('/2').data == b'apple'
assert c.get('/3').data == b'apple' assert c.get('/3').data == b'apple'
def test_trapping_of_bad_request_key_errors(self):
def test_trapping_of_bad_request_key_errors():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.testing = True app.testing = True
@app.route('/fail') @app.route('/fail')
def fail(): def fail():
flask.request.form['missing_key'] flask.request.form['missing_key']
@ -733,26 +819,26 @@ class TestBasicFunctionality(object):
else: else:
assert False, 'Expected exception' assert False, 'Expected exception'
def test_trapping_of_all_http_exceptions(self):
def test_trapping_of_all_http_exceptions():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.testing = True app.testing = True
app.config['TRAP_HTTP_EXCEPTIONS'] = True app.config['TRAP_HTTP_EXCEPTIONS'] = True
@app.route('/fail') @app.route('/fail')
def fail(): def fail():
flask.abort(404) flask.abort(404)
c = app.test_client() c = app.test_client()
try: with pytest.raises(NotFound):
c.get('/fail') c.get('/fail')
except NotFound as e:
pass
else:
assert False, 'Expected exception'
def test_enctype_debug_helper(self):
def test_enctype_debug_helper():
from flask.debughelpers import DebugFilesKeyError from flask.debughelpers import DebugFilesKeyError
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.debug = True app.debug = True
@app.route('/fail', methods=['POST']) @app.route('/fail', methods=['POST'])
def index(): def index():
return flask.request.files['foo'].filename return flask.request.files['foo'].filename
@ -769,29 +855,36 @@ class TestBasicFunctionality(object):
else: else:
assert False, 'Expected exception' assert False, 'Expected exception'
def test_response_creation(self):
def test_response_creation():
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.route('/unicode') @app.route('/unicode')
def from_unicode(): def from_unicode():
return u'Hällo Wörld' return u'Hällo Wörld'
@app.route('/string') @app.route('/string')
def from_string(): def from_string():
return u'Hällo Wörld'.encode('utf-8') return u'Hällo Wörld'.encode('utf-8')
@app.route('/args') @app.route('/args')
def from_tuple(): def from_tuple():
return 'Meh', 400, { return 'Meh', 400, {
'X-Foo': 'Testing', 'X-Foo': 'Testing',
'Content-Type': 'text/plain; charset=utf-8' 'Content-Type': 'text/plain; charset=utf-8'
} }
@app.route('/two_args') @app.route('/two_args')
def from_two_args_tuple(): def from_two_args_tuple():
return 'Hello', { return 'Hello', {
'X-Foo': 'Test', 'X-Foo': 'Test',
'Content-Type': 'text/plain; charset=utf-8' 'Content-Type': 'text/plain; charset=utf-8'
} }
@app.route('/args_status') @app.route('/args_status')
def from_status_tuple(): def from_status_tuple():
return 'Hi, status!', 400 return 'Hi, status!', 400
@app.route('/args_header') @app.route('/args_header')
def from_response_instance_status_tuple(): def from_response_instance_status_tuple():
return flask.Response('Hello world', 404), { return flask.Response('Hello world', 404), {
@ -822,7 +915,8 @@ class TestBasicFunctionality(object):
assert rv4.headers['X-Bar'] == 'Foo' assert rv4.headers['X-Bar'] == 'Foo'
assert rv4.status_code == 404 assert rv4.status_code == 404
def test_make_response(self):
def test_make_response():
app = flask.Flask(__name__) app = flask.Flask(__name__)
with app.test_request_context(): with app.test_request_context():
rv = flask.make_response() rv = flask.make_response()
@ -840,7 +934,8 @@ class TestBasicFunctionality(object):
assert rv.data == b'W00t' assert rv.data == b'W00t'
assert rv.mimetype == 'text/html' assert rv.mimetype == 'text/html'
def test_make_response_with_response_instance(self):
def test_make_response_with_response_instance():
app = flask.Flask(__name__) app = flask.Flask(__name__)
with app.test_request_context(): with app.test_request_context():
rv = flask.make_response( rv = flask.make_response(
@ -862,8 +957,10 @@ class TestBasicFunctionality(object):
assert rv.headers['Content-Type'] == 'text/html' assert rv.headers['Content-Type'] == 'text/html'
assert rv.headers['X-Foo'] == 'bar' assert rv.headers['X-Foo'] == 'bar'
def test_url_generation(self):
def test_url_generation():
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.route('/hello/<name>', methods=['POST']) @app.route('/hello/<name>', methods=['POST'])
def hello(): def hello():
pass pass
@ -872,7 +969,8 @@ class TestBasicFunctionality(object):
assert flask.url_for('hello', name='test x', _external=True) == \ assert flask.url_for('hello', name='test x', _external=True) == \
'http://localhost/hello/test%20x' 'http://localhost/hello/test%20x'
def test_build_error_handler(self):
def test_build_error_handler():
app = flask.Flask(__name__) app = flask.Flask(__name__)
# Test base case, a URL which results in a BuildError. # Test base case, a URL which results in a BuildError.
@ -888,7 +986,8 @@ class TestBasicFunctionality(object):
try: try:
raise RuntimeError('Test case where BuildError is not current.') raise RuntimeError('Test case where BuildError is not current.')
except RuntimeError: except RuntimeError:
pytest.raises(BuildError, app.handle_url_build_error, error, 'spam', {}) pytest.raises(
BuildError, app.handle_url_build_error, error, 'spam', {})
# Test a custom handler. # Test a custom handler.
def handler(error, endpoint, values): def handler(error, endpoint, values):
@ -898,23 +997,29 @@ class TestBasicFunctionality(object):
with app.test_request_context(): with app.test_request_context():
assert flask.url_for('spam') == '/test_handler/' assert flask.url_for('spam') == '/test_handler/'
def test_custom_converters(self):
def test_custom_converters():
from werkzeug.routing import BaseConverter from werkzeug.routing import BaseConverter
class ListConverter(BaseConverter): class ListConverter(BaseConverter):
def to_python(self, value): def to_python(self, value):
return value.split(',') return value.split(',')
def to_url(self, value): def to_url(self, value):
base_to_url = super(ListConverter, self).to_url base_to_url = super(ListConverter, self).to_url
return ','.join(base_to_url(x) for x in value) return ','.join(base_to_url(x) for x in value)
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.url_map.converters['list'] = ListConverter app.url_map.converters['list'] = ListConverter
@app.route('/<list:args>') @app.route('/<list:args>')
def index(args): def index(args):
return '|'.join(args) return '|'.join(args)
c = app.test_client() c = app.test_client()
assert c.get('/1,2,3').data == b'1|2|3' assert c.get('/1,2,3').data == b'1|2|3'
def test_static_files(self):
def test_static_files():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.testing = True app.testing = True
rv = app.test_client().get('/static/index.html') rv = app.test_client().get('/static/index.html')
@ -925,9 +1030,11 @@ class TestBasicFunctionality(object):
'/static/index.html' '/static/index.html'
rv.close() rv.close()
def test_none_response(self):
def test_none_response():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.testing = True app.testing = True
@app.route('/') @app.route('/')
def test(): def test():
return None return None
@ -939,15 +1046,18 @@ class TestBasicFunctionality(object):
else: else:
assert "Expected ValueError" assert "Expected ValueError"
def test_request_locals(self):
def test_request_locals():
assert repr(flask.g) == '<LocalProxy unbound>' assert repr(flask.g) == '<LocalProxy unbound>'
assert not flask.g assert not flask.g
def test_test_app_proper_environ(self):
def test_test_app_proper_environ():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config.update( app.config.update(
SERVER_NAME='localhost.localdomain:5000' SERVER_NAME='localhost.localdomain:5000'
) )
@app.route('/') @app.route('/')
def index(): def index():
return 'Foo' return 'Foo'
@ -998,10 +1108,12 @@ class TestBasicFunctionality(object):
rv = app.test_client().get('/', 'http://foo.localhost.localdomain') rv = app.test_client().get('/', 'http://foo.localhost.localdomain')
assert rv.data == b'Foo SubDomain' assert rv.data == b'Foo SubDomain'
def test_exception_propagation(self):
def test_exception_propagation():
def apprunner(configkey): def apprunner(configkey):
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config['LOGGER_HANDLER_POLICY'] = 'never' app.config['LOGGER_HANDLER_POLICY'] = 'never'
@app.route('/') @app.route('/')
def index(): def index():
1 // 0 1 // 0
@ -1026,17 +1138,21 @@ class TestBasicFunctionality(object):
t.start() t.start()
t.join() t.join()
def test_max_content_length(self):
def test_max_content_length():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 64 app.config['MAX_CONTENT_LENGTH'] = 64
@app.before_request @app.before_request
def always_first(): def always_first():
flask.request.form['myfile'] flask.request.form['myfile']
assert False assert False
@app.route('/accept', methods=['POST']) @app.route('/accept', methods=['POST'])
def accept_file(): def accept_file():
flask.request.form['myfile'] flask.request.form['myfile']
assert False assert False
@app.errorhandler(413) @app.errorhandler(413)
def catcher(error): def catcher(error):
return '42' return '42'
@ -1045,7 +1161,8 @@ class TestBasicFunctionality(object):
rv = c.post('/accept', data={'myfile': 'foo' * 100}) rv = c.post('/accept', data={'myfile': 'foo' * 100})
assert rv.data == b'42' assert rv.data == b'42'
def test_url_processors(self):
def test_url_processors():
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.url_defaults @app.url_defaults
@ -1076,7 +1193,8 @@ class TestBasicFunctionality(object):
assert c.get('/de/about').data == b'/foo' assert c.get('/de/about').data == b'/foo'
assert c.get('/foo').data == b'/en/about' assert c.get('/foo').data == b'/en/about'
def test_inject_blueprint_url_defaults(self):
def test_inject_blueprint_url_defaults():
app = flask.Flask(__name__) app = flask.Flask(__name__)
bp = flask.Blueprint('foo.bar.baz', __name__, bp = flask.Blueprint('foo.bar.baz', __name__,
template_folder='template') template_folder='template')
@ -1084,8 +1202,10 @@ class TestBasicFunctionality(object):
@bp.url_defaults @bp.url_defaults
def bp_defaults(endpoint, values): def bp_defaults(endpoint, values):
values['page'] = 'login' values['page'] = 'login'
@bp.route('/<page>') @bp.route('/<page>')
def view(page): pass def view(page):
pass
app.register_blueprint(bp) app.register_blueprint(bp)
@ -1099,7 +1219,8 @@ class TestBasicFunctionality(object):
expected = '/login' expected = '/login'
assert url == expected assert url == expected
def test_nonascii_pathinfo(self):
def test_nonascii_pathinfo():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.testing = True app.testing = True
@ -1111,9 +1232,11 @@ class TestBasicFunctionality(object):
rv = c.get(u'/киртест') rv = c.get(u'/киртест')
assert rv.data == b'Hello World!' assert rv.data == b'Hello World!'
def test_debug_mode_complains_after_first_request(self):
def test_debug_mode_complains_after_first_request():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.debug = True app.debug = True
@app.route('/') @app.route('/')
def index(): def index():
return 'Awesome' return 'Awesome'
@ -1129,15 +1252,18 @@ class TestBasicFunctionality(object):
assert False, 'Expected exception' assert False, 'Expected exception'
app.debug = False app.debug = False
@app.route('/foo') @app.route('/foo')
def working(): def working():
return 'Meh' return 'Meh'
assert app.test_client().get('/foo').data == b'Meh' assert app.test_client().get('/foo').data == b'Meh'
assert app.got_first_request assert app.got_first_request
def test_before_first_request_functions(self):
def test_before_first_request_functions():
got = [] got = []
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.before_first_request @app.before_first_request
def foo(): def foo():
got.append(42) got.append(42)
@ -1148,7 +1274,8 @@ class TestBasicFunctionality(object):
assert got == [42] assert got == [42]
assert app.got_first_request assert app.got_first_request
def test_before_first_request_functions_concurrent(self):
def test_before_first_request_functions_concurrent():
got = [] got = []
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -1158,6 +1285,7 @@ class TestBasicFunctionality(object):
got.append(42) got.append(42)
c = app.test_client() c = app.test_client()
def get_and_assert(): def get_and_assert():
c.get("/") c.get("/")
assert got == [42] assert got == [42]
@ -1168,9 +1296,11 @@ class TestBasicFunctionality(object):
t.join() t.join()
assert app.got_first_request assert app.got_first_request
def test_routing_redirect_debugging(self):
def test_routing_redirect_debugging():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.debug = True app.debug = True
@app.route('/foo/', methods=['GET', 'POST']) @app.route('/foo/', methods=['GET', 'POST'])
def foo(): def foo():
return 'success' return 'success'
@ -1192,7 +1322,8 @@ class TestBasicFunctionality(object):
rv = c.post('/foo', data={}, follow_redirects=True) rv = c.post('/foo', data={}, follow_redirects=True)
assert rv.data == b'success' assert rv.data == b'success'
def test_route_decorator_custom_endpoint(self):
def test_route_decorator_custom_endpoint():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.debug = True app.debug = True
@ -1218,7 +1349,8 @@ class TestBasicFunctionality(object):
assert c.get('/bar/').data == b'bar' assert c.get('/bar/').data == b'bar'
assert c.get('/bar/123').data == b'123' assert c.get('/bar/123').data == b'123'
def test_preserve_only_once(self):
def test_preserve_only_once():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.debug = True app.debug = True
@ -1238,7 +1370,8 @@ class TestBasicFunctionality(object):
assert flask._request_ctx_stack.top is None assert flask._request_ctx_stack.top is None
assert flask._app_ctx_stack.top is None assert flask._app_ctx_stack.top is None
def test_preserve_remembers_exception(self):
def test_preserve_remembers_exception():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.debug = True app.debug = True
errors = [] errors = []
@ -1270,20 +1403,22 @@ class TestBasicFunctionality(object):
# At this point another request does nothing. # At this point another request does nothing.
c.get('/success') c.get('/success')
assert len(errors) == 3 assert len(errors) == 3
assert errors[1] == None assert errors[1] is None
def test_get_method_on_g(self): def test_get_method_on_g():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.testing = True app.testing = True
with app.app_context(): with app.app_context():
assert flask.g.get('x') == None assert flask.g.get('x') is None
assert flask.g.get('x', 11) == 11 assert flask.g.get('x', 11) == 11
flask.g.x = 42 flask.g.x = 42
assert flask.g.get('x') == 42 assert flask.g.get('x') == 42
assert flask.g.x == 42 assert flask.g.x == 42
def test_g_iteration_protocol(self):
def test_g_iteration_protocol():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.testing = True app.testing = True
@ -1295,14 +1430,14 @@ class TestBasicFunctionality(object):
assert sorted(flask.g) == ['bar', 'foo'] assert sorted(flask.g) == ['bar', 'foo']
class TestSubdomain(object): def test_subdomain_basic_support():
def test_basic_support(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config['SERVER_NAME'] = 'localhost' app.config['SERVER_NAME'] = 'localhost'
@app.route('/') @app.route('/')
def normal_index(): def normal_index():
return 'normal index' return 'normal index'
@app.route('/', subdomain='test') @app.route('/', subdomain='test')
def test_index(): def test_index():
return 'test index' return 'test index'
@ -1314,9 +1449,11 @@ class TestSubdomain(object):
rv = c.get('/', 'http://test.localhost/') rv = c.get('/', 'http://test.localhost/')
assert rv.data == b'test index' assert rv.data == b'test index'
def test_subdomain_matching(self):
def test_subdomain_matching():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config['SERVER_NAME'] = 'localhost' app.config['SERVER_NAME'] = 'localhost'
@app.route('/', subdomain='<user>') @app.route('/', subdomain='<user>')
def index(user): def index(user):
return 'index for %s' % user return 'index for %s' % user
@ -1325,9 +1462,11 @@ class TestSubdomain(object):
rv = c.get('/', 'http://mitsuhiko.localhost/') rv = c.get('/', 'http://mitsuhiko.localhost/')
assert rv.data == b'index for mitsuhiko' assert rv.data == b'index for mitsuhiko'
def test_subdomain_matching_with_ports(self):
def test_subdomain_matching_with_ports():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config['SERVER_NAME'] = 'localhost:3000' app.config['SERVER_NAME'] = 'localhost:3000'
@app.route('/', subdomain='<user>') @app.route('/', subdomain='<user>')
def index(user): def index(user):
return 'index for %s' % user return 'index for %s' % user
@ -1336,7 +1475,8 @@ class TestSubdomain(object):
rv = c.get('/', 'http://mitsuhiko.localhost:3000/') rv = c.get('/', 'http://mitsuhiko.localhost:3000/')
assert rv.data == b'index for mitsuhiko' assert rv.data == b'index for mitsuhiko'
def test_multi_route_rules(self):
def test_multi_route_rules():
app = flask.Flask(__name__) app = flask.Flask(__name__)
@app.route('/') @app.route('/')
@ -1349,8 +1489,10 @@ class TestSubdomain(object):
rv = app.test_client().open('/b/') rv = app.test_client().open('/b/')
assert rv.data == b'b' assert rv.data == b'b'
def test_multi_route_class_views(self):
def test_multi_route_class_views():
class View(object): class View(object):
def __init__(self, app): def __init__(self, app):
app.add_url_rule('/', 'index', self.index) app.add_url_rule('/', 'index', self.index)
app.add_url_rule('/<test>/', 'index', self.index) app.add_url_rule('/<test>/', 'index', self.index)

Loading…
Cancel
Save