我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用flask.Flask()。
def test_default_static_cache_timeout(self): app = flask.Flask(__name__) class MyBlueprint(flask.Blueprint): def get_send_file_max_age(self, filename): return 100 blueprint = MyBlueprint('blueprint', __name__, static_folder='static') app.register_blueprint(blueprint) # try/finally, in case other tests use this app for Blueprint tests. max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT'] try: with app.test_request_context(): unexpected_max_age = 3600 if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == unexpected_max_age: unexpected_max_age = 7200 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age rv = blueprint.send_static_file('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, 100) rv.close() finally: app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default
def test_test_client_context_binding(self): app = flask.Flask(__name__) @app.route('/') def index(): flask.g.value = 42 return 'Hello World!' @app.route('/other') def other(): 1 // 0 with app.test_client() as c: resp = c.get('/') self.assert_equal(flask.g.value, 42) self.assert_equal(resp.data, b'Hello World!') self.assert_equal(resp.status_code, 200) resp = c.get('/other') self.assert_false(hasattr(flask.g, 'value')) self.assert_in(b'Internal Server Error', resp.data) self.assert_equal(resp.status_code, 500) flask.g.value = 23 try: flask.g.value except (AttributeError, RuntimeError): pass else: raise AssertionError('some kind of exception expected')
def test_blueprint_url_definitions(self): bp = flask.Blueprint('test', __name__) @bp.route('/foo', defaults={'baz': 42}) def foo(bar, baz): return '%s/%d' % (bar, baz) @bp.route('/bar') def bar(bar): return text_type(bar) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23}) app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19}) c = app.test_client() self.assert_equal(c.get('/1/foo').data, b'23/42') self.assert_equal(c.get('/2/foo').data, b'19/42') self.assert_equal(c.get('/1/bar').data, b'23') self.assert_equal(c.get('/2/bar').data, b'19')
def test_dotted_names_from_app(self): app = flask.Flask(__name__) app.testing = True test = flask.Blueprint('test', __name__) @app.route('/') def app_index(): return flask.url_for('test.index') @test.route('/test/') def index(): return flask.url_for('app_index') app.register_blueprint(test) with app.test_client() as c: rv = c.get('/') self.assert_equal(rv.data, b'/test/')
def test_before_request_and_routing_errors(self): app = flask.Flask(__name__) @app.before_request def attach_something(): flask.g.something = 'value' @app.errorhandler(404) def return_something(error): return flask.g.something, 404 rv = app.test_client().get('/') self.assert_equal(rv.status_code, 404) self.assert_equal(rv.data, b'value')
def test_inject_blueprint_url_defaults(self): app = flask.Flask(__name__) bp = flask.Blueprint('foo.bar.baz', __name__, template_folder='template') @bp.url_defaults def bp_defaults(endpoint, values): values['page'] = 'login' @bp.route('/<page>') def view(page): pass app.register_blueprint(bp) values = dict() app.inject_url_defaults('foo.bar.baz.view', values) expected = dict(page='login') self.assert_equal(values, expected) with app.test_request_context('/somepage'): url = flask.url_for('foo.bar.baz.view') expected = '/login' self.assert_equal(url, expected)
def test_manual_context_binding(self): app = flask.Flask(__name__) @app.route('/') def index(): return 'Hello %s!' % flask.request.args['name'] ctx = app.test_request_context('/?name=World') ctx.push() self.assert_equal(index(), 'Hello World!') ctx.pop() try: index() except RuntimeError: pass else: self.assert_true(0, 'expected runtime error')
def WaitForFileServerToStart(port): """ Wait for the Flask file server to start up. Test it by trying the PyUpdater update URL, e.g. http://127.0.0.1:12345. If we receive a ConnectionError, we continue waiting, but if we receive an HTTP response code (404), we return True. For a frozen app, e.g. a Mac .app bundle, the location of the updates must be supplied by an environment variable, whereas when running from the source repo, the location of the updates is likely to be ./pyu-data/deploy/ """ url = 'http://%s:%s/fileserver-is-ready' % (LOCALHOST, port) attempts = 0 while True: try: attempts += 1 requests.get(url, timeout=1) return True except requests.exceptions.ConnectionError: time.sleep(0.25) if attempts > 10: logger.warning("WaitForFileServerToStart: timeout") return
def create_app(): app = Flask(__name__) app.config.from_object(config_dict[FLASK_CONFIGURATION]) app.secret_key = secret_key Bootstrap(app) assets = Environment(app) js_files = Bundle('justgage.js', 'raphael-2.1.4.min.js', filters='rjsmin', output='gen/minified.js') assets.register('js_files', js_files) nav.init_app(app) from .blueprints import bp app.register_blueprint(bp) global celery celery = make_celery(app) @app.errorhandler(404) def fournotfour(_): return render_template("404page.html"), 404 @app.errorhandler(500) def fivezerozero(_): return render_template("500page.html"), 500 return app
def build_web_app(ctx, name=__name__, debug=False): app = Flask(name) CORS(app) if debug: app.debug = debug @app.route('/') def hello(): return 'Hello, world!' @app.before_request def before_request(): g.repos = ctx.repos g.recommendations = ctx.recommendations app.register_blueprint(movies_bp) app.register_blueprint(users_bp) app.register_blueprint(recommendations_bp) app.register_blueprint(populate_bp) return app
def create_app(config_name): app = Flask(__name__)#, static_url_path='/app/static') app.config.from_object(config[config_name]) config[config_name].init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .admin import admin as admin_blueprint app.register_blueprint(admin_blueprint, url_prefix='/admin') db.init_app(app) login_manager.init_app(app) return app
def test_session_transactions(self): app = flask.Flask(__name__) app.testing = True app.secret_key = 'testing' @app.route('/') def index(): return text_type(flask.session['foo']) with app.test_client() as c: with c.session_transaction() as sess: self.assert_equal(len(sess), 0) sess['foo'] = [42] self.assert_equal(len(sess), 1) rv = c.get('/') self.assert_equal(rv.data, b'[42]') with c.session_transaction() as sess: self.assert_equal(len(sess), 1) self.assert_equal(sess['foo'], [42])
def test_test_client_calls_teardown_handlers(self): app = flask.Flask(__name__) called = [] @app.teardown_request def remember(error): called.append(error) with app.test_client() as c: self.assert_equal(called, []) c.get('/') self.assert_equal(called, []) self.assert_equal(called, [None]) del called[:] with app.test_client() as c: self.assert_equal(called, []) c.get('/') self.assert_equal(called, []) c.get('/') self.assert_equal(called, [None]) self.assert_equal(called, [None, None])
def test_send_file_xsendfile(self): app = flask.Flask(__name__) app.use_x_sendfile = True with app.test_request_context(): rv = flask.send_file('static/index.html') self.assert_true(rv.direct_passthrough) self.assert_in('x-sendfile', rv.headers) self.assert_equal(rv.headers['x-sendfile'], os.path.join(app.root_path, 'static/index.html')) self.assert_equal(rv.mimetype, 'text/html') rv.close()
def test_processor_exceptions(self): app = flask.Flask(__name__) @app.before_request def before_request(): if trigger == 'before': 1 // 0 @app.after_request def after_request(response): if trigger == 'after': 1 // 0 return response @app.route('/') def index(): return 'Foo' @app.errorhandler(500) def internal_server_error(e): return 'Hello Server Error', 500 for trigger in 'before', 'after': rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) self.assert_equal(rv.data, b'Hello Server Error')
def test_url_with_method(self): from flask.views import MethodView app = flask.Flask(__name__) class MyView(MethodView): def get(self, id=None): if id is None: return 'List' return 'Get %d' % id def post(self): return 'Create' myview = MyView.as_view('myview') app.add_url_rule('/myview/', methods=['GET'], view_func=myview) app.add_url_rule('/myview/<int:id>', methods=['GET'], view_func=myview) app.add_url_rule('/myview/create', methods=['POST'], view_func=myview) with app.test_request_context(): self.assert_equal(flask.url_for('myview', _method='GET'), '/myview/') self.assert_equal(flask.url_for('myview', id=42, _method='GET'), '/myview/42') self.assert_equal(flask.url_for('myview', _method='POST'), '/myview/create')
def test_view_inheritance(self): app = flask.Flask(__name__) class Index(flask.views.MethodView): def get(self): return 'GET' def post(self): return 'POST' class BetterIndex(Index): def delete(self): return 'DELETE' app.add_url_rule('/', view_func=BetterIndex.as_view('index')) c = app.test_client() meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow']) self.assert_equal(sorted(meths), ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST'])
def test_view_decorators(self): app = flask.Flask(__name__) def add_x_parachute(f): def new_function(*args, **kwargs): resp = flask.make_response(f(*args, **kwargs)) resp.headers['X-Parachute'] = 'awesome' return resp return new_function class Index(flask.views.View): decorators = [add_x_parachute] def dispatch_request(self): return 'Awesome' app.add_url_rule('/', view_func=Index.as_view('index')) c = app.test_client() rv = c.get('/') self.assert_equal(rv.headers['X-Parachute'], 'awesome') self.assert_equal(rv.data, b'Awesome')
def test_endpoint_override(self): app = flask.Flask(__name__) app.debug = True class Index(flask.views.View): methods = ['GET', 'POST'] def dispatch_request(self): return flask.request.method app.add_url_rule('/', view_func=Index.as_view('index')) with self.assert_raises(AssertionError): app.add_url_rule('/', view_func=Index.as_view('index')) # But these tests should still pass. We just log a warning. self.common_test(app)
def test_basic_module(self): app = flask.Flask(__name__) admin = flask.Module(__name__, 'admin', url_prefix='/admin') @admin.route('/') def admin_index(): return 'admin index' @admin.route('/login') def admin_login(): return 'admin login' @admin.route('/logout') def admin_logout(): return 'admin logout' @app.route('/') def index(): return 'the index' app.register_module(admin) c = app.test_client() self.assert_equal(c.get('/').data, b'the index') self.assert_equal(c.get('/admin/').data, b'admin index') self.assert_equal(c.get('/admin/login').data, b'admin login') self.assert_equal(c.get('/admin/logout').data, b'admin logout')
def test_context_processors(self): app = flask.Flask(__name__) admin = flask.Module(__name__, 'admin', url_prefix='/admin') @app.context_processor def inject_all_regular(): return {'a': 1} @admin.context_processor def inject_admin(): return {'b': 2} @admin.app_context_processor def inject_all_module(): return {'c': 3} @app.route('/') def index(): return flask.render_template_string('{{ a }}{{ b }}{{ c }}') @admin.route('/') def admin_index(): return flask.render_template_string('{{ a }}{{ b }}{{ c }}') app.register_module(admin) c = app.test_client() self.assert_equal(c.get('/').data, b'13') self.assert_equal(c.get('/admin/').data, b'123')
def test_endpoint_decorator(self): from werkzeug.routing import Submount, Rule from flask import Module app = flask.Flask(__name__) app.testing = True app.url_map.add(Submount('/foo', [ Rule('/bar', endpoint='bar'), Rule('/', endpoint='index') ])) module = Module(__name__, __name__) @module.endpoint('bar') def bar(): return 'bar' @module.endpoint('index') def index(): return 'index' app.register_module(module) c = app.test_client() self.assert_equal(c.get('/foo/').data, b'index') self.assert_equal(c.get('/foo/bar').data, b'bar')
def test_dotted_names(self): frontend = flask.Blueprint('myapp.frontend', __name__) backend = flask.Blueprint('myapp.backend', __name__) @frontend.route('/fe') def frontend_index(): return flask.url_for('myapp.backend.backend_index') @frontend.route('/fe2') def frontend_page2(): return flask.url_for('.frontend_index') @backend.route('/be') def backend_index(): return flask.url_for('myapp.frontend.frontend_index') app = flask.Flask(__name__) app.register_blueprint(frontend) app.register_blueprint(backend) c = app.test_client() self.assert_equal(c.get('/fe').data.strip(), b'/be') self.assert_equal(c.get('/fe2').data.strip(), b'/fe') self.assert_equal(c.get('/be').data.strip(), b'/fe')
def test_options_handling_disabled(self): app = flask.Flask(__name__) def index(): return 'Hello World!' index.provide_automatic_options = False app.route('/')(index) rv = app.test_client().open('/', method='OPTIONS') self.assert_equal(rv.status_code, 405) app = flask.Flask(__name__) def index2(): return 'Hello World!' index2.provide_automatic_options = True app.route('/', methods=['OPTIONS'])(index2) rv = app.test_client().open('/', method='OPTIONS') self.assert_equal(sorted(rv.allow), ['OPTIONS'])
def test_request_dispatching(self): app = flask.Flask(__name__) @app.route('/') def index(): return flask.request.method @app.route('/more', methods=['GET', 'POST']) def more(): return flask.request.method c = app.test_client() self.assert_equal(c.get('/').data, b'GET') rv = c.post('/') self.assert_equal(rv.status_code, 405) self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS']) rv = c.head('/') self.assert_equal(rv.status_code, 200) self.assert_false(rv.data) # head truncates self.assert_equal(c.post('/more').data, b'POST') self.assert_equal(c.get('/more').data, b'GET') rv = c.delete('/more') self.assert_equal(rv.status_code, 405) self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST'])
def test_url_mapping(self): app = flask.Flask(__name__) def index(): return flask.request.method def more(): return flask.request.method app.add_url_rule('/', 'index', index) app.add_url_rule('/more', 'more', more, methods=['GET', 'POST']) c = app.test_client() self.assert_equal(c.get('/').data, b'GET') rv = c.post('/') self.assert_equal(rv.status_code, 405) self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS']) rv = c.head('/') self.assert_equal(rv.status_code, 200) self.assert_false(rv.data) # head truncates self.assert_equal(c.post('/more').data, b'POST') self.assert_equal(c.get('/more').data, b'GET') rv = c.delete('/more') self.assert_equal(rv.status_code, 405) self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST'])
def test_endpoint_decorator(self): from werkzeug.routing import Submount, Rule app = flask.Flask(__name__) app.url_map.add(Submount('/foo', [ Rule('/bar', endpoint='bar'), Rule('/', endpoint='index') ])) @app.endpoint('bar') def bar(): return 'bar' @app.endpoint('index') def index(): return 'index' c = app.test_client() self.assert_equal(c.get('/foo/').data, b'index') self.assert_equal(c.get('/foo/bar').data, b'bar')
def test_session_using_session_settings(self): app = flask.Flask(__name__) app.config.update( SECRET_KEY='foo', SERVER_NAME='www.example.com:8080', APPLICATION_ROOT='/test', SESSION_COOKIE_DOMAIN='.example.com', SESSION_COOKIE_HTTPONLY=False, SESSION_COOKIE_SECURE=True, SESSION_COOKIE_PATH='/' ) @app.route('/') def index(): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://www.example.com:8080/test/') cookie = rv.headers['set-cookie'].lower() self.assert_in('domain=.example.com', cookie) self.assert_in('path=/', cookie) self.assert_in('secure', cookie) self.assert_not_in('httponly', cookie)
def test_session_stored_last(self): app = flask.Flask(__name__) app.secret_key = 'development-key' app.testing = True @app.after_request def modify_session(response): flask.session['foo'] = 42 return response @app.route('/') def dump_session_contents(): return repr(flask.session.get('foo')) c = app.test_client() self.assert_equal(c.get('/').data, b'None') self.assert_equal(c.get('/').data, b'42')
def test_request_processing(self): app = flask.Flask(__name__) evts = [] @app.before_request def before_request(): evts.append('before') @app.after_request def after_request(response): response.data += b'|after' evts.append('after') return response @app.route('/') def index(): self.assert_in('before', evts) self.assert_not_in('after', evts) return 'request' self.assert_not_in('after', evts) rv = app.test_client().get('/').data self.assert_in('after', evts) self.assert_equal(rv, b'request|after')
def test_error_handling(self): app = flask.Flask(__name__) @app.errorhandler(404) def not_found(e): return 'not found', 404 @app.errorhandler(500) def internal_server_error(e): return 'internal server error', 500 @app.route('/') def index(): flask.abort(404) @app.route('/error') def error(): 1 // 0 c = app.test_client() rv = c.get('/') self.assert_equal(rv.status_code, 404) self.assert_equal(rv.data, b'not found') rv = c.get('/error') self.assert_equal(rv.status_code, 500) self.assert_equal(b'internal server error', rv.data)
def test_trapping_of_bad_request_key_errors(self): app = flask.Flask(__name__) app.testing = True @app.route('/fail') def fail(): flask.request.form['missing_key'] c = app.test_client() self.assert_equal(c.get('/fail').status_code, 400) app.config['TRAP_BAD_REQUEST_ERRORS'] = True c = app.test_client() try: c.get('/fail') except KeyError as e: self.assert_true(isinstance(e, BadRequest)) else: self.fail('Expected exception')
def test_response_creation(self): app = flask.Flask(__name__) @app.route('/unicode') def from_unicode(): return u'Hällo Wörld' @app.route('/string') def from_string(): return u'Hällo Wörld'.encode('utf-8') @app.route('/args') def from_tuple(): return 'Meh', 400, { 'X-Foo': 'Testing', 'Content-Type': 'text/plain; charset=utf-8' } c = app.test_client() self.assert_equal(c.get('/unicode').data, u'Hällo Wörld'.encode('utf-8')) self.assert_equal(c.get('/string').data, u'Hällo Wörld'.encode('utf-8')) rv = c.get('/args') self.assert_equal(rv.data, b'Meh') self.assert_equal(rv.headers['X-Foo'], 'Testing') self.assert_equal(rv.status_code, 400) self.assert_equal(rv.mimetype, 'text/plain')
def test_make_response(self): app = flask.Flask(__name__) with app.test_request_context(): rv = flask.make_response() self.assert_equal(rv.status_code, 200) self.assert_equal(rv.data, b'') self.assert_equal(rv.mimetype, 'text/html') rv = flask.make_response('Awesome') self.assert_equal(rv.status_code, 200) self.assert_equal(rv.data, b'Awesome') self.assert_equal(rv.mimetype, 'text/html') rv = flask.make_response('W00t', 404) self.assert_equal(rv.status_code, 404) self.assert_equal(rv.data, b'W00t') self.assert_equal(rv.mimetype, 'text/html')
def test_build_error_handler(self): app = flask.Flask(__name__) # Test base case, a URL which results in a BuildError. with app.test_request_context(): self.assertRaises(BuildError, flask.url_for, 'spam') # Verify the error is re-raised if not the current exception. try: with app.test_request_context(): flask.url_for('spam') except BuildError as err: error = err try: raise RuntimeError('Test case where BuildError is not current.') except RuntimeError: self.assertRaises(BuildError, app.handle_url_build_error, error, 'spam', {}) # Test a custom handler. def handler(error, endpoint, values): # Just a test. return '/test_handler/' app.url_build_error_handlers.append(handler) with app.test_request_context(): self.assert_equal(flask.url_for('spam'), '/test_handler/')
def test_max_content_length(self): app = flask.Flask(__name__) app.config['MAX_CONTENT_LENGTH'] = 64 @app.before_request def always_first(): flask.request.form['myfile'] self.assert_true(False) @app.route('/accept', methods=['POST']) def accept_file(): flask.request.form['myfile'] self.assert_true(False) @app.errorhandler(413) def catcher(error): return '42' c = app.test_client() rv = c.post('/accept', data={'myfile': 'foo' * 100}) self.assert_equal(rv.data, b'42')
def test_debug_mode_complains_after_first_request(self): app = flask.Flask(__name__) app.debug = True @app.route('/') def index(): return 'Awesome' self.assert_false(app.got_first_request) self.assert_equal(app.test_client().get('/').data, b'Awesome') try: @app.route('/foo') def broken(): return 'Meh' except AssertionError as e: self.assert_in('A setup function was called', str(e)) else: self.fail('Expected exception') app.debug = False @app.route('/foo') def working(): return 'Meh' self.assert_equal(app.test_client().get('/foo').data, b'Meh') self.assert_true(app.got_first_request)
def test_routing_redirect_debugging(self): app = flask.Flask(__name__) app.debug = True @app.route('/foo/', methods=['GET', 'POST']) def foo(): return 'success' with app.test_client() as c: try: c.post('/foo', data={}) except AssertionError as e: self.assert_in('http://localhost/foo/', str(e)) self.assert_in('Make sure to directly send your POST-request ' 'to this URL', str(e)) else: self.fail('Expected exception') rv = c.get('/foo', data={}, follow_redirects=True) self.assert_equal(rv.data, b'success') app.debug = False with app.test_client() as c: rv = c.post('/foo', data={}, follow_redirects=True) self.assert_equal(rv.data, b'success')
def test_preserve_only_once(self): app = flask.Flask(__name__) app.debug = True @app.route('/fail') def fail_func(): 1 // 0 c = app.test_client() for x in range(3): with self.assert_raises(ZeroDivisionError): c.get('/fail') self.assert_true(flask._request_ctx_stack.top is not None) self.assert_true(flask._app_ctx_stack.top is not None) # implicit appctx disappears too flask._request_ctx_stack.top.pop() self.assert_true(flask._request_ctx_stack.top is None) self.assert_true(flask._app_ctx_stack.top is None)
def test_basic_support(self): app = flask.Flask(__name__) app.config['SERVER_NAME'] = 'localhost' @app.route('/') def normal_index(): return 'normal index' @app.route('/', subdomain='test') def test_index(): return 'test index' c = app.test_client() rv = c.get('/', 'http://localhost/') self.assert_equal(rv.data, b'normal index') rv = c.get('/', 'http://test.localhost/') self.assert_equal(rv.data, b'test index')
def test_module_subdomain_support(self): app = flask.Flask(__name__) mod = flask.Module(__name__, 'test', subdomain='testing') app.config['SERVER_NAME'] = 'localhost' @mod.route('/test') def test(): return 'Test' @mod.route('/outside', subdomain='xtesting') def bar(): return 'Outside' app.register_module(mod) c = app.test_client() rv = c.get('/test', 'http://testing.localhost/') self.assert_equal(rv.data, b'Test') rv = c.get('/outside', 'http://xtesting.localhost/') self.assert_equal(rv.data, b'Outside')
def test_escaping(self): text = '<p>Hello World!' app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template('escaping_template.html', text=text, html=flask.Markup(text)) lines = app.test_client().get('/').data.splitlines() self.assert_equal(lines, [ b'<p>Hello World!', b'<p>Hello World!', b'<p>Hello World!', b'<p>Hello World!', b'<p>Hello World!', b'<p>Hello World!' ])
def test_template_rendered(self): app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template('simple_template.html', whiskey=42) recorded = [] def record(sender, template, context): recorded.append((template, context)) flask.template_rendered.connect(record, app) try: app.test_client().get('/') self.assert_equal(len(recorded), 1) template, context = recorded[0] self.assert_equal(template.name, 'simple_template.html') self.assert_equal(context['whiskey'], 42) finally: flask.template_rendered.disconnect(record, app)
def test_request_exception_signal(self): app = flask.Flask(__name__) recorded = [] @app.route('/') def index(): 1 // 0 def record(sender, exception): recorded.append(exception) flask.got_request_exception.connect(record, app) try: self.assert_equal(app.test_client().get('/').status_code, 500) self.assert_equal(len(recorded), 1) self.assert_true(isinstance(recorded[0], ZeroDivisionError)) finally: flask.got_request_exception.disconnect(record, app)
def test_appcontext_signals(self): app = flask.Flask(__name__) recorded = [] def record_push(sender, **kwargs): recorded.append('push') def record_pop(sender, **kwargs): recorded.append('push') @app.route('/') def index(): return 'Hello' flask.appcontext_pushed.connect(record_push, app) flask.appcontext_popped.connect(record_pop, app) try: with app.test_client() as c: rv = c.get('/') self.assert_equal(rv.data, b'Hello') self.assert_equal(recorded, ['push']) self.assert_equal(recorded, ['push', 'pop']) finally: flask.appcontext_pushed.disconnect(record_push, app) flask.appcontext_popped.disconnect(record_pop, app)
def test_greenlet_context_copying_api(self): app = flask.Flask(__name__) greenlets = [] @app.route('/') def index(): reqctx = flask._request_ctx_stack.top.copy() @flask.copy_current_request_context def g(): self.assert_true(flask.request) self.assert_equal(flask.current_app, app) self.assert_equal(flask.request.path, '/') self.assert_equal(flask.request.args['foo'], 'bar') return 42 greenlets.append(greenlet(g)) return 'Hello World!' rv = app.test_client().get('/?foo=bar') self.assert_equal(rv.data, b'Hello World!') result = greenlets[0].run() self.assert_equal(result, 42) # Disable test if we don't have greenlets available
def test_suppressed_exception_logging(self): class SuppressedFlask(flask.Flask): def log_exception(self, exc_info): pass out = StringIO() app = SuppressedFlask(__name__) app.logger_name = 'flask_tests/test_suppressed_exception_logging' app.logger.addHandler(StreamHandler(out)) @app.route('/') def index(): 1 // 0 rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) self.assert_in(b'Internal Server Error', rv.data) err = out.getvalue() self.assert_equal(err, '')
def test_memory_consumption(self): app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template('simple_template.html', whiskey=42) def fire(): with app.test_client() as c: rv = c.get('/') self.assert_equal(rv.status_code, 200) self.assert_equal(rv.data, b'<h1>42</h1>') # Trigger caches fire() # This test only works on CPython 2.7. if sys.version_info >= (2, 7) and \ not hasattr(sys, 'pypy_translation_info'): with self.assert_no_leak(): for x in range(10): fire()
def test_aborting(self): class Foo(Exception): whatever = 42 app = flask.Flask(__name__) app.testing = True @app.errorhandler(Foo) def handle_foo(e): return str(e.whatever) @app.route('/') def index(): raise flask.abort(flask.redirect(flask.url_for('test'))) @app.route('/test') def test(): raise Foo() with app.test_client() as c: rv = c.get('/') self.assertEqual(rv.headers['Location'], 'http://localhost/test') rv = c.get('/test') self.assertEqual(rv.data, b'42')
def test_config_from_envvar(self): env = os.environ try: os.environ = {} app = flask.Flask(__name__) try: app.config.from_envvar('FOO_SETTINGS') except RuntimeError as e: self.assert_true("'FOO_SETTINGS' is not set" in str(e)) else: self.assert_true(0, 'expected exception') self.assert_false(app.config.from_envvar('FOO_SETTINGS', silent=True)) os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'} self.assert_true(app.config.from_envvar('FOO_SETTINGS')) self.common_object_test(app) finally: os.environ = env