Browse Source

More DRYing up the test suite (#2325)

pull/2333/head
Christian Stade-Schuldt 8 years ago committed by David Lord
parent
commit
4ec1fbc9f5
  1. 195
      tests/test_basic.py
  2. 8
      tests/test_blueprints.py
  3. 22
      tests/test_cli.py
  4. 2
      tests/test_deprecations.py
  5. 28
      tests/test_helpers.py
  6. 4
      tests/test_regression.py
  7. 12
      tests/test_signals.py
  8. 8
      tests/test_templating.py
  9. 84
      tests/test_testing.py
  10. 38
      tests/test_views.py

195
tests/test_basic.py

@ -951,18 +951,16 @@ def test_http_error_subclass_handling(app, client):
assert client.get('/3').data == b'apple' assert client.get('/3').data == b'apple'
def test_trapping_of_bad_request_key_errors(app): def test_trapping_of_bad_request_key_errors(app, client):
@app.route('/fail') @app.route('/fail')
def fail(): def fail():
flask.request.form['missing_key'] flask.request.form['missing_key']
c = app.test_client() assert client.get('/fail').status_code == 400
assert c.get('/fail').status_code == 400
app.config['TRAP_BAD_REQUEST_ERRORS'] = True app.config['TRAP_BAD_REQUEST_ERRORS'] = True
c = app.test_client()
with pytest.raises(KeyError) as e: with pytest.raises(KeyError) as e:
c.get("/fail") client.get("/fail")
assert e.errisinstance(BadRequest) assert e.errisinstance(BadRequest)
@ -988,17 +986,14 @@ def test_enctype_debug_helper(app, client):
# with statement is important because we leave an exception on the # with statement is important because we leave an exception on the
# stack otherwise and we want to ensure that this is not the case # stack otherwise and we want to ensure that this is not the case
# to not negatively affect other tests. # to not negatively affect other tests.
with client as c: with client:
with pytest.raises(DebugFilesKeyError) as e: with pytest.raises(DebugFilesKeyError) as e:
c.post('/fail', data={'foo': 'index.txt'}) client.post('/fail', data={'foo': 'index.txt'})
assert 'no file contents were transmitted' in str(e.value) assert 'no file contents were transmitted' in str(e.value)
assert 'This was submitted: "index.txt"' in str(e.value) assert 'This was submitted: "index.txt"' in str(e.value)
def test_response_types(): def test_response_types(app, client):
app = flask.Flask(__name__)
app.testing = True
@app.route('/text') @app.route('/text')
def from_text(): def from_text():
return u'Hällo Wörld' return u'Hällo Wörld'
@ -1040,39 +1035,37 @@ def test_response_types():
def from_wsgi(): def from_wsgi():
return NotFound() return NotFound()
c = app.test_client() assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')
assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')
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') rv = client.get('/full_tuple')
assert rv.data == b'Meh' assert rv.data == b'Meh'
assert rv.headers['X-Foo'] == 'Testing' assert rv.headers['X-Foo'] == 'Testing'
assert rv.status_code == 400 assert rv.status_code == 400
assert rv.mimetype == 'text/plain' assert rv.mimetype == 'text/plain'
rv = c.get('/text_headers') rv = client.get('/text_headers')
assert rv.data == b'Hello' assert rv.data == b'Hello'
assert rv.headers['X-Foo'] == 'Test' assert rv.headers['X-Foo'] == 'Test'
assert rv.status_code == 200 assert rv.status_code == 200
assert rv.mimetype == 'text/plain' assert rv.mimetype == 'text/plain'
rv = c.get('/text_status') rv = client.get('/text_status')
assert rv.data == b'Hi, status!' assert rv.data == b'Hi, status!'
assert rv.status_code == 400 assert rv.status_code == 400
assert rv.mimetype == 'text/html' assert rv.mimetype == 'text/html'
rv = c.get('/response_headers') rv = client.get('/response_headers')
assert rv.data == b'Hello world' assert rv.data == b'Hello world'
assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar'] assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']
assert rv.headers['X-Bar'] == 'Foo' assert rv.headers['X-Bar'] == 'Foo'
assert rv.status_code == 404 assert rv.status_code == 404
rv = c.get('/response_status') rv = client.get('/response_status')
assert rv.data == b'Hello world' assert rv.data == b'Hello world'
assert rv.status_code == 500 assert rv.status_code == 500
rv = c.get('/wsgi') rv = client.get('/wsgi')
assert b'Not Found' in rv.data assert b'Not Found' in rv.data
assert rv.status_code == 404 assert rv.status_code == 404
@ -1120,9 +1113,7 @@ def test_response_type_errors():
pytest.raises(TypeError, c.get, '/bad_wsgi') pytest.raises(TypeError, c.get, '/bad_wsgi')
def test_make_response(): def test_make_response(app, req_ctx):
app = flask.Flask(__name__)
with app.test_request_context():
rv = flask.make_response() rv = flask.make_response()
assert rv.status_code == 200 assert rv.status_code == 200
assert rv.data == b'' assert rv.data == b''
@ -1139,9 +1130,7 @@ def test_make_response():
assert rv.mimetype == 'text/html' assert rv.mimetype == 'text/html'
def test_make_response_with_response_instance(): def test_make_response_with_response_instance(app, req_ctx):
app = flask.Flask(__name__)
with app.test_request_context():
rv = flask.make_response( rv = flask.make_response(
flask.jsonify({'msg': 'W00t'}), 400) flask.jsonify({'msg': 'W00t'}), 400)
assert rv.status_code == 400 assert rv.status_code == 400
@ -1162,10 +1151,8 @@ def test_make_response_with_response_instance():
assert rv.headers['X-Foo'] == 'bar' assert rv.headers['X-Foo'] == 'bar'
def test_jsonify_no_prettyprint(): def test_jsonify_no_prettyprint(app, req_ctx):
app = flask.Flask(__name__)
app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False}) app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})
with app.test_request_context():
compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n' compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'
uncompressed_msg = { uncompressed_msg = {
"msg": { "msg": {
@ -1179,10 +1166,8 @@ def test_jsonify_no_prettyprint():
assert rv.data == compressed_msg assert rv.data == compressed_msg
def test_jsonify_prettyprint(): def test_jsonify_prettyprint(app, req_ctx):
app = flask.Flask(__name__)
app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True}) app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})
with app.test_request_context():
compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"} compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}
pretty_response = \ pretty_response = \
b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n' b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'
@ -1192,10 +1177,8 @@ def test_jsonify_prettyprint():
assert rv.data == pretty_response assert rv.data == pretty_response
def test_jsonify_mimetype(): def test_jsonify_mimetype(app, req_ctx):
app = flask.Flask(__name__)
app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'}) app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})
with app.test_request_context():
msg = { msg = {
"msg": {"submsg": "W00t"}, "msg": {"submsg": "W00t"},
} }
@ -1204,30 +1187,23 @@ def test_jsonify_mimetype():
assert rv.mimetype == 'application/vnd.api+json' assert rv.mimetype == 'application/vnd.api+json'
def test_jsonify_args_and_kwargs_check(): def test_jsonify_args_and_kwargs_check(app, req_ctx):
app = flask.Flask(__name__)
with app.test_request_context():
with pytest.raises(TypeError) as e: with pytest.raises(TypeError) as e:
flask.jsonify('fake args', kwargs='fake') flask.jsonify('fake args', kwargs='fake')
assert 'behavior undefined' in str(e.value) assert 'behavior undefined' in str(e.value)
def test_url_generation(): def test_url_generation(app, req_ctx):
app = flask.Flask(__name__)
@app.route('/hello/<name>', methods=['POST']) @app.route('/hello/<name>', methods=['POST'])
def hello(): def hello():
pass pass
with app.test_request_context():
assert flask.url_for('hello', name='test x') == '/hello/test%20x' assert flask.url_for('hello', name='test x') == '/hello/test%20x'
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(): def test_build_error_handler(app):
app = flask.Flask(__name__)
# Test base case, a URL which results in a BuildError. # Test base case, a URL which results in a BuildError.
with app.test_request_context(): with app.test_request_context():
pytest.raises(BuildError, flask.url_for, 'spam') pytest.raises(BuildError, flask.url_for, 'spam')
@ -1254,9 +1230,7 @@ def test_build_error_handler():
assert flask.url_for('spam') == '/test_handler/' assert flask.url_for('spam') == '/test_handler/'
def test_build_error_handler_reraise(): def test_build_error_handler_reraise(app):
app = flask.Flask(__name__)
# Test a custom handler which reraises the BuildError # Test a custom handler which reraises the BuildError
def handler_raises_build_error(error, endpoint, values): def handler_raises_build_error(error, endpoint, values):
raise error raise error
@ -1267,9 +1241,7 @@ def test_build_error_handler_reraise():
pytest.raises(BuildError, flask.url_for, 'not.existing') pytest.raises(BuildError, flask.url_for, 'not.existing')
def test_url_for_passes_special_values_to_build_error_handler(): def test_url_for_passes_special_values_to_build_error_handler(app):
app = flask.Flask(__name__)
@app.url_build_error_handlers.append @app.url_build_error_handlers.append
def handler(error, endpoint, values): def handler(error, endpoint, values):
assert values == { assert values == {
@ -1284,7 +1256,7 @@ def test_url_for_passes_special_values_to_build_error_handler():
flask.url_for('/') flask.url_for('/')
def test_custom_converters(): def test_custom_converters(app, client):
from werkzeug.routing import BaseConverter from werkzeug.routing import BaseConverter
class ListConverter(BaseConverter): class ListConverter(BaseConverter):
@ -1295,21 +1267,17 @@ def test_custom_converters():
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.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() assert client.get('/1,2,3').data == b'1|2|3'
assert c.get('/1,2,3').data == b'1|2|3'
def test_static_files(): def test_static_files(app, client):
app = flask.Flask(__name__) rv = client.get('/static/index.html')
app.testing = True
rv = app.test_client().get('/static/index.html')
assert rv.status_code == 200 assert rv.status_code == 200
assert rv.data.strip() == b'<h1>Hello World!</h1>' assert rv.data.strip() == b'<h1>Hello World!</h1>'
with app.test_request_context(): with app.test_request_context():
@ -1366,8 +1334,7 @@ def test_request_locals():
assert not flask.g assert not flask.g
def test_test_app_proper_environ(): def test_test_app_proper_environ(app, client):
app = flask.Flask(__name__)
app.config.update( app.config.update(
SERVER_NAME='localhost.localdomain:5000' SERVER_NAME='localhost.localdomain:5000'
) )
@ -1380,22 +1347,22 @@ def test_test_app_proper_environ():
def subdomain(): def subdomain():
return 'Foo SubDomain' return 'Foo SubDomain'
rv = app.test_client().get('/') rv = client.get('/')
assert rv.data == b'Foo' assert rv.data == b'Foo'
rv = app.test_client().get('/', 'http://localhost.localdomain:5000') rv = client.get('/', 'http://localhost.localdomain:5000')
assert rv.data == b'Foo' assert rv.data == b'Foo'
rv = app.test_client().get('/', 'https://localhost.localdomain:5000') rv = client.get('/', 'https://localhost.localdomain:5000')
assert rv.data == b'Foo' assert rv.data == b'Foo'
app.config.update(SERVER_NAME='localhost.localdomain') app.config.update(SERVER_NAME='localhost.localdomain')
rv = app.test_client().get('/', 'https://localhost.localdomain') rv = client.get('/', 'https://localhost.localdomain')
assert rv.data == b'Foo' assert rv.data == b'Foo'
try: try:
app.config.update(SERVER_NAME='localhost.localdomain:443') app.config.update(SERVER_NAME='localhost.localdomain:443')
rv = app.test_client().get('/', 'https://localhost.localdomain') rv = client.get('/', 'https://localhost.localdomain')
# Werkzeug 0.8 # Werkzeug 0.8
assert rv.status_code == 404 assert rv.status_code == 404
except ValueError as e: except ValueError as e:
@ -1408,7 +1375,7 @@ def test_test_app_proper_environ():
try: try:
app.config.update(SERVER_NAME='localhost.localdomain') app.config.update(SERVER_NAME='localhost.localdomain')
rv = app.test_client().get('/', 'http://foo.localhost') rv = client.get('/', 'http://foo.localhost')
# Werkzeug 0.8 # Werkzeug 0.8
assert rv.status_code == 404 assert rv.status_code == 404
except ValueError as e: except ValueError as e:
@ -1419,26 +1386,24 @@ def test_test_app_proper_environ():
"server name from the WSGI environment ('foo.localhost')" "server name from the WSGI environment ('foo.localhost')"
) )
rv = app.test_client().get('/', 'http://foo.localhost.localdomain') rv = client.get('/', 'http://foo.localhost.localdomain')
assert rv.data == b'Foo SubDomain' assert rv.data == b'Foo SubDomain'
def test_exception_propagation(): def test_exception_propagation(app, client):
def apprunner(config_key): def apprunner(config_key):
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
c = app.test_client()
if config_key is not None: if config_key is not None:
app.config[config_key] = True app.config[config_key] = True
with pytest.raises(Exception): with pytest.raises(Exception):
c.get('/') client.get('/')
else: else:
assert c.get('/').status_code == 500 assert client.get('/').status_code == 500
# we have to run this test in an isolated thread because if the # we have to run this test in an isolated thread because if the
# debug flag is set to true and an exception happens the context is # debug flag is set to true and an exception happens the context is
@ -1455,21 +1420,19 @@ def test_exception_propagation():
@pytest.mark.parametrize('use_reloader', [True, False]) @pytest.mark.parametrize('use_reloader', [True, False])
@pytest.mark.parametrize('propagate_exceptions', [None, True, False]) @pytest.mark.parametrize('propagate_exceptions', [None, True, False])
def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger, def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,
use_reloader, propagate_exceptions): use_reloader, propagate_exceptions, app):
rv = {} rv = {}
# Mocks werkzeug.serving.run_simple method # Mocks werkzeug.serving.run_simple method
def run_simple_mock(*args, **kwargs): def run_simple_mock(*args, **kwargs):
rv['passthrough_errors'] = kwargs.get('passthrough_errors') rv['passthrough_errors'] = kwargs.get('passthrough_errors')
app = flask.Flask(__name__)
monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock) monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)
app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions
app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader) app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)
def test_max_content_length(): def test_max_content_length(app, client):
app = flask.Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 64 app.config['MAX_CONTENT_LENGTH'] = 64
@app.before_request @app.before_request
@ -1486,13 +1449,11 @@ def test_max_content_length():
def catcher(error): def catcher(error):
return '42' return '42'
c = app.test_client() rv = client.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(): def test_url_processors(app, client):
app = flask.Flask(__name__)
@app.url_defaults @app.url_defaults
def add_language_code(endpoint, values): def add_language_code(endpoint, values):
@ -1516,15 +1477,12 @@ def test_url_processors():
def something_else(): def something_else():
return flask.url_for('about', lang_code='en') return flask.url_for('about', lang_code='en')
c = app.test_client() assert client.get('/de/').data == b'/de/about'
assert client.get('/de/about').data == b'/foo'
assert c.get('/de/').data == b'/de/about' assert client.get('/foo').data == b'/en/about'
assert c.get('/de/about').data == b'/foo'
assert c.get('/foo').data == b'/en/about'
def test_inject_blueprint_url_defaults(): def test_inject_blueprint_url_defaults(app):
app = flask.Flask(__name__)
bp = flask.Blueprint('foo.bar.baz', __name__, bp = flask.Blueprint('foo.bar.baz', __name__,
template_folder='template') template_folder='template')
@ -1549,21 +1507,16 @@ def test_inject_blueprint_url_defaults():
assert url == expected assert url == expected
def test_nonascii_pathinfo(): def test_nonascii_pathinfo(app, client):
app = flask.Flask(__name__)
app.testing = True
@app.route(u'/киртест') @app.route(u'/киртест')
def index(): def index():
return 'Hello World!' return 'Hello World!'
c = app.test_client() rv = client.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(): def test_debug_mode_complains_after_first_request(app, client):
app = flask.Flask(__name__)
app.debug = True app.debug = True
@app.route('/') @app.route('/')
@ -1571,7 +1524,7 @@ def test_debug_mode_complains_after_first_request():
return 'Awesome' return 'Awesome'
assert not app.got_first_request assert not app.got_first_request
assert app.test_client().get('/').data == b'Awesome' assert client.get('/').data == b'Awesome'
with pytest.raises(AssertionError) as e: with pytest.raises(AssertionError) as e:
@app.route('/foo') @app.route('/foo')
def broken(): def broken():
@ -1584,39 +1537,34 @@ def test_debug_mode_complains_after_first_request():
def working(): def working():
return 'Meh' return 'Meh'
assert app.test_client().get('/foo').data == b'Meh' assert client.get('/foo').data == b'Meh'
assert app.got_first_request assert app.got_first_request
def test_before_first_request_functions(): def test_before_first_request_functions(app, client):
got = [] got = []
app = flask.Flask(__name__)
@app.before_first_request @app.before_first_request
def foo(): def foo():
got.append(42) got.append(42)
c = app.test_client() client.get('/')
c.get('/')
assert got == [42] assert got == [42]
c.get('/') client.get('/')
assert got == [42] assert got == [42]
assert app.got_first_request assert app.got_first_request
def test_before_first_request_functions_concurrent(): def test_before_first_request_functions_concurrent(app, client):
got = [] got = []
app = flask.Flask(__name__)
@app.before_first_request @app.before_first_request
def foo(): def foo():
time.sleep(0.2) time.sleep(0.2)
got.append(42) got.append(42)
c = app.test_client()
def get_and_assert(): def get_and_assert():
c.get("/") client.get("/")
assert got == [42] assert got == [42]
t = Thread(target=get_and_assert) t = Thread(target=get_and_assert)
@ -1626,32 +1574,30 @@ def test_before_first_request_functions_concurrent():
assert app.got_first_request assert app.got_first_request
def test_routing_redirect_debugging(): def test_routing_redirect_debugging(app, client):
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'
with app.test_client() as c: with client:
with pytest.raises(AssertionError) as e: with pytest.raises(AssertionError) as e:
c.post('/foo', data={}) client.post('/foo', data={})
assert 'http://localhost/foo/' in str(e) assert 'http://localhost/foo/' in str(e)
assert ('Make sure to directly send ' assert ('Make sure to directly send '
'your POST-request to this URL') in str(e) 'your POST-request to this URL') in str(e)
rv = c.get('/foo', data={}, follow_redirects=True) rv = client.get('/foo', data={}, follow_redirects=True)
assert rv.data == b'success' assert rv.data == b'success'
app.debug = False app.debug = False
with app.test_client() as c: with client:
rv = c.post('/foo', data={}, follow_redirects=True) rv = client.post('/foo', data={}, follow_redirects=True)
assert rv.data == b'success' assert rv.data == b'success'
def test_route_decorator_custom_endpoint(): def test_route_decorator_custom_endpoint(app, client):
app = flask.Flask(__name__)
app.debug = True app.debug = True
@app.route('/foo/') @app.route('/foo/')
@ -1671,24 +1617,21 @@ def test_route_decorator_custom_endpoint():
assert flask.url_for('bar') == '/bar/' assert flask.url_for('bar') == '/bar/'
assert flask.url_for('123') == '/bar/123' assert flask.url_for('123') == '/bar/123'
c = app.test_client() assert client.get('/foo/').data == b'foo'
assert c.get('/foo/').data == b'foo' assert client.get('/bar/').data == b'bar'
assert c.get('/bar/').data == b'bar' assert client.get('/bar/123').data == b'123'
assert c.get('/bar/123').data == b'123'
def test_preserve_only_once(): def test_preserve_only_once(app, client):
app = flask.Flask(__name__)
app.debug = True app.debug = True
@app.route('/fail') @app.route('/fail')
def fail_func(): def fail_func():
1 // 0 1 // 0
c = app.test_client()
for x in range(3): for x in range(3):
with pytest.raises(ZeroDivisionError): with pytest.raises(ZeroDivisionError):
c.get('/fail') client.get('/fail')
assert flask._request_ctx_stack.top is not None assert flask._request_ctx_stack.top is not None
assert flask._app_ctx_stack.top is not None assert flask._app_ctx_stack.top is not None

8
tests/test_blueprints.py

@ -718,17 +718,21 @@ def test_template_global(app):
rv = flask.render_template_string('{{ get_answer() }}') rv = flask.render_template_string('{{ get_answer() }}')
assert rv == '42' assert rv == '42'
def test_request_processing(app, client): def test_request_processing(app, client):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
evts = [] evts = []
@bp.before_request @bp.before_request
def before_bp(): def before_bp():
evts.append('before') evts.append('before')
@bp.after_request @bp.after_request
def after_bp(response): def after_bp(response):
response.data += b'|after' response.data += b'|after'
evts.append('after') evts.append('after')
return response return response
@bp.teardown_request @bp.teardown_request
def teardown_bp(exc): def teardown_bp(exc):
evts.append('teardown') evts.append('teardown')
@ -745,6 +749,7 @@ def test_request_processing(app, client):
assert rv.data == b'request|after' assert rv.data == b'request|after'
assert evts == ['before', 'after', 'teardown'] assert evts == ['before', 'after', 'teardown']
def test_app_request_processing(app, client): def test_app_request_processing(app, client):
bp = flask.Blueprint('bp', __name__) bp = flask.Blueprint('bp', __name__)
evts = [] evts = []
@ -752,14 +757,17 @@ def test_app_request_processing(app, client):
@bp.before_app_first_request @bp.before_app_first_request
def before_first_request(): def before_first_request():
evts.append('first') evts.append('first')
@bp.before_app_request @bp.before_app_request
def before_app(): def before_app():
evts.append('before') evts.append('before')
@bp.after_app_request @bp.after_app_request
def after_app(response): def after_app(response):
response.data += b'|after' response.data += b'|after'
evts.append('after') evts.append('after')
return response return response
@bp.teardown_app_request @bp.teardown_app_request
def teardown_app(exc): def teardown_app(exc):
evts.append('teardown') evts.append('teardown')

22
tests/test_cli.py

@ -40,22 +40,27 @@ def test_cli_name(test_apps):
def test_find_best_app(test_apps): def test_find_best_app(test_apps):
"""Test if `find_best_app` behaves as expected with different combinations of input.""" """Test if `find_best_app` behaves as expected with different combinations of input."""
script_info = ScriptInfo() script_info = ScriptInfo()
class Module: class Module:
app = Flask('appname') app = Flask('appname')
assert find_best_app(script_info, Module) == Module.app assert find_best_app(script_info, Module) == Module.app
class Module: class Module:
application = Flask('appname') application = Flask('appname')
assert find_best_app(script_info, Module) == Module.application assert find_best_app(script_info, Module) == Module.application
class Module: class Module:
myapp = Flask('appname') myapp = Flask('appname')
assert find_best_app(script_info, Module) == Module.myapp assert find_best_app(script_info, Module) == Module.myapp
class Module: class Module:
@staticmethod @staticmethod
def create_app(): def create_app():
return Flask('appname') return Flask('appname')
assert isinstance(find_best_app(script_info, Module), Flask) assert isinstance(find_best_app(script_info, Module), Flask)
assert find_best_app(script_info, Module).name == 'appname' assert find_best_app(script_info, Module).name == 'appname'
@ -63,6 +68,7 @@ def test_find_best_app(test_apps):
@staticmethod @staticmethod
def create_app(foo): def create_app(foo):
return Flask('appname') return Flask('appname')
assert isinstance(find_best_app(script_info, Module), Flask) assert isinstance(find_best_app(script_info, Module), Flask)
assert find_best_app(script_info, Module).name == 'appname' assert find_best_app(script_info, Module).name == 'appname'
@ -70,6 +76,7 @@ def test_find_best_app(test_apps):
@staticmethod @staticmethod
def create_app(foo=None, script_info=None): def create_app(foo=None, script_info=None):
return Flask('appname') return Flask('appname')
assert isinstance(find_best_app(script_info, Module), Flask) assert isinstance(find_best_app(script_info, Module), Flask)
assert find_best_app(script_info, Module).name == 'appname' assert find_best_app(script_info, Module).name == 'appname'
@ -77,36 +84,44 @@ def test_find_best_app(test_apps):
@staticmethod @staticmethod
def make_app(): def make_app():
return Flask('appname') return Flask('appname')
assert isinstance(find_best_app(script_info, Module), Flask) assert isinstance(find_best_app(script_info, Module), Flask)
assert find_best_app(script_info, Module).name == 'appname' assert find_best_app(script_info, Module).name == 'appname'
class Module: class Module:
myapp = Flask('appname1') myapp = Flask('appname1')
@staticmethod @staticmethod
def create_app(): def create_app():
return Flask('appname2') return Flask('appname2')
assert find_best_app(script_info, Module) == Module.myapp assert find_best_app(script_info, Module) == Module.myapp
class Module: class Module:
myapp = Flask('appname1') myapp = Flask('appname1')
@staticmethod @staticmethod
def create_app(): def create_app():
return Flask('appname2') return Flask('appname2')
assert find_best_app(script_info, Module) == Module.myapp assert find_best_app(script_info, Module) == Module.myapp
class Module: class Module:
pass pass
pytest.raises(NoAppException, find_best_app, script_info, Module) pytest.raises(NoAppException, find_best_app, script_info, Module)
class Module: class Module:
myapp1 = Flask('appname1') myapp1 = Flask('appname1')
myapp2 = Flask('appname2') myapp2 = Flask('appname2')
pytest.raises(NoAppException, find_best_app, script_info, Module) pytest.raises(NoAppException, find_best_app, script_info, Module)
class Module: class Module:
@staticmethod @staticmethod
def create_app(foo, bar): def create_app(foo, bar):
return Flask('appname2') return Flask('appname2')
pytest.raises(NoAppException, find_best_app, script_info, Module) pytest.raises(NoAppException, find_best_app, script_info, Module)
@ -163,10 +178,13 @@ def test_get_version(test_apps, capsys):
"""Test of get_version.""" """Test of get_version."""
from flask import __version__ as flask_ver from flask import __version__ as flask_ver
from sys import version as py_ver from sys import version as py_ver
class MockCtx(object): class MockCtx(object):
resilient_parsing = False resilient_parsing = False
color = None color = None
def exit(self): return def exit(self): return
ctx = MockCtx() ctx = MockCtx()
get_version(ctx, None, "test") get_version(ctx, None, "test")
out, err = capsys.readouterr() out, err = capsys.readouterr()
@ -191,6 +209,7 @@ def test_scriptinfo(test_apps):
def test_with_appcontext(runner): def test_with_appcontext(runner):
"""Test of with_appcontext.""" """Test of with_appcontext."""
@click.command() @click.command()
@with_appcontext @with_appcontext
def testcmd(): def testcmd():
@ -205,6 +224,7 @@ def test_with_appcontext(runner):
def test_appgroup(runner): def test_appgroup(runner):
"""Test of with_appcontext.""" """Test of with_appcontext."""
@click.group(cls=AppGroup) @click.group(cls=AppGroup)
def cli(): def cli():
pass pass
@ -234,6 +254,7 @@ def test_appgroup(runner):
def test_flaskgroup(runner): def test_flaskgroup(runner):
"""Test FlaskGroup.""" """Test FlaskGroup."""
def create_app(info): def create_app(info):
return Flask("flaskgroup") return Flask("flaskgroup")
@ -252,6 +273,7 @@ def test_flaskgroup(runner):
def test_print_exceptions(runner): def test_print_exceptions(runner):
"""Print the stacktrace if the CLI.""" """Print the stacktrace if the CLI."""
def create_app(info): def create_app(info):
raise Exception("oh no") raise Exception("oh no")
return Flask("flaskgroup") return Flask("flaskgroup")

2
tests/test_deprecations.py

@ -17,7 +17,6 @@ import flask
class TestRequestDeprecation(object): class TestRequestDeprecation(object):
def test_request_json(self, recwarn, app, client): def test_request_json(self, recwarn, app, client):
"""Request.json is deprecated""" """Request.json is deprecated"""
app.testing = True
@app.route('/', methods=['POST']) @app.route('/', methods=['POST'])
def index(): def index():
@ -30,7 +29,6 @@ class TestRequestDeprecation(object):
def test_request_module(self, recwarn, app, client): def test_request_module(self, recwarn, app, client):
"""Request.module is deprecated""" """Request.module is deprecated"""
app.testing = True
@app.route('/') @app.route('/')
def index(): def index():

28
tests/test_helpers.py

@ -85,7 +85,6 @@ class TestJSON(object):
assert rv.data == b'foo' assert rv.data == b'foo'
def test_json_body_encoding(self, app, client): def test_json_body_encoding(self, app, client):
app.testing = True
@app.route('/') @app.route('/')
def index(): def index():
@ -241,7 +240,6 @@ class TestJSON(object):
return X(obj['_foo']) return X(obj['_foo'])
return obj return obj
app.testing = True
app.json_encoder = MyEncoder app.json_encoder = MyEncoder
app.json_decoder = MyDecoder app.json_decoder = MyDecoder
@ -285,7 +283,6 @@ class TestJSON(object):
def index(): def index():
return flask.json.dumps(flask.request.get_json()['x']) return flask.json.dumps(flask.request.get_json()['x'])
app.testing = True
app.register_blueprint(bp) app.register_blueprint(bp)
rv = client.post('/bp', data=flask.json.dumps({ rv = client.post('/bp', data=flask.json.dumps({
@ -293,11 +290,10 @@ class TestJSON(object):
}), content_type='application/json') }), content_type='application/json')
assert rv.data == b'"<42>"' assert rv.data == b'"<42>"'
def test_modified_url_encoding(self, app): def test_modified_url_encoding(self, app, client):
class ModifiedRequest(flask.Request): class ModifiedRequest(flask.Request):
url_charset = 'euc-kr' url_charset = 'euc-kr'
app.testing = True
app.request_class = ModifiedRequest app.request_class = ModifiedRequest
app.url_map.charset = 'euc-kr' app.url_map.charset = 'euc-kr'
@ -305,7 +301,7 @@ class TestJSON(object):
def index(): def index():
return flask.request.args['foo'] return flask.request.args['foo']
rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr')) rv = client.get(u'/?foo=정상처리'.encode('euc-kr'))
assert rv.status_code == 200 assert rv.status_code == 200
assert rv.data == u'정상처리'.encode('utf-8') assert rv.data == u'정상처리'.encode('utf-8')
@ -313,7 +309,6 @@ class TestJSON(object):
test_modified_url_encoding = None test_modified_url_encoding = None
def test_json_key_sorting(self, app, client): def test_json_key_sorting(self, app, client):
app.testing = True
app.debug = True app.debug = True
assert app.config['JSON_SORT_KEYS'] == True assert app.config['JSON_SORT_KEYS'] == True
@ -538,7 +533,6 @@ class TestSendfile(object):
rv.close() rv.close()
def test_attachment(self, app, req_ctx): def test_attachment(self, app, req_ctx):
app = flask.Flask(__name__)
with open(os.path.join(app.root_path, 'static/index.html')) as f: 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,
@ -619,7 +613,6 @@ class TestSendfile(object):
rv.close() rv.close()
def test_send_from_directory(self, app, req_ctx): def test_send_from_directory(self, app, req_ctx):
app.testing = True
app.root_path = os.path.join(os.path.dirname(__file__), app.root_path = os.path.join(os.path.dirname(__file__),
'test_apps', 'subdomaintestmodule') 'test_apps', 'subdomaintestmodule')
rv = flask.send_from_directory('static', 'hello.txt') rv = flask.send_from_directory('static', 'hello.txt')
@ -628,7 +621,6 @@ class TestSendfile(object):
rv.close() rv.close()
def test_send_from_directory_bad_request(self, app, req_ctx): def test_send_from_directory_bad_request(self, app, req_ctx):
app.testing = True
app.root_path = os.path.join(os.path.dirname(__file__), app.root_path = os.path.join(os.path.dirname(__file__),
'test_apps', 'subdomaintestmodule') 'test_apps', 'subdomaintestmodule')
@ -645,8 +637,7 @@ class TestLogging(object):
app.logger_name = __name__ + '/test_logger_cache' app.logger_name = __name__ + '/test_logger_cache'
assert app.logger is not logger1 assert app.logger is not logger1
def test_debug_log(self, capsys): def test_debug_log(self, capsys, app, client):
app = flask.Flask(__name__)
app.debug = True app.debug = True
@app.route('/') @app.route('/')
@ -659,8 +650,8 @@ class TestLogging(object):
def exc(): def exc():
1 // 0 1 // 0
with app.test_client() as c: with client:
c.get('/') client.get('/')
out, err = capsys.readouterr() out, err = capsys.readouterr()
assert 'WARNING in test_helpers [' in err assert 'WARNING in test_helpers [' in err
assert os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in err assert os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in err
@ -668,7 +659,7 @@ class TestLogging(object):
assert 'this is a debug statement' in err assert 'this is a debug statement' in err
with pytest.raises(ZeroDivisionError): with pytest.raises(ZeroDivisionError):
c.get('/exc') client.get('/exc')
def test_debug_log_override(self, app): def test_debug_log_override(self, app):
app.debug = True app.debug = True
@ -676,7 +667,7 @@ class TestLogging(object):
app.logger.level = 10 app.logger.level = 10
assert app.logger.level == 10 assert app.logger.level == 10
def test_exception_logging(self, app): def test_exception_logging(self, app, client):
out = StringIO() out = StringIO()
app.config['LOGGER_HANDLER_POLICY'] = 'never' app.config['LOGGER_HANDLER_POLICY'] = 'never'
app.logger_name = 'flask_tests/test_exception_logging' app.logger_name = 'flask_tests/test_exception_logging'
@ -687,7 +678,7 @@ class TestLogging(object):
def index(): def index():
1 // 0 1 // 0
rv = app.test_client().get('/') rv = client.get('/')
assert rv.status_code == 500 assert rv.status_code == 500
assert b'Internal Server Error' in rv.data assert b'Internal Server Error' in rv.data
@ -808,7 +799,6 @@ class TestNoImports(object):
class TestStreaming(object): class TestStreaming(object):
def test_streaming_with_context(self, app, client): def test_streaming_with_context(self, app, client):
app.testing = True
@app.route('/') @app.route('/')
def index(): def index():
@ -823,7 +813,6 @@ class TestStreaming(object):
assert rv.data == b'Hello World!' assert rv.data == b'Hello World!'
def test_streaming_with_context_as_decorator(self, app, client): def test_streaming_with_context_as_decorator(self, app, client):
app.testing = True
@app.route('/') @app.route('/')
def index(): def index():
@ -839,7 +828,6 @@ class TestStreaming(object):
assert rv.data == b'Hello World!' assert rv.data == b'Hello World!'
def test_streaming_with_context_and_custom_close(self, app, client): def test_streaming_with_context_and_custom_close(self, app, client):
app.testing = True
called = [] called = []
class Wrapper(object): class Wrapper(object):

4
tests/test_regression.py

@ -76,11 +76,9 @@ def test_safe_join_toplevel_pardir():
safe_join('/foo', '..') safe_join('/foo', '..')
def test_aborting(): def test_aborting(app):
class Foo(Exception): class Foo(Exception):
whatever = 42 whatever = 42
app = flask.Flask(__name__)
app.testing = True
@app.errorhandler(Foo) @app.errorhandler(Foo)
def handle_foo(e): def handle_foo(e):

12
tests/test_signals.py

@ -18,15 +18,13 @@ except ImportError:
import flask import flask
pytestmark = pytest.mark.skipif( pytestmark = pytest.mark.skipif(
blinker is None, blinker is None,
reason='Signals require the blinker library.' reason='Signals require the blinker library.'
) )
def test_template_rendered():
app = flask.Flask(__name__)
def test_template_rendered(app, client):
@app.route('/') @app.route('/')
def index(): def index():
return flask.render_template('simple_template.html', whiskey=42) return flask.render_template('simple_template.html', whiskey=42)
@ -38,7 +36,7 @@ def test_template_rendered():
flask.template_rendered.connect(record, app) flask.template_rendered.connect(record, app)
try: try:
app.test_client().get('/') client.get('/')
assert len(recorded) == 1 assert len(recorded) == 1
template, context = recorded[0] template, context = recorded[0]
assert template.name == 'simple_template.html' assert template.name == 'simple_template.html'
@ -46,6 +44,7 @@ def test_template_rendered():
finally: finally:
flask.template_rendered.disconnect(record, app) flask.template_rendered.disconnect(record, app)
def test_before_render_template(): def test_before_render_template():
app = flask.Flask(__name__) app = flask.Flask(__name__)
@ -70,6 +69,7 @@ def test_before_render_template():
finally: finally:
flask.before_render_template.disconnect(record, app) flask.before_render_template.disconnect(record, app)
def test_request_signals(): def test_request_signals():
app = flask.Flask(__name__) app = flask.Flask(__name__)
calls = [] calls = []
@ -109,6 +109,7 @@ def test_request_signals():
flask.request_started.disconnect(before_request_signal, app) flask.request_started.disconnect(before_request_signal, app)
flask.request_finished.disconnect(after_request_signal, app) flask.request_finished.disconnect(after_request_signal, app)
def test_request_exception_signal(): def test_request_exception_signal():
app = flask.Flask(__name__) app = flask.Flask(__name__)
recorded = [] recorded = []
@ -128,6 +129,7 @@ def test_request_exception_signal():
finally: finally:
flask.got_request_exception.disconnect(record, app) flask.got_request_exception.disconnect(record, app)
def test_appcontext_signals(): def test_appcontext_signals():
app = flask.Flask(__name__) app = flask.Flask(__name__)
recorded = [] recorded = []
@ -154,6 +156,7 @@ def test_appcontext_signals():
flask.appcontext_pushed.disconnect(record_push, app) flask.appcontext_pushed.disconnect(record_push, app)
flask.appcontext_popped.disconnect(record_pop, app) flask.appcontext_popped.disconnect(record_pop, app)
def test_flash_signal(): def test_flash_signal():
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config['SECRET_KEY'] = 'secret' app.config['SECRET_KEY'] = 'secret'
@ -180,6 +183,7 @@ def test_flash_signal():
finally: finally:
flask.message_flashed.disconnect(record, app) flask.message_flashed.disconnect(record, app)
def test_appcontext_tearing_down_signal(): def test_appcontext_tearing_down_signal():
app = flask.Flask(__name__) app = flask.Flask(__name__)
recorded = [] recorded = []

8
tests/test_templating.py

@ -16,7 +16,7 @@ import logging
from jinja2 import TemplateNotFound from jinja2 import TemplateNotFound
def test_context_processing(app): def test_context_processing(app, client):
@app.context_processor @app.context_processor
def context_processor(): def context_processor():
return {'injected_value': 42} return {'injected_value': 42}
@ -25,7 +25,7 @@ def test_context_processing(app):
def index(): def index():
return flask.render_template('context_template.html', value=23) return flask.render_template('context_template.html', value=23)
rv = app.test_client().get('/') rv = client.get('/')
assert rv.data == b'<p>23|42' assert rv.data == b'<p>23|42'
@ -253,7 +253,7 @@ def test_add_template_test_with_name(app):
assert app.jinja_env.tests['boolean'](False) assert app.jinja_env.tests['boolean'](False)
def test_template_test_with_template(app): def test_template_test_with_template(app, client):
@app.template_test() @app.template_test()
def boolean(value): def boolean(value):
return isinstance(value, bool) return isinstance(value, bool)
@ -262,7 +262,7 @@ def test_template_test_with_template(app):
def index(): def index():
return flask.render_template('template_test.html', value=False) return flask.render_template('template_test.html', value=False)
rv = app.test_client().get('/') rv = client.get('/')
assert b'Success!' in rv.data assert b'Success!' in rv.data

84
tests/test_testing.py

@ -38,14 +38,12 @@ def test_environ_defaults(app, client, app_ctx, req_ctx):
ctx = app.test_request_context() ctx = app.test_request_context()
assert ctx.request.url == 'http://localhost/' assert ctx.request.url == 'http://localhost/'
with app.test_client() as c: with client:
rv = c.get('/') rv = client.get('/')
assert rv.data == b'http://localhost/' assert rv.data == b'http://localhost/'
def test_environ_base_default(app, client, app_ctx): def test_environ_base_default(app, client, app_ctx):
app.testing = True
@app.route('/') @app.route('/')
def index(): def index():
flask.g.user_agent = flask.request.headers["User-Agent"] flask.g.user_agent = flask.request.headers["User-Agent"]
@ -89,39 +87,39 @@ def test_redirect_keep_session(app, client, app_ctx):
def get_session(): def get_session():
return flask.session.get('data', '<missing>') return flask.session.get('data', '<missing>')
with client as c: with client:
rv = c.get('/getsession') rv = client.get('/getsession')
assert rv.data == b'<missing>' assert rv.data == b'<missing>'
rv = c.get('/') rv = client.get('/')
assert rv.data == b'index' assert rv.data == b'index'
assert flask.session.get('data') == 'foo' assert flask.session.get('data') == 'foo'
rv = c.post('/', data={}, follow_redirects=True) rv = client.post('/', data={}, follow_redirects=True)
assert rv.data == b'foo' assert rv.data == b'foo'
# This support requires a new Werkzeug version # This support requires a new Werkzeug version
if not hasattr(c, 'redirect_client'): if not hasattr(client, 'redirect_client'):
assert flask.session.get('data') == 'foo' assert flask.session.get('data') == 'foo'
rv = c.get('/getsession') rv = client.get('/getsession')
assert rv.data == b'foo' assert rv.data == b'foo'
def test_session_transactions(app): def test_session_transactions(app, client):
app.secret_key = 'testing' app.secret_key = 'testing'
@app.route('/') @app.route('/')
def index(): def index():
return text_type(flask.session['foo']) return text_type(flask.session['foo'])
with app.test_client() as c: with client:
with c.session_transaction() as sess: with client.session_transaction() as sess:
assert len(sess) == 0 assert len(sess) == 0
sess['foo'] = [42] sess['foo'] = [42]
assert len(sess) == 1 assert len(sess) == 1
rv = c.get('/') rv = client.get('/')
assert rv.data == b'[42]' assert rv.data == b'[42]'
with c.session_transaction() as sess: with client.session_transaction() as sess:
assert len(sess) == 1 assert len(sess) == 1
assert sess['foo'] == [42] assert sess['foo'] == [42]
@ -146,6 +144,7 @@ def test_session_transactions_keep_context(app, client, req_ctx):
with client.session_transaction(): with client.session_transaction():
assert req is flask.request._get_current_object() assert req is flask.request._get_current_object()
def test_session_transaction_needs_cookies(app): def test_session_transaction_needs_cookies(app):
c = app.test_client(use_cookies=False) c = app.test_client(use_cookies=False)
with pytest.raises(RuntimeError) as e: with pytest.raises(RuntimeError) as e:
@ -154,9 +153,9 @@ def test_session_transaction_needs_cookies(app):
assert 'cookies' in str(e.value) assert 'cookies' in str(e.value)
def test_test_client_context_binding(): def test_test_client_context_binding(app, client):
app = flask.Flask(__name__)
app.config['LOGGER_HANDLER_POLICY'] = 'never' app.config['LOGGER_HANDLER_POLICY'] = 'never'
app.testing = False
@app.route('/') @app.route('/')
def index(): def index():
@ -167,13 +166,13 @@ def test_test_client_context_binding():
def other(): def other():
1 // 0 1 // 0
with app.test_client() as c: with client:
resp = c.get('/') resp = client.get('/')
assert flask.g.value == 42 assert flask.g.value == 42
assert resp.data == b'Hello World!' assert resp.data == b'Hello World!'
assert resp.status_code == 200 assert resp.status_code == 200
resp = c.get('/other') resp = client.get('/other')
assert not hasattr(flask.g, 'value') assert not hasattr(flask.g, 'value')
assert b'Internal Server Error' in resp.data assert b'Internal Server Error' in resp.data
assert resp.status_code == 500 assert resp.status_code == 500
@ -187,58 +186,52 @@ def test_test_client_context_binding():
raise AssertionError('some kind of exception expected') raise AssertionError('some kind of exception expected')
def test_reuse_client(): def test_reuse_client(client):
app = flask.Flask(__name__) c = client
c = app.test_client()
with c: with c:
assert c.get('/').status_code == 404 assert client.get('/').status_code == 404
with c: with c:
assert c.get('/').status_code == 404 assert client.get('/').status_code == 404
def test_test_client_calls_teardown_handlers(): def test_test_client_calls_teardown_handlers(app, client):
app = flask.Flask(__name__)
called = [] called = []
@app.teardown_request @app.teardown_request
def remember(error): def remember(error):
called.append(error) called.append(error)
with app.test_client() as c: with client:
assert called == [] assert called == []
c.get('/') client.get('/')
assert called == [] assert called == []
assert called == [None] assert called == [None]
del called[:] del called[:]
with app.test_client() as c: with client:
assert called == [] assert called == []
c.get('/') client.get('/')
assert called == [] assert called == []
c.get('/') client.get('/')
assert called == [None] assert called == [None]
assert called == [None, None] assert called == [None, None]
def test_full_url_request(): def test_full_url_request(app, client):
app = flask.Flask(__name__)
app.testing = True
@app.route('/action', methods=['POST']) @app.route('/action', methods=['POST'])
def action(): def action():
return 'x' return 'x'
with app.test_client() as c: with client:
rv = c.post('http://domain.com/action?vodka=42', data={'gin': 43}) rv = client.post('http://domain.com/action?vodka=42', data={'gin': 43})
assert rv.status_code == 200 assert rv.status_code == 200
assert 'gin' in flask.request.form assert 'gin' in flask.request.form
assert 'vodka' in flask.request.args assert 'vodka' in flask.request.args
def test_subdomain(): def test_subdomain(app, client):
app = flask.Flask(__name__)
app.config['SERVER_NAME'] = 'example.com' app.config['SERVER_NAME'] = 'example.com'
@app.route('/', subdomain='<company_id>') @app.route('/', subdomain='<company_id>')
@ -248,15 +241,14 @@ def test_subdomain():
with app.test_request_context(): with app.test_request_context():
url = flask.url_for('view', company_id='xxx') url = flask.url_for('view', company_id='xxx')
with app.test_client() as c: with client:
response = c.get(url) response = client.get(url)
assert 200 == response.status_code assert 200 == response.status_code
assert b'xxx' == response.data assert b'xxx' == response.data
def test_nosubdomain(): def test_nosubdomain(app, client):
app = flask.Flask(__name__)
app.config['SERVER_NAME'] = 'example.com' app.config['SERVER_NAME'] = 'example.com'
@app.route('/<company_id>') @app.route('/<company_id>')
@ -266,8 +258,8 @@ def test_nosubdomain():
with app.test_request_context(): with app.test_request_context():
url = flask.url_for('view', company_id='xxx') url = flask.url_for('view', company_id='xxx')
with app.test_client() as c: with client:
response = c.get(url) response = client.get(url)
assert 200 == response.status_code assert 200 == response.status_code
assert b'xxx' == response.data assert b'xxx' == response.data

38
tests/test_views.py

@ -72,7 +72,7 @@ def test_view_patching(app):
common_test(app) common_test(app)
def test_view_inheritance(app): def test_view_inheritance(app, client):
class Index(flask.views.MethodView): class Index(flask.views.MethodView):
def get(self): def get(self):
return 'GET' return 'GET'
@ -85,13 +85,12 @@ def test_view_inheritance(app):
return 'DELETE' return 'DELETE'
app.add_url_rule('/', view_func=BetterIndex.as_view('index')) app.add_url_rule('/', view_func=BetterIndex.as_view('index'))
c = app.test_client()
meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow']) meths = parse_set_header(client.open('/', method='OPTIONS').headers['Allow'])
assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST'] assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']
def test_view_decorators(app): def test_view_decorators(app, client):
def add_x_parachute(f): def add_x_parachute(f):
def new_function(*args, **kwargs): def new_function(*args, **kwargs):
resp = flask.make_response(f(*args, **kwargs)) resp = flask.make_response(f(*args, **kwargs))
@ -107,8 +106,7 @@ def test_view_decorators(app):
return 'Awesome' return 'Awesome'
app.add_url_rule('/', view_func=Index.as_view('index')) app.add_url_rule('/', view_func=Index.as_view('index'))
c = app.test_client() rv = client.get('/')
rv = c.get('/')
assert rv.headers['X-Parachute'] == 'awesome' assert rv.headers['X-Parachute'] == 'awesome'
assert rv.data == b'Awesome' assert rv.data == b'Awesome'
@ -153,7 +151,7 @@ def test_view_provide_automatic_options_attr():
assert 'OPTIONS' in rv.allow assert 'OPTIONS' in rv.allow
def test_implicit_head(app): def test_implicit_head(app, client):
class Index(flask.views.MethodView): class Index(flask.views.MethodView):
def get(self): def get(self):
return flask.Response('Blub', headers={ return flask.Response('Blub', headers={
@ -161,16 +159,15 @@ def test_implicit_head(app):
}) })
app.add_url_rule('/', view_func=Index.as_view('index')) app.add_url_rule('/', view_func=Index.as_view('index'))
c = app.test_client() rv = client.get('/')
rv = c.get('/')
assert rv.data == b'Blub' assert rv.data == b'Blub'
assert rv.headers['X-Method'] == 'GET' assert rv.headers['X-Method'] == 'GET'
rv = c.head('/') rv = client.head('/')
assert rv.data == b'' assert rv.data == b''
assert rv.headers['X-Method'] == 'HEAD' assert rv.headers['X-Method'] == 'HEAD'
def test_explicit_head(app): def test_explicit_head(app, client):
class Index(flask.views.MethodView): class Index(flask.views.MethodView):
def get(self): def get(self):
return 'GET' return 'GET'
@ -179,10 +176,9 @@ def test_explicit_head(app):
return flask.Response('', headers={'X-Method': 'HEAD'}) return flask.Response('', headers={'X-Method': 'HEAD'})
app.add_url_rule('/', view_func=Index.as_view('index')) app.add_url_rule('/', view_func=Index.as_view('index'))
c = app.test_client() rv = client.get('/')
rv = c.get('/')
assert rv.data == b'GET' assert rv.data == b'GET'
rv = c.head('/') rv = client.head('/')
assert rv.data == b'' assert rv.data == b''
assert rv.headers['X-Method'] == 'HEAD' assert rv.headers['X-Method'] == 'HEAD'
@ -205,7 +201,7 @@ def test_endpoint_override(app):
common_test(app) common_test(app)
def test_multiple_inheritance(app): def test_multiple_inheritance(app, client):
class GetView(flask.views.MethodView): class GetView(flask.views.MethodView):
def get(self): def get(self):
return 'GET' return 'GET'
@ -219,13 +215,12 @@ def test_multiple_inheritance(app):
app.add_url_rule('/', view_func=GetDeleteView.as_view('index')) app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))
c = app.test_client() assert client.get('/').data == b'GET'
assert c.get('/').data == b'GET' assert client.delete('/').data == b'DELETE'
assert c.delete('/').data == b'DELETE'
assert sorted(GetDeleteView.methods) == ['DELETE', 'GET'] assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']
def test_remove_method_from_parent(app): def test_remove_method_from_parent(app, client):
class GetView(flask.views.MethodView): class GetView(flask.views.MethodView):
def get(self): def get(self):
return 'GET' return 'GET'
@ -239,7 +234,6 @@ def test_remove_method_from_parent(app):
app.add_url_rule('/', view_func=View.as_view('index')) app.add_url_rule('/', view_func=View.as_view('index'))
c = app.test_client() assert client.get('/').data == b'GET'
assert c.get('/').data == b'GET' assert client.post('/').status_code == 405
assert c.post('/').status_code == 405
assert sorted(View.methods) == ['GET'] assert sorted(View.methods) == ['GET']

Loading…
Cancel
Save