forked from orbit-oss/flask
parent
5b309831ec
commit
025589ee76
63 changed files with 3784 additions and 3459 deletions
|
|
@ -20,7 +20,7 @@ import flask
|
|||
from flask import Flask as _Flask
|
||||
|
||||
|
||||
@pytest.fixture(scope='session', autouse=True)
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _standard_os_environ():
|
||||
"""Set up ``os.environ`` at the start of the test session to have
|
||||
standard values. Returns a list of operations that is used by
|
||||
|
|
@ -28,11 +28,11 @@ def _standard_os_environ():
|
|||
"""
|
||||
mp = monkeypatch.MonkeyPatch()
|
||||
out = (
|
||||
(os.environ, 'FLASK_APP', monkeypatch.notset),
|
||||
(os.environ, 'FLASK_ENV', monkeypatch.notset),
|
||||
(os.environ, 'FLASK_DEBUG', monkeypatch.notset),
|
||||
(os.environ, 'FLASK_RUN_FROM_CLI', monkeypatch.notset),
|
||||
(os.environ, 'WERKZEUG_RUN_MAIN', monkeypatch.notset),
|
||||
(os.environ, "FLASK_APP", monkeypatch.notset),
|
||||
(os.environ, "FLASK_ENV", monkeypatch.notset),
|
||||
(os.environ, "FLASK_DEBUG", monkeypatch.notset),
|
||||
(os.environ, "FLASK_RUN_FROM_CLI", monkeypatch.notset),
|
||||
(os.environ, "WERKZEUG_RUN_MAIN", monkeypatch.notset),
|
||||
)
|
||||
|
||||
for _, key, value in out:
|
||||
|
|
@ -55,12 +55,12 @@ def _reset_os_environ(monkeypatch, _standard_os_environ):
|
|||
|
||||
class Flask(_Flask):
|
||||
testing = True
|
||||
secret_key = 'test key'
|
||||
secret_key = "test key"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app():
|
||||
app = Flask('flask_test', root_path=os.path.dirname(__file__))
|
||||
app = Flask("flask_test", root_path=os.path.dirname(__file__))
|
||||
return app
|
||||
|
||||
|
||||
|
|
@ -84,8 +84,7 @@ def client(app):
|
|||
@pytest.fixture
|
||||
def test_apps(monkeypatch):
|
||||
monkeypatch.syspath_prepend(
|
||||
os.path.abspath(os.path.join(
|
||||
os.path.dirname(__file__), 'test_apps'))
|
||||
os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps"))
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -120,8 +119,8 @@ def limit_loader(request, monkeypatch):
|
|||
self.loader = loader
|
||||
|
||||
def __getattr__(self, name):
|
||||
if name in ('archive', 'get_filename'):
|
||||
msg = 'Mocking a loader which does not have `%s.`' % name
|
||||
if name in ("archive", "get_filename"):
|
||||
msg = "Mocking a loader which does not have `%s.`" % name
|
||||
raise AttributeError(msg)
|
||||
return getattr(self.loader, name)
|
||||
|
||||
|
|
@ -130,30 +129,31 @@ def limit_loader(request, monkeypatch):
|
|||
def get_loader(*args, **kwargs):
|
||||
return LimitedLoader(old_get_loader(*args, **kwargs))
|
||||
|
||||
monkeypatch.setattr(pkgutil, 'get_loader', get_loader)
|
||||
monkeypatch.setattr(pkgutil, "get_loader", get_loader)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def modules_tmpdir(tmpdir, monkeypatch):
|
||||
"""A tmpdir added to sys.path."""
|
||||
rv = tmpdir.mkdir('modules_tmpdir')
|
||||
rv = tmpdir.mkdir("modules_tmpdir")
|
||||
monkeypatch.syspath_prepend(str(rv))
|
||||
return rv
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def modules_tmpdir_prefix(modules_tmpdir, monkeypatch):
|
||||
monkeypatch.setattr(sys, 'prefix', str(modules_tmpdir))
|
||||
monkeypatch.setattr(sys, "prefix", str(modules_tmpdir))
|
||||
return modules_tmpdir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def site_packages(modules_tmpdir, monkeypatch):
|
||||
"""Create a fake site-packages."""
|
||||
rv = modules_tmpdir \
|
||||
.mkdir('lib') \
|
||||
.mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info)) \
|
||||
.mkdir('site-packages')
|
||||
rv = (
|
||||
modules_tmpdir.mkdir("lib")
|
||||
.mkdir("python{x[0]}.{x[1]}".format(x=sys.version_info))
|
||||
.mkdir("site-packages")
|
||||
)
|
||||
monkeypatch.syspath_prepend(str(rv))
|
||||
return rv
|
||||
|
||||
|
|
@ -167,23 +167,29 @@ def install_egg(modules_tmpdir, monkeypatch):
|
|||
if not isinstance(name, str):
|
||||
raise ValueError(name)
|
||||
base.join(name).ensure_dir()
|
||||
base.join(name).join('__init__.py').ensure()
|
||||
base.join(name).join("__init__.py").ensure()
|
||||
|
||||
egg_setup = base.join('setup.py')
|
||||
egg_setup.write(textwrap.dedent("""
|
||||
egg_setup = base.join("setup.py")
|
||||
egg_setup.write(
|
||||
textwrap.dedent(
|
||||
"""
|
||||
from setuptools import setup
|
||||
setup(name='{0}',
|
||||
version='1.0',
|
||||
packages=['site_egg'],
|
||||
zip_safe=True)
|
||||
""".format(name)))
|
||||
""".format(
|
||||
name
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
import subprocess
|
||||
|
||||
subprocess.check_call(
|
||||
[sys.executable, 'setup.py', 'bdist_egg'],
|
||||
cwd=str(modules_tmpdir)
|
||||
[sys.executable, "setup.py", "bdist_egg"], cwd=str(modules_tmpdir)
|
||||
)
|
||||
egg_path, = modules_tmpdir.join('dist/').listdir()
|
||||
egg_path, = modules_tmpdir.join("dist/").listdir()
|
||||
monkeypatch.syspath_prepend(str(egg_path))
|
||||
return egg_path
|
||||
|
||||
|
|
@ -202,4 +208,4 @@ def purge_module(request):
|
|||
def catch_deprecation_warnings(recwarn):
|
||||
yield
|
||||
gc.collect()
|
||||
assert not recwarn.list, '\n'.join(str(w.message) for w in recwarn.list)
|
||||
assert not recwarn.list, "\n".join(str(w.message) for w in recwarn.list)
|
||||
|
|
|
|||
|
|
@ -15,27 +15,27 @@ import flask
|
|||
|
||||
|
||||
def test_basic_url_generation(app):
|
||||
app.config['SERVER_NAME'] = 'localhost'
|
||||
app.config['PREFERRED_URL_SCHEME'] = 'https'
|
||||
app.config["SERVER_NAME"] = "localhost"
|
||||
app.config["PREFERRED_URL_SCHEME"] = "https"
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
pass
|
||||
|
||||
with app.app_context():
|
||||
rv = flask.url_for('index')
|
||||
assert rv == 'https://localhost/'
|
||||
rv = flask.url_for("index")
|
||||
assert rv == "https://localhost/"
|
||||
|
||||
|
||||
def test_url_generation_requires_server_name(app):
|
||||
with app.app_context():
|
||||
with pytest.raises(RuntimeError):
|
||||
flask.url_for('index')
|
||||
flask.url_for("index")
|
||||
|
||||
|
||||
def test_url_generation_without_context_fails():
|
||||
with pytest.raises(RuntimeError):
|
||||
flask.url_for('index')
|
||||
flask.url_for("index")
|
||||
|
||||
|
||||
def test_request_context_means_app_context(app):
|
||||
|
|
@ -71,7 +71,7 @@ def test_app_tearing_down_with_previous_exception(app):
|
|||
cleanup_stuff.append(exception)
|
||||
|
||||
try:
|
||||
raise Exception('dummy')
|
||||
raise Exception("dummy")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
|
@ -90,7 +90,7 @@ def test_app_tearing_down_with_handled_exception_by_except_block(app):
|
|||
|
||||
with app.app_context():
|
||||
try:
|
||||
raise Exception('dummy')
|
||||
raise Exception("dummy")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
|
@ -98,79 +98,79 @@ def test_app_tearing_down_with_handled_exception_by_except_block(app):
|
|||
|
||||
|
||||
def test_app_tearing_down_with_handled_exception_by_app_handler(app, client):
|
||||
app.config['PROPAGATE_EXCEPTIONS'] = True
|
||||
app.config["PROPAGATE_EXCEPTIONS"] = True
|
||||
cleanup_stuff = []
|
||||
|
||||
@app.teardown_appcontext
|
||||
def cleanup(exception):
|
||||
cleanup_stuff.append(exception)
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
raise Exception('dummy')
|
||||
raise Exception("dummy")
|
||||
|
||||
@app.errorhandler(Exception)
|
||||
def handler(f):
|
||||
return flask.jsonify(str(f))
|
||||
|
||||
with app.app_context():
|
||||
client.get('/')
|
||||
client.get("/")
|
||||
|
||||
assert cleanup_stuff == [None]
|
||||
|
||||
|
||||
def test_app_tearing_down_with_unhandled_exception(app, client):
|
||||
app.config['PROPAGATE_EXCEPTIONS'] = True
|
||||
app.config["PROPAGATE_EXCEPTIONS"] = True
|
||||
cleanup_stuff = []
|
||||
|
||||
@app.teardown_appcontext
|
||||
def cleanup(exception):
|
||||
cleanup_stuff.append(exception)
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
raise Exception('dummy')
|
||||
raise Exception("dummy")
|
||||
|
||||
with pytest.raises(Exception):
|
||||
with app.app_context():
|
||||
client.get('/')
|
||||
client.get("/")
|
||||
|
||||
assert len(cleanup_stuff) == 1
|
||||
assert isinstance(cleanup_stuff[0], Exception)
|
||||
assert str(cleanup_stuff[0]) == 'dummy'
|
||||
assert str(cleanup_stuff[0]) == "dummy"
|
||||
|
||||
|
||||
def test_app_ctx_globals_methods(app, app_ctx):
|
||||
# get
|
||||
assert flask.g.get('foo') is None
|
||||
assert flask.g.get('foo', 'bar') == 'bar'
|
||||
assert flask.g.get("foo") is None
|
||||
assert flask.g.get("foo", "bar") == "bar"
|
||||
# __contains__
|
||||
assert 'foo' not in flask.g
|
||||
flask.g.foo = 'bar'
|
||||
assert 'foo' in flask.g
|
||||
assert "foo" not in flask.g
|
||||
flask.g.foo = "bar"
|
||||
assert "foo" in flask.g
|
||||
# setdefault
|
||||
flask.g.setdefault('bar', 'the cake is a lie')
|
||||
flask.g.setdefault('bar', 'hello world')
|
||||
assert flask.g.bar == 'the cake is a lie'
|
||||
flask.g.setdefault("bar", "the cake is a lie")
|
||||
flask.g.setdefault("bar", "hello world")
|
||||
assert flask.g.bar == "the cake is a lie"
|
||||
# pop
|
||||
assert flask.g.pop('bar') == 'the cake is a lie'
|
||||
assert flask.g.pop("bar") == "the cake is a lie"
|
||||
with pytest.raises(KeyError):
|
||||
flask.g.pop('bar')
|
||||
assert flask.g.pop('bar', 'more cake') == 'more cake'
|
||||
flask.g.pop("bar")
|
||||
assert flask.g.pop("bar", "more cake") == "more cake"
|
||||
# __iter__
|
||||
assert list(flask.g) == ['foo']
|
||||
#__repr__
|
||||
assert list(flask.g) == ["foo"]
|
||||
# __repr__
|
||||
assert repr(flask.g) == "<flask.g of 'flask_test'>"
|
||||
|
||||
|
||||
def test_custom_app_ctx_globals_class(app):
|
||||
class CustomRequestGlobals(object):
|
||||
def __init__(self):
|
||||
self.spam = 'eggs'
|
||||
self.spam = "eggs"
|
||||
|
||||
app.app_ctx_globals_class = CustomRequestGlobals
|
||||
with app.app_context():
|
||||
assert flask.render_template_string('{{ g.spam }}') == 'eggs'
|
||||
assert flask.render_template_string("{{ g.spam }}") == "eggs"
|
||||
|
||||
|
||||
def test_context_refcounts(app, client):
|
||||
|
|
@ -178,25 +178,25 @@ def test_context_refcounts(app, client):
|
|||
|
||||
@app.teardown_request
|
||||
def teardown_req(error=None):
|
||||
called.append('request')
|
||||
called.append("request")
|
||||
|
||||
@app.teardown_appcontext
|
||||
def teardown_app(error=None):
|
||||
called.append('app')
|
||||
called.append("app")
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
with flask._app_ctx_stack.top:
|
||||
with flask._request_ctx_stack.top:
|
||||
pass
|
||||
env = flask._request_ctx_stack.top.request.environ
|
||||
assert env['werkzeug.request'] is not None
|
||||
return u''
|
||||
assert env["werkzeug.request"] is not None
|
||||
return u""
|
||||
|
||||
res = client.get('/')
|
||||
res = client.get("/")
|
||||
assert res.status_code == 200
|
||||
assert res.data == b''
|
||||
assert called == ['request', 'app']
|
||||
assert res.data == b""
|
||||
assert called == ["request", "app"]
|
||||
|
||||
|
||||
def test_clean_pop(app):
|
||||
|
|
@ -209,7 +209,7 @@ def test_clean_pop(app):
|
|||
|
||||
@app.teardown_appcontext
|
||||
def teardown_app(error=None):
|
||||
called.append('TEARDOWN')
|
||||
called.append("TEARDOWN")
|
||||
|
||||
try:
|
||||
with app.test_request_context():
|
||||
|
|
@ -217,5 +217,5 @@ def test_clean_pop(app):
|
|||
except ZeroDivisionError:
|
||||
pass
|
||||
|
||||
assert called == ['flask_test', 'TEARDOWN']
|
||||
assert called == ["flask_test", "TEARDOWN"]
|
||||
assert not flask.current_app
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
from flask import Flask
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config['DEBUG'] = True
|
||||
app.config["DEBUG"] = True
|
||||
from blueprintapp.apps.admin import admin
|
||||
from blueprintapp.apps.frontend import frontend
|
||||
|
||||
app.register_blueprint(admin)
|
||||
app.register_blueprint(frontend)
|
||||
|
|
|
|||
|
|
@ -1,15 +1,19 @@
|
|||
from flask import Blueprint, render_template
|
||||
|
||||
admin = Blueprint('admin', __name__, url_prefix='/admin',
|
||||
template_folder='templates',
|
||||
static_folder='static')
|
||||
admin = Blueprint(
|
||||
"admin",
|
||||
__name__,
|
||||
url_prefix="/admin",
|
||||
template_folder="templates",
|
||||
static_folder="static",
|
||||
)
|
||||
|
||||
|
||||
@admin.route('/')
|
||||
@admin.route("/")
|
||||
def index():
|
||||
return render_template('admin/index.html')
|
||||
return render_template("admin/index.html")
|
||||
|
||||
|
||||
@admin.route('/index2')
|
||||
@admin.route("/index2")
|
||||
def index2():
|
||||
return render_template('./admin/index.html')
|
||||
return render_template("./admin/index.html")
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
from flask import Blueprint, render_template
|
||||
|
||||
frontend = Blueprint('frontend', __name__, template_folder='templates')
|
||||
frontend = Blueprint("frontend", __name__, template_folder="templates")
|
||||
|
||||
|
||||
@frontend.route('/')
|
||||
@frontend.route("/")
|
||||
def index():
|
||||
return render_template('frontend/index.html')
|
||||
return render_template("frontend/index.html")
|
||||
|
||||
|
||||
@frontend.route('/missing')
|
||||
@frontend.route("/missing")
|
||||
def missing_template():
|
||||
return render_template('missing_template.html')
|
||||
return render_template("missing_template.html")
|
||||
|
|
|
|||
|
|
@ -2,4 +2,4 @@ from __future__ import absolute_import, print_function
|
|||
|
||||
from flask import Flask
|
||||
|
||||
testapp = Flask('testapp')
|
||||
testapp = Flask("testapp")
|
||||
|
|
|
|||
|
|
@ -4,15 +4,15 @@ from flask import Flask
|
|||
|
||||
|
||||
def create_app():
|
||||
return Flask('app')
|
||||
return Flask("app")
|
||||
|
||||
|
||||
def create_app2(foo, bar):
|
||||
return Flask('_'.join(['app2', foo, bar]))
|
||||
return Flask("_".join(["app2", foo, bar]))
|
||||
|
||||
|
||||
def create_app3(foo, script_info):
|
||||
return Flask('_'.join(['app3', foo, script_info.data['test']]))
|
||||
return Flask("_".join(["app3", foo, script_info.data["test"]]))
|
||||
|
||||
|
||||
def no_app():
|
||||
|
|
|
|||
|
|
@ -4,4 +4,4 @@ from flask import Flask
|
|||
|
||||
raise ImportError()
|
||||
|
||||
testapp = Flask('testapp')
|
||||
testapp = Flask("testapp")
|
||||
|
|
|
|||
|
|
@ -2,5 +2,5 @@ from __future__ import absolute_import, print_function
|
|||
|
||||
from flask import Flask
|
||||
|
||||
app1 = Flask('app1')
|
||||
app2 = Flask('app2')
|
||||
app1 = Flask("app1")
|
||||
app2 = Flask("app2")
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
from flask import Flask
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
|
||||
@app.route("/")
|
||||
def hello():
|
||||
return "Hello World!"
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
from flask import Module
|
||||
|
||||
|
||||
mod = Module(__name__, 'foo', subdomain='foo')
|
||||
mod = Module(__name__, "foo", subdomain="foo")
|
||||
|
|
|
|||
1412
tests/test_basic.py
1412
tests/test_basic.py
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -25,15 +25,22 @@ from click.testing import CliRunner
|
|||
|
||||
from flask import Flask, current_app
|
||||
from flask.cli import (
|
||||
AppGroup, FlaskGroup, NoAppException, ScriptInfo, dotenv, find_best_app,
|
||||
get_version, load_dotenv, locate_app, prepare_import, run_command,
|
||||
with_appcontext
|
||||
AppGroup,
|
||||
FlaskGroup,
|
||||
NoAppException,
|
||||
ScriptInfo,
|
||||
dotenv,
|
||||
find_best_app,
|
||||
get_version,
|
||||
load_dotenv,
|
||||
locate_app,
|
||||
prepare_import,
|
||||
run_command,
|
||||
with_appcontext,
|
||||
)
|
||||
|
||||
cwd = os.getcwd()
|
||||
test_path = os.path.abspath(os.path.join(
|
||||
os.path.dirname(__file__), 'test_apps'
|
||||
))
|
||||
test_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
|
@ -44,6 +51,7 @@ def runner():
|
|||
def test_cli_name(test_apps):
|
||||
"""Make sure the CLI object's name is the app's name and not the app itself"""
|
||||
from cliapp.app import testapp
|
||||
|
||||
assert testapp.cli.name == testapp.name
|
||||
|
||||
|
||||
|
|
@ -52,67 +60,67 @@ def test_find_best_app(test_apps):
|
|||
script_info = ScriptInfo()
|
||||
|
||||
class Module:
|
||||
app = Flask('appname')
|
||||
app = Flask("appname")
|
||||
|
||||
assert find_best_app(script_info, Module) == Module.app
|
||||
|
||||
class Module:
|
||||
application = Flask('appname')
|
||||
application = Flask("appname")
|
||||
|
||||
assert find_best_app(script_info, Module) == Module.application
|
||||
|
||||
class Module:
|
||||
myapp = Flask('appname')
|
||||
myapp = Flask("appname")
|
||||
|
||||
assert find_best_app(script_info, Module) == Module.myapp
|
||||
|
||||
class Module:
|
||||
@staticmethod
|
||||
def create_app():
|
||||
return Flask('appname')
|
||||
return Flask("appname")
|
||||
|
||||
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:
|
||||
@staticmethod
|
||||
def create_app(foo):
|
||||
return Flask('appname')
|
||||
return Flask("appname")
|
||||
|
||||
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:
|
||||
@staticmethod
|
||||
def create_app(foo=None, script_info=None):
|
||||
return Flask('appname')
|
||||
return Flask("appname")
|
||||
|
||||
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:
|
||||
@staticmethod
|
||||
def make_app():
|
||||
return Flask('appname')
|
||||
return Flask("appname")
|
||||
|
||||
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:
|
||||
myapp = Flask('appname1')
|
||||
myapp = Flask("appname1")
|
||||
|
||||
@staticmethod
|
||||
def create_app():
|
||||
return Flask('appname2')
|
||||
return Flask("appname2")
|
||||
|
||||
assert find_best_app(script_info, Module) == Module.myapp
|
||||
|
||||
class Module:
|
||||
myapp = Flask('appname1')
|
||||
myapp = Flask("appname1")
|
||||
|
||||
@staticmethod
|
||||
def create_app():
|
||||
return Flask('appname2')
|
||||
return Flask("appname2")
|
||||
|
||||
assert find_best_app(script_info, Module) == Module.myapp
|
||||
|
||||
|
|
@ -122,50 +130,56 @@ def test_find_best_app(test_apps):
|
|||
pytest.raises(NoAppException, find_best_app, script_info, Module)
|
||||
|
||||
class Module:
|
||||
myapp1 = Flask('appname1')
|
||||
myapp2 = Flask('appname2')
|
||||
myapp1 = Flask("appname1")
|
||||
myapp2 = Flask("appname2")
|
||||
|
||||
pytest.raises(NoAppException, find_best_app, script_info, Module)
|
||||
|
||||
class Module:
|
||||
@staticmethod
|
||||
def create_app(foo, bar):
|
||||
return Flask('appname2')
|
||||
return Flask("appname2")
|
||||
|
||||
pytest.raises(NoAppException, find_best_app, script_info, Module)
|
||||
|
||||
class Module:
|
||||
@staticmethod
|
||||
def create_app():
|
||||
raise TypeError('bad bad factory!')
|
||||
raise TypeError("bad bad factory!")
|
||||
|
||||
pytest.raises(TypeError, find_best_app, script_info, Module)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('value,path,result', (
|
||||
('test', cwd, 'test'),
|
||||
('test.py', cwd, 'test'),
|
||||
('a/test', os.path.join(cwd, 'a'), 'test'),
|
||||
('test/__init__.py', cwd, 'test'),
|
||||
('test/__init__', cwd, 'test'),
|
||||
# nested package
|
||||
@pytest.mark.parametrize(
|
||||
"value,path,result",
|
||||
(
|
||||
os.path.join(test_path, 'cliapp', 'inner1', '__init__'),
|
||||
test_path, 'cliapp.inner1'
|
||||
("test", cwd, "test"),
|
||||
("test.py", cwd, "test"),
|
||||
("a/test", os.path.join(cwd, "a"), "test"),
|
||||
("test/__init__.py", cwd, "test"),
|
||||
("test/__init__", cwd, "test"),
|
||||
# nested package
|
||||
(
|
||||
os.path.join(test_path, "cliapp", "inner1", "__init__"),
|
||||
test_path,
|
||||
"cliapp.inner1",
|
||||
),
|
||||
(
|
||||
os.path.join(test_path, "cliapp", "inner1", "inner2"),
|
||||
test_path,
|
||||
"cliapp.inner1.inner2",
|
||||
),
|
||||
# dotted name
|
||||
("test.a.b", cwd, "test.a.b"),
|
||||
(os.path.join(test_path, "cliapp.app"), test_path, "cliapp.app"),
|
||||
# not a Python file, will be caught during import
|
||||
(
|
||||
os.path.join(test_path, "cliapp", "message.txt"),
|
||||
test_path,
|
||||
"cliapp.message.txt",
|
||||
),
|
||||
),
|
||||
(
|
||||
os.path.join(test_path, 'cliapp', 'inner1', 'inner2'),
|
||||
test_path, 'cliapp.inner1.inner2'
|
||||
),
|
||||
# dotted name
|
||||
('test.a.b', cwd, 'test.a.b'),
|
||||
(os.path.join(test_path, 'cliapp.app'), test_path, 'cliapp.app'),
|
||||
# not a Python file, will be caught during import
|
||||
(
|
||||
os.path.join(test_path, 'cliapp', 'message.txt'),
|
||||
test_path, 'cliapp.message.txt'
|
||||
),
|
||||
))
|
||||
)
|
||||
def test_prepare_import(request, value, path, result):
|
||||
"""Expect the correct path to be set and the correct import and app names
|
||||
to be returned.
|
||||
|
|
@ -185,42 +199,48 @@ def test_prepare_import(request, value, path, result):
|
|||
assert sys.path[0] == path
|
||||
|
||||
|
||||
@pytest.mark.parametrize('iname,aname,result', (
|
||||
('cliapp.app', None, 'testapp'),
|
||||
('cliapp.app', 'testapp', 'testapp'),
|
||||
('cliapp.factory', None, 'app'),
|
||||
('cliapp.factory', 'create_app', 'app'),
|
||||
('cliapp.factory', 'create_app()', 'app'),
|
||||
# no script_info
|
||||
('cliapp.factory', 'create_app2("foo", "bar")', 'app2_foo_bar'),
|
||||
# trailing comma space
|
||||
('cliapp.factory', 'create_app2("foo", "bar", )', 'app2_foo_bar'),
|
||||
# takes script_info
|
||||
('cliapp.factory', 'create_app3("foo")', 'app3_foo_spam'),
|
||||
# strip whitespace
|
||||
('cliapp.factory', ' create_app () ', 'app'),
|
||||
))
|
||||
@pytest.mark.parametrize(
|
||||
"iname,aname,result",
|
||||
(
|
||||
("cliapp.app", None, "testapp"),
|
||||
("cliapp.app", "testapp", "testapp"),
|
||||
("cliapp.factory", None, "app"),
|
||||
("cliapp.factory", "create_app", "app"),
|
||||
("cliapp.factory", "create_app()", "app"),
|
||||
# no script_info
|
||||
("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),
|
||||
# trailing comma space
|
||||
("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),
|
||||
# takes script_info
|
||||
("cliapp.factory", 'create_app3("foo")', "app3_foo_spam"),
|
||||
# strip whitespace
|
||||
("cliapp.factory", " create_app () ", "app"),
|
||||
),
|
||||
)
|
||||
def test_locate_app(test_apps, iname, aname, result):
|
||||
info = ScriptInfo()
|
||||
info.data['test'] = 'spam'
|
||||
info.data["test"] = "spam"
|
||||
assert locate_app(info, iname, aname).name == result
|
||||
|
||||
|
||||
@pytest.mark.parametrize('iname,aname', (
|
||||
('notanapp.py', None),
|
||||
('cliapp/app', None),
|
||||
('cliapp.app', 'notanapp'),
|
||||
# not enough arguments
|
||||
('cliapp.factory', 'create_app2("foo")'),
|
||||
# invalid identifier
|
||||
('cliapp.factory', 'create_app('),
|
||||
# no app returned
|
||||
('cliapp.factory', 'no_app'),
|
||||
# nested import error
|
||||
('cliapp.importerrorapp', None),
|
||||
# not a Python file
|
||||
('cliapp.message.txt', None),
|
||||
))
|
||||
@pytest.mark.parametrize(
|
||||
"iname,aname",
|
||||
(
|
||||
("notanapp.py", None),
|
||||
("cliapp/app", None),
|
||||
("cliapp.app", "notanapp"),
|
||||
# not enough arguments
|
||||
("cliapp.factory", 'create_app2("foo")'),
|
||||
# invalid identifier
|
||||
("cliapp.factory", "create_app("),
|
||||
# no app returned
|
||||
("cliapp.factory", "no_app"),
|
||||
# nested import error
|
||||
("cliapp.importerrorapp", None),
|
||||
# not a Python file
|
||||
("cliapp.message.txt", None),
|
||||
),
|
||||
)
|
||||
def test_locate_app_raises(test_apps, iname, aname):
|
||||
info = ScriptInfo()
|
||||
|
||||
|
|
@ -230,14 +250,12 @@ def test_locate_app_raises(test_apps, iname, aname):
|
|||
|
||||
def test_locate_app_suppress_raise():
|
||||
info = ScriptInfo()
|
||||
app = locate_app(info, 'notanapp.py', None, raise_if_not_found=False)
|
||||
app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)
|
||||
assert app is None
|
||||
|
||||
# only direct import error is suppressed
|
||||
with pytest.raises(NoAppException):
|
||||
locate_app(
|
||||
info, 'cliapp.importerrorapp', None, raise_if_not_found=False
|
||||
)
|
||||
locate_app(info, "cliapp.importerrorapp", None, raise_if_not_found=False)
|
||||
|
||||
|
||||
def test_get_version(test_apps, capsys):
|
||||
|
|
@ -249,7 +267,8 @@ def test_get_version(test_apps, capsys):
|
|||
resilient_parsing = False
|
||||
color = None
|
||||
|
||||
def exit(self): return
|
||||
def exit(self):
|
||||
return
|
||||
|
||||
ctx = MockCtx()
|
||||
get_version(ctx, None, "test")
|
||||
|
|
@ -267,15 +286,16 @@ def test_scriptinfo(test_apps, monkeypatch):
|
|||
assert obj.load_app() is app
|
||||
|
||||
# import app with module's absolute path
|
||||
cli_app_path = os.path.abspath(os.path.join(
|
||||
os.path.dirname(__file__), 'test_apps', 'cliapp', 'app.py'))
|
||||
cli_app_path = os.path.abspath(
|
||||
os.path.join(os.path.dirname(__file__), "test_apps", "cliapp", "app.py")
|
||||
)
|
||||
obj = ScriptInfo(app_import_path=cli_app_path)
|
||||
app = obj.load_app()
|
||||
assert app.name == 'testapp'
|
||||
assert app.name == "testapp"
|
||||
assert obj.load_app() is app
|
||||
obj = ScriptInfo(app_import_path=cli_app_path + ':testapp')
|
||||
obj = ScriptInfo(app_import_path=cli_app_path + ":testapp")
|
||||
app = obj.load_app()
|
||||
assert app.name == 'testapp'
|
||||
assert app.name == "testapp"
|
||||
assert obj.load_app() is app
|
||||
|
||||
def create_app(info):
|
||||
|
|
@ -290,20 +310,22 @@ def test_scriptinfo(test_apps, monkeypatch):
|
|||
pytest.raises(NoAppException, obj.load_app)
|
||||
|
||||
# import app from wsgi.py in current directory
|
||||
monkeypatch.chdir(os.path.abspath(os.path.join(
|
||||
os.path.dirname(__file__), 'test_apps', 'helloworld'
|
||||
)))
|
||||
monkeypatch.chdir(
|
||||
os.path.abspath(
|
||||
os.path.join(os.path.dirname(__file__), "test_apps", "helloworld")
|
||||
)
|
||||
)
|
||||
obj = ScriptInfo()
|
||||
app = obj.load_app()
|
||||
assert app.name == 'hello'
|
||||
assert app.name == "hello"
|
||||
|
||||
# import app from app.py in current directory
|
||||
monkeypatch.chdir(os.path.abspath(os.path.join(
|
||||
os.path.dirname(__file__), 'test_apps', 'cliapp'
|
||||
)))
|
||||
monkeypatch.chdir(
|
||||
os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps", "cliapp"))
|
||||
)
|
||||
obj = ScriptInfo()
|
||||
app = obj.load_app()
|
||||
assert app.name == 'testapp'
|
||||
assert app.name == "testapp"
|
||||
|
||||
|
||||
def test_with_appcontext(runner):
|
||||
|
|
@ -318,7 +340,7 @@ def test_with_appcontext(runner):
|
|||
|
||||
result = runner.invoke(testcmd, obj=obj)
|
||||
assert result.exit_code == 0
|
||||
assert result.output == 'testapp\n'
|
||||
assert result.output == "testapp\n"
|
||||
|
||||
|
||||
def test_appgroup(runner):
|
||||
|
|
@ -342,13 +364,13 @@ def test_appgroup(runner):
|
|||
|
||||
obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))
|
||||
|
||||
result = runner.invoke(cli, ['test'], obj=obj)
|
||||
result = runner.invoke(cli, ["test"], obj=obj)
|
||||
assert result.exit_code == 0
|
||||
assert result.output == 'testappgroup\n'
|
||||
assert result.output == "testappgroup\n"
|
||||
|
||||
result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)
|
||||
result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)
|
||||
assert result.exit_code == 0
|
||||
assert result.output == 'testappgroup\n'
|
||||
assert result.output == "testappgroup\n"
|
||||
|
||||
|
||||
def test_flaskgroup(runner):
|
||||
|
|
@ -365,12 +387,12 @@ def test_flaskgroup(runner):
|
|||
def test():
|
||||
click.echo(current_app.name)
|
||||
|
||||
result = runner.invoke(cli, ['test'])
|
||||
result = runner.invoke(cli, ["test"])
|
||||
assert result.exit_code == 0
|
||||
assert result.output == 'flaskgroup\n'
|
||||
assert result.output == "flaskgroup\n"
|
||||
|
||||
|
||||
@pytest.mark.parametrize('set_debug_flag', (True, False))
|
||||
@pytest.mark.parametrize("set_debug_flag", (True, False))
|
||||
def test_flaskgroup_debug(runner, set_debug_flag):
|
||||
"""Test FlaskGroup debug flag behavior."""
|
||||
|
||||
|
|
@ -387,9 +409,9 @@ def test_flaskgroup_debug(runner, set_debug_flag):
|
|||
def test():
|
||||
click.echo(str(current_app.debug))
|
||||
|
||||
result = runner.invoke(cli, ['test'])
|
||||
result = runner.invoke(cli, ["test"])
|
||||
assert result.exit_code == 0
|
||||
assert result.output == '%s\n' % str(not set_debug_flag)
|
||||
assert result.output == "%s\n" % str(not set_debug_flag)
|
||||
|
||||
|
||||
def test_print_exceptions(runner):
|
||||
|
|
@ -403,10 +425,10 @@ def test_print_exceptions(runner):
|
|||
def cli(**params):
|
||||
pass
|
||||
|
||||
result = runner.invoke(cli, ['--help'])
|
||||
result = runner.invoke(cli, ["--help"])
|
||||
assert result.exit_code == 0
|
||||
assert 'Exception: oh no' in result.output
|
||||
assert 'Traceback' in result.output
|
||||
assert "Exception: oh no" in result.output
|
||||
assert "Traceback" in result.output
|
||||
|
||||
|
||||
class TestRoutes:
|
||||
|
|
@ -416,11 +438,11 @@ class TestRoutes:
|
|||
app = Flask(__name__)
|
||||
app.testing = True
|
||||
|
||||
@app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])
|
||||
@app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])
|
||||
def yyy_get_post(x, y):
|
||||
pass
|
||||
|
||||
@app.route('/zzz_post', methods=['POST'])
|
||||
@app.route("/zzz_post", methods=["POST"])
|
||||
def aaa_post():
|
||||
pass
|
||||
|
||||
|
|
@ -444,138 +466,132 @@ class TestRoutes:
|
|||
# skip the header and match the start of each row
|
||||
for expect, line in zip(order, output.splitlines()[2:]):
|
||||
# do this instead of startswith for nicer pytest output
|
||||
assert line[:len(expect)] == expect
|
||||
assert line[: len(expect)] == expect
|
||||
|
||||
def test_simple(self, invoke):
|
||||
result = invoke(['routes'])
|
||||
result = invoke(["routes"])
|
||||
assert result.exit_code == 0
|
||||
self.expect_order(
|
||||
['aaa_post', 'static', 'yyy_get_post'],
|
||||
result.output
|
||||
)
|
||||
self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)
|
||||
|
||||
def test_sort(self, invoke):
|
||||
default_output = invoke(['routes']).output
|
||||
endpoint_output = invoke(['routes', '-s', 'endpoint']).output
|
||||
default_output = invoke(["routes"]).output
|
||||
endpoint_output = invoke(["routes", "-s", "endpoint"]).output
|
||||
assert default_output == endpoint_output
|
||||
self.expect_order(
|
||||
['static', 'yyy_get_post', 'aaa_post'],
|
||||
invoke(['routes', '-s', 'methods']).output
|
||||
["static", "yyy_get_post", "aaa_post"],
|
||||
invoke(["routes", "-s", "methods"]).output,
|
||||
)
|
||||
self.expect_order(
|
||||
['yyy_get_post', 'static', 'aaa_post'],
|
||||
invoke(['routes', '-s', 'rule']).output
|
||||
["yyy_get_post", "static", "aaa_post"],
|
||||
invoke(["routes", "-s", "rule"]).output,
|
||||
)
|
||||
self.expect_order(
|
||||
['aaa_post', 'yyy_get_post', 'static'],
|
||||
invoke(['routes', '-s', 'match']).output
|
||||
["aaa_post", "yyy_get_post", "static"],
|
||||
invoke(["routes", "-s", "match"]).output,
|
||||
)
|
||||
|
||||
def test_all_methods(self, invoke):
|
||||
output = invoke(['routes']).output
|
||||
assert 'GET, HEAD, OPTIONS, POST' not in output
|
||||
output = invoke(['routes', '--all-methods']).output
|
||||
assert 'GET, HEAD, OPTIONS, POST' in output
|
||||
output = invoke(["routes"]).output
|
||||
assert "GET, HEAD, OPTIONS, POST" not in output
|
||||
output = invoke(["routes", "--all-methods"]).output
|
||||
assert "GET, HEAD, OPTIONS, POST" in output
|
||||
|
||||
def test_no_routes(self, invoke_no_routes):
|
||||
result = invoke_no_routes(['routes'])
|
||||
result = invoke_no_routes(["routes"])
|
||||
assert result.exit_code == 0
|
||||
assert 'No routes were registered.' in result.output
|
||||
assert "No routes were registered." in result.output
|
||||
|
||||
|
||||
need_dotenv = pytest.mark.skipif(
|
||||
dotenv is None, reason='dotenv is not installed'
|
||||
)
|
||||
need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")
|
||||
|
||||
|
||||
@need_dotenv
|
||||
def test_load_dotenv(monkeypatch):
|
||||
# can't use monkeypatch.delitem since the keys don't exist yet
|
||||
for item in ('FOO', 'BAR', 'SPAM'):
|
||||
for item in ("FOO", "BAR", "SPAM"):
|
||||
monkeypatch._setitem.append((os.environ, item, notset))
|
||||
|
||||
monkeypatch.setenv('EGGS', '3')
|
||||
monkeypatch.chdir(os.path.join(test_path, 'cliapp', 'inner1'))
|
||||
monkeypatch.setenv("EGGS", "3")
|
||||
monkeypatch.chdir(os.path.join(test_path, "cliapp", "inner1"))
|
||||
load_dotenv()
|
||||
assert os.getcwd() == test_path
|
||||
# .flaskenv doesn't overwrite .env
|
||||
assert os.environ['FOO'] == 'env'
|
||||
assert os.environ["FOO"] == "env"
|
||||
# set only in .flaskenv
|
||||
assert os.environ['BAR'] == 'bar'
|
||||
assert os.environ["BAR"] == "bar"
|
||||
# set only in .env
|
||||
assert os.environ['SPAM'] == '1'
|
||||
assert os.environ["SPAM"] == "1"
|
||||
# set manually, files don't overwrite
|
||||
assert os.environ['EGGS'] == '3'
|
||||
assert os.environ["EGGS"] == "3"
|
||||
|
||||
|
||||
@need_dotenv
|
||||
def test_dotenv_path(monkeypatch):
|
||||
for item in ('FOO', 'BAR', 'EGGS'):
|
||||
for item in ("FOO", "BAR", "EGGS"):
|
||||
monkeypatch._setitem.append((os.environ, item, notset))
|
||||
|
||||
cwd = os.getcwd()
|
||||
load_dotenv(os.path.join(test_path, '.flaskenv'))
|
||||
load_dotenv(os.path.join(test_path, ".flaskenv"))
|
||||
assert os.getcwd() == cwd
|
||||
assert 'FOO' in os.environ
|
||||
assert "FOO" in os.environ
|
||||
|
||||
|
||||
def test_dotenv_optional(monkeypatch):
|
||||
monkeypatch.setattr('flask.cli.dotenv', None)
|
||||
monkeypatch.setattr("flask.cli.dotenv", None)
|
||||
monkeypatch.chdir(test_path)
|
||||
load_dotenv()
|
||||
assert 'FOO' not in os.environ
|
||||
assert "FOO" not in os.environ
|
||||
|
||||
|
||||
@need_dotenv
|
||||
def test_disable_dotenv_from_env(monkeypatch, runner):
|
||||
monkeypatch.chdir(test_path)
|
||||
monkeypatch.setitem(os.environ, 'FLASK_SKIP_DOTENV', '1')
|
||||
monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")
|
||||
runner.invoke(FlaskGroup())
|
||||
assert 'FOO' not in os.environ
|
||||
assert "FOO" not in os.environ
|
||||
|
||||
|
||||
def test_run_cert_path():
|
||||
# no key
|
||||
with pytest.raises(click.BadParameter):
|
||||
run_command.make_context('run', ['--cert', __file__])
|
||||
run_command.make_context("run", ["--cert", __file__])
|
||||
|
||||
# no cert
|
||||
with pytest.raises(click.BadParameter):
|
||||
run_command.make_context('run', ['--key', __file__])
|
||||
run_command.make_context("run", ["--key", __file__])
|
||||
|
||||
ctx = run_command.make_context(
|
||||
'run', ['--cert', __file__, '--key', __file__])
|
||||
assert ctx.params['cert'] == (__file__, __file__)
|
||||
ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])
|
||||
assert ctx.params["cert"] == (__file__, __file__)
|
||||
|
||||
|
||||
def test_run_cert_adhoc(monkeypatch):
|
||||
monkeypatch.setitem(sys.modules, 'OpenSSL', None)
|
||||
monkeypatch.setitem(sys.modules, "OpenSSL", None)
|
||||
|
||||
# pyOpenSSL not installed
|
||||
with pytest.raises(click.BadParameter):
|
||||
run_command.make_context('run', ['--cert', 'adhoc'])
|
||||
run_command.make_context("run", ["--cert", "adhoc"])
|
||||
|
||||
# pyOpenSSL installed
|
||||
monkeypatch.setitem(sys.modules, 'OpenSSL', types.ModuleType('OpenSSL'))
|
||||
ctx = run_command.make_context('run', ['--cert', 'adhoc'])
|
||||
assert ctx.params['cert'] == 'adhoc'
|
||||
monkeypatch.setitem(sys.modules, "OpenSSL", types.ModuleType("OpenSSL"))
|
||||
ctx = run_command.make_context("run", ["--cert", "adhoc"])
|
||||
assert ctx.params["cert"] == "adhoc"
|
||||
|
||||
# no key with adhoc
|
||||
with pytest.raises(click.BadParameter):
|
||||
run_command.make_context('run', ['--cert', 'adhoc', '--key', __file__])
|
||||
run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])
|
||||
|
||||
|
||||
def test_run_cert_import(monkeypatch):
|
||||
monkeypatch.setitem(sys.modules, 'not_here', None)
|
||||
monkeypatch.setitem(sys.modules, "not_here", None)
|
||||
|
||||
# ImportError
|
||||
with pytest.raises(click.BadParameter):
|
||||
run_command.make_context('run', ['--cert', 'not_here'])
|
||||
run_command.make_context("run", ["--cert", "not_here"])
|
||||
|
||||
# not an SSLContext
|
||||
if sys.version_info >= (2, 7, 9):
|
||||
with pytest.raises(click.BadParameter):
|
||||
run_command.make_context('run', ['--cert', 'flask'])
|
||||
run_command.make_context("run", ["--cert", "flask"])
|
||||
|
||||
# SSLContext
|
||||
if sys.version_info < (2, 7, 9):
|
||||
|
|
@ -583,11 +599,10 @@ def test_run_cert_import(monkeypatch):
|
|||
else:
|
||||
ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
|
||||
|
||||
monkeypatch.setitem(sys.modules, 'ssl_context', ssl_context)
|
||||
ctx = run_command.make_context('run', ['--cert', 'ssl_context'])
|
||||
assert ctx.params['cert'] is ssl_context
|
||||
monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)
|
||||
ctx = run_command.make_context("run", ["--cert", "ssl_context"])
|
||||
assert ctx.params["cert"] is ssl_context
|
||||
|
||||
# no --key with SSLContext
|
||||
with pytest.raises(click.BadParameter):
|
||||
run_command.make_context(
|
||||
'run', ['--cert', 'ssl_context', '--key', __file__])
|
||||
run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])
|
||||
|
|
|
|||
|
|
@ -17,19 +17,19 @@ import pytest
|
|||
|
||||
|
||||
# config keys used for the TestConfig
|
||||
TEST_KEY = 'foo'
|
||||
SECRET_KEY = 'config'
|
||||
TEST_KEY = "foo"
|
||||
SECRET_KEY = "config"
|
||||
|
||||
|
||||
def common_object_test(app):
|
||||
assert app.secret_key == 'config'
|
||||
assert app.config['TEST_KEY'] == 'foo'
|
||||
assert 'TestConfig' not in app.config
|
||||
assert app.secret_key == "config"
|
||||
assert app.config["TEST_KEY"] == "foo"
|
||||
assert "TestConfig" not in app.config
|
||||
|
||||
|
||||
def test_config_from_file():
|
||||
app = flask.Flask(__name__)
|
||||
app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')
|
||||
app.config.from_pyfile(__file__.rsplit(".", 1)[0] + ".py")
|
||||
common_object_test(app)
|
||||
|
||||
|
||||
|
|
@ -42,45 +42,34 @@ def test_config_from_object():
|
|||
def test_config_from_json():
|
||||
app = flask.Flask(__name__)
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
app.config.from_json(os.path.join(current_dir, 'static', 'config.json'))
|
||||
app.config.from_json(os.path.join(current_dir, "static", "config.json"))
|
||||
common_object_test(app)
|
||||
|
||||
|
||||
def test_config_from_mapping():
|
||||
app = flask.Flask(__name__)
|
||||
app.config.from_mapping({
|
||||
'SECRET_KEY': 'config',
|
||||
'TEST_KEY': 'foo'
|
||||
})
|
||||
app.config.from_mapping({"SECRET_KEY": "config", "TEST_KEY": "foo"})
|
||||
common_object_test(app)
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
app.config.from_mapping([
|
||||
('SECRET_KEY', 'config'),
|
||||
('TEST_KEY', 'foo')
|
||||
])
|
||||
app.config.from_mapping([("SECRET_KEY", "config"), ("TEST_KEY", "foo")])
|
||||
common_object_test(app)
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
app.config.from_mapping(
|
||||
SECRET_KEY='config',
|
||||
TEST_KEY='foo'
|
||||
)
|
||||
app.config.from_mapping(SECRET_KEY="config", TEST_KEY="foo")
|
||||
common_object_test(app)
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
with pytest.raises(TypeError):
|
||||
app.config.from_mapping(
|
||||
{}, {}
|
||||
)
|
||||
app.config.from_mapping({}, {})
|
||||
|
||||
|
||||
def test_config_from_class():
|
||||
class Base(object):
|
||||
TEST_KEY = 'foo'
|
||||
TEST_KEY = "foo"
|
||||
|
||||
class Test(Base):
|
||||
SECRET_KEY = 'config'
|
||||
SECRET_KEY = "config"
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
app.config.from_object(Test)
|
||||
|
|
@ -93,12 +82,12 @@ def test_config_from_envvar():
|
|||
os.environ = {}
|
||||
app = flask.Flask(__name__)
|
||||
with pytest.raises(RuntimeError) as e:
|
||||
app.config.from_envvar('FOO_SETTINGS')
|
||||
app.config.from_envvar("FOO_SETTINGS")
|
||||
assert "'FOO_SETTINGS' is not set" in str(e.value)
|
||||
assert not app.config.from_envvar('FOO_SETTINGS', silent=True)
|
||||
assert not app.config.from_envvar("FOO_SETTINGS", silent=True)
|
||||
|
||||
os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}
|
||||
assert app.config.from_envvar('FOO_SETTINGS')
|
||||
os.environ = {"FOO_SETTINGS": __file__.rsplit(".", 1)[0] + ".py"}
|
||||
assert app.config.from_envvar("FOO_SETTINGS")
|
||||
common_object_test(app)
|
||||
finally:
|
||||
os.environ = env
|
||||
|
|
@ -107,15 +96,17 @@ def test_config_from_envvar():
|
|||
def test_config_from_envvar_missing():
|
||||
env = os.environ
|
||||
try:
|
||||
os.environ = {'FOO_SETTINGS': 'missing.cfg'}
|
||||
os.environ = {"FOO_SETTINGS": "missing.cfg"}
|
||||
with pytest.raises(IOError) as e:
|
||||
app = flask.Flask(__name__)
|
||||
app.config.from_envvar('FOO_SETTINGS')
|
||||
app.config.from_envvar("FOO_SETTINGS")
|
||||
msg = str(e.value)
|
||||
assert msg.startswith('[Errno 2] Unable to load configuration '
|
||||
'file (No such file or directory):')
|
||||
assert msg.startswith(
|
||||
"[Errno 2] Unable to load configuration "
|
||||
"file (No such file or directory):"
|
||||
)
|
||||
assert msg.endswith("missing.cfg'")
|
||||
assert not app.config.from_envvar('FOO_SETTINGS', silent=True)
|
||||
assert not app.config.from_envvar("FOO_SETTINGS", silent=True)
|
||||
finally:
|
||||
os.environ = env
|
||||
|
||||
|
|
@ -123,23 +114,25 @@ def test_config_from_envvar_missing():
|
|||
def test_config_missing():
|
||||
app = flask.Flask(__name__)
|
||||
with pytest.raises(IOError) as e:
|
||||
app.config.from_pyfile('missing.cfg')
|
||||
app.config.from_pyfile("missing.cfg")
|
||||
msg = str(e.value)
|
||||
assert msg.startswith('[Errno 2] Unable to load configuration '
|
||||
'file (No such file or directory):')
|
||||
assert msg.startswith(
|
||||
"[Errno 2] Unable to load configuration " "file (No such file or directory):"
|
||||
)
|
||||
assert msg.endswith("missing.cfg'")
|
||||
assert not app.config.from_pyfile('missing.cfg', silent=True)
|
||||
assert not app.config.from_pyfile("missing.cfg", silent=True)
|
||||
|
||||
|
||||
def test_config_missing_json():
|
||||
app = flask.Flask(__name__)
|
||||
with pytest.raises(IOError) as e:
|
||||
app.config.from_json('missing.json')
|
||||
app.config.from_json("missing.json")
|
||||
msg = str(e.value)
|
||||
assert msg.startswith('[Errno 2] Unable to load configuration '
|
||||
'file (No such file or directory):')
|
||||
assert msg.startswith(
|
||||
"[Errno 2] Unable to load configuration " "file (No such file or directory):"
|
||||
)
|
||||
assert msg.endswith("missing.json'")
|
||||
assert not app.config.from_json('missing.json', silent=True)
|
||||
assert not app.config.from_json("missing.json", silent=True)
|
||||
|
||||
|
||||
def test_custom_config_class():
|
||||
|
|
@ -148,6 +141,7 @@ def test_custom_config_class():
|
|||
|
||||
class Flask(flask.Flask):
|
||||
config_class = Config
|
||||
|
||||
app = Flask(__name__)
|
||||
assert isinstance(app.config, Config)
|
||||
app.config.from_object(__name__)
|
||||
|
|
@ -156,52 +150,60 @@ def test_custom_config_class():
|
|||
|
||||
def test_session_lifetime():
|
||||
app = flask.Flask(__name__)
|
||||
app.config['PERMANENT_SESSION_LIFETIME'] = 42
|
||||
app.config["PERMANENT_SESSION_LIFETIME"] = 42
|
||||
assert app.permanent_session_lifetime.seconds == 42
|
||||
|
||||
|
||||
def test_send_file_max_age():
|
||||
app = flask.Flask(__name__)
|
||||
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600
|
||||
app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 3600
|
||||
assert app.send_file_max_age_default.seconds == 3600
|
||||
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(hours=2)
|
||||
app.config["SEND_FILE_MAX_AGE_DEFAULT"] = timedelta(hours=2)
|
||||
assert app.send_file_max_age_default.seconds == 7200
|
||||
|
||||
|
||||
def test_get_namespace():
|
||||
app = flask.Flask(__name__)
|
||||
app.config['FOO_OPTION_1'] = 'foo option 1'
|
||||
app.config['FOO_OPTION_2'] = 'foo option 2'
|
||||
app.config['BAR_STUFF_1'] = 'bar stuff 1'
|
||||
app.config['BAR_STUFF_2'] = 'bar stuff 2'
|
||||
foo_options = app.config.get_namespace('FOO_')
|
||||
app.config["FOO_OPTION_1"] = "foo option 1"
|
||||
app.config["FOO_OPTION_2"] = "foo option 2"
|
||||
app.config["BAR_STUFF_1"] = "bar stuff 1"
|
||||
app.config["BAR_STUFF_2"] = "bar stuff 2"
|
||||
foo_options = app.config.get_namespace("FOO_")
|
||||
assert 2 == len(foo_options)
|
||||
assert 'foo option 1' == foo_options['option_1']
|
||||
assert 'foo option 2' == foo_options['option_2']
|
||||
bar_options = app.config.get_namespace('BAR_', lowercase=False)
|
||||
assert "foo option 1" == foo_options["option_1"]
|
||||
assert "foo option 2" == foo_options["option_2"]
|
||||
bar_options = app.config.get_namespace("BAR_", lowercase=False)
|
||||
assert 2 == len(bar_options)
|
||||
assert 'bar stuff 1' == bar_options['STUFF_1']
|
||||
assert 'bar stuff 2' == bar_options['STUFF_2']
|
||||
foo_options = app.config.get_namespace('FOO_', trim_namespace=False)
|
||||
assert "bar stuff 1" == bar_options["STUFF_1"]
|
||||
assert "bar stuff 2" == bar_options["STUFF_2"]
|
||||
foo_options = app.config.get_namespace("FOO_", trim_namespace=False)
|
||||
assert 2 == len(foo_options)
|
||||
assert 'foo option 1' == foo_options['foo_option_1']
|
||||
assert 'foo option 2' == foo_options['foo_option_2']
|
||||
bar_options = app.config.get_namespace('BAR_', lowercase=False, trim_namespace=False)
|
||||
assert "foo option 1" == foo_options["foo_option_1"]
|
||||
assert "foo option 2" == foo_options["foo_option_2"]
|
||||
bar_options = app.config.get_namespace(
|
||||
"BAR_", lowercase=False, trim_namespace=False
|
||||
)
|
||||
assert 2 == len(bar_options)
|
||||
assert 'bar stuff 1' == bar_options['BAR_STUFF_1']
|
||||
assert 'bar stuff 2' == bar_options['BAR_STUFF_2']
|
||||
assert "bar stuff 1" == bar_options["BAR_STUFF_1"]
|
||||
assert "bar stuff 2" == bar_options["BAR_STUFF_2"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('encoding', ['utf-8', 'iso-8859-15', 'latin-1'])
|
||||
@pytest.mark.parametrize("encoding", ["utf-8", "iso-8859-15", "latin-1"])
|
||||
def test_from_pyfile_weird_encoding(tmpdir, encoding):
|
||||
f = tmpdir.join('my_config.py')
|
||||
f.write_binary(textwrap.dedent(u'''
|
||||
f = tmpdir.join("my_config.py")
|
||||
f.write_binary(
|
||||
textwrap.dedent(
|
||||
u"""
|
||||
# -*- coding: {0} -*-
|
||||
TEST_VALUE = "föö"
|
||||
'''.format(encoding)).encode(encoding))
|
||||
""".format(
|
||||
encoding
|
||||
)
|
||||
).encode(encoding)
|
||||
)
|
||||
app = flask.Flask(__name__)
|
||||
app.config.from_pyfile(str(f))
|
||||
value = app.config['TEST_VALUE']
|
||||
value = app.config["TEST_VALUE"]
|
||||
if PY2:
|
||||
value = value.decode(encoding)
|
||||
assert value == u'föö'
|
||||
assert value == u"föö"
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -17,112 +17,120 @@ from flask._compat import PY2
|
|||
|
||||
def test_explicit_instance_paths(modules_tmpdir):
|
||||
with pytest.raises(ValueError) as excinfo:
|
||||
flask.Flask(__name__, instance_path='instance')
|
||||
assert 'must be absolute' in str(excinfo.value)
|
||||
flask.Flask(__name__, instance_path="instance")
|
||||
assert "must be absolute" in str(excinfo.value)
|
||||
|
||||
app = flask.Flask(__name__, instance_path=str(modules_tmpdir))
|
||||
assert app.instance_path == str(modules_tmpdir)
|
||||
|
||||
|
||||
def test_main_module_paths(modules_tmpdir, purge_module):
|
||||
app = modules_tmpdir.join('main_app.py')
|
||||
app = modules_tmpdir.join("main_app.py")
|
||||
app.write('import flask\n\napp = flask.Flask("__main__")')
|
||||
purge_module('main_app')
|
||||
purge_module("main_app")
|
||||
|
||||
from main_app import app
|
||||
|
||||
here = os.path.abspath(os.getcwd())
|
||||
assert app.instance_path == os.path.join(here, 'instance')
|
||||
assert app.instance_path == os.path.join(here, "instance")
|
||||
|
||||
|
||||
def test_uninstalled_module_paths(modules_tmpdir, purge_module):
|
||||
app = modules_tmpdir.join('config_module_app.py').write(
|
||||
'import os\n'
|
||||
'import flask\n'
|
||||
'here = os.path.abspath(os.path.dirname(__file__))\n'
|
||||
'app = flask.Flask(__name__)\n'
|
||||
app = modules_tmpdir.join("config_module_app.py").write(
|
||||
"import os\n"
|
||||
"import flask\n"
|
||||
"here = os.path.abspath(os.path.dirname(__file__))\n"
|
||||
"app = flask.Flask(__name__)\n"
|
||||
)
|
||||
purge_module('config_module_app')
|
||||
purge_module("config_module_app")
|
||||
|
||||
from config_module_app import app
|
||||
assert app.instance_path == str(modules_tmpdir.join('instance'))
|
||||
|
||||
assert app.instance_path == str(modules_tmpdir.join("instance"))
|
||||
|
||||
|
||||
def test_uninstalled_package_paths(modules_tmpdir, purge_module):
|
||||
app = modules_tmpdir.mkdir('config_package_app')
|
||||
init = app.join('__init__.py')
|
||||
app = modules_tmpdir.mkdir("config_package_app")
|
||||
init = app.join("__init__.py")
|
||||
init.write(
|
||||
'import os\n'
|
||||
'import flask\n'
|
||||
'here = os.path.abspath(os.path.dirname(__file__))\n'
|
||||
'app = flask.Flask(__name__)\n'
|
||||
"import os\n"
|
||||
"import flask\n"
|
||||
"here = os.path.abspath(os.path.dirname(__file__))\n"
|
||||
"app = flask.Flask(__name__)\n"
|
||||
)
|
||||
purge_module('config_package_app')
|
||||
purge_module("config_package_app")
|
||||
|
||||
from config_package_app import app
|
||||
assert app.instance_path == str(modules_tmpdir.join('instance'))
|
||||
|
||||
assert app.instance_path == str(modules_tmpdir.join("instance"))
|
||||
|
||||
|
||||
def test_installed_module_paths(modules_tmpdir, modules_tmpdir_prefix,
|
||||
purge_module, site_packages, limit_loader):
|
||||
site_packages.join('site_app.py').write(
|
||||
'import flask\n'
|
||||
'app = flask.Flask(__name__)\n'
|
||||
def test_installed_module_paths(
|
||||
modules_tmpdir, modules_tmpdir_prefix, purge_module, site_packages, limit_loader
|
||||
):
|
||||
site_packages.join("site_app.py").write(
|
||||
"import flask\n" "app = flask.Flask(__name__)\n"
|
||||
)
|
||||
purge_module('site_app')
|
||||
purge_module("site_app")
|
||||
|
||||
from site_app import app
|
||||
assert app.instance_path == \
|
||||
modules_tmpdir.join('var').join('site_app-instance')
|
||||
|
||||
assert app.instance_path == modules_tmpdir.join("var").join("site_app-instance")
|
||||
|
||||
|
||||
def test_installed_package_paths(limit_loader, modules_tmpdir,
|
||||
modules_tmpdir_prefix, purge_module,
|
||||
monkeypatch):
|
||||
installed_path = modules_tmpdir.mkdir('path')
|
||||
def test_installed_package_paths(
|
||||
limit_loader, modules_tmpdir, modules_tmpdir_prefix, purge_module, monkeypatch
|
||||
):
|
||||
installed_path = modules_tmpdir.mkdir("path")
|
||||
monkeypatch.syspath_prepend(installed_path)
|
||||
|
||||
app = installed_path.mkdir('installed_package')
|
||||
init = app.join('__init__.py')
|
||||
init.write('import flask\napp = flask.Flask(__name__)')
|
||||
purge_module('installed_package')
|
||||
app = installed_path.mkdir("installed_package")
|
||||
init = app.join("__init__.py")
|
||||
init.write("import flask\napp = flask.Flask(__name__)")
|
||||
purge_module("installed_package")
|
||||
|
||||
from installed_package import app
|
||||
assert app.instance_path == \
|
||||
modules_tmpdir.join('var').join('installed_package-instance')
|
||||
|
||||
assert app.instance_path == modules_tmpdir.join("var").join(
|
||||
"installed_package-instance"
|
||||
)
|
||||
|
||||
|
||||
def test_prefix_package_paths(limit_loader, modules_tmpdir,
|
||||
modules_tmpdir_prefix, purge_module,
|
||||
site_packages):
|
||||
app = site_packages.mkdir('site_package')
|
||||
init = app.join('__init__.py')
|
||||
init.write('import flask\napp = flask.Flask(__name__)')
|
||||
purge_module('site_package')
|
||||
def test_prefix_package_paths(
|
||||
limit_loader, modules_tmpdir, modules_tmpdir_prefix, purge_module, site_packages
|
||||
):
|
||||
app = site_packages.mkdir("site_package")
|
||||
init = app.join("__init__.py")
|
||||
init.write("import flask\napp = flask.Flask(__name__)")
|
||||
purge_module("site_package")
|
||||
|
||||
import site_package
|
||||
assert site_package.app.instance_path == \
|
||||
modules_tmpdir.join('var').join('site_package-instance')
|
||||
|
||||
|
||||
def test_egg_installed_paths(install_egg, modules_tmpdir,
|
||||
modules_tmpdir_prefix):
|
||||
modules_tmpdir.mkdir('site_egg').join('__init__.py').write(
|
||||
'import flask\n\napp = flask.Flask(__name__)'
|
||||
assert site_package.app.instance_path == modules_tmpdir.join("var").join(
|
||||
"site_package-instance"
|
||||
)
|
||||
install_egg('site_egg')
|
||||
|
||||
|
||||
def test_egg_installed_paths(install_egg, modules_tmpdir, modules_tmpdir_prefix):
|
||||
modules_tmpdir.mkdir("site_egg").join("__init__.py").write(
|
||||
"import flask\n\napp = flask.Flask(__name__)"
|
||||
)
|
||||
install_egg("site_egg")
|
||||
try:
|
||||
import site_egg
|
||||
assert site_egg.app.instance_path == \
|
||||
str(modules_tmpdir.join('var/').join('site_egg-instance'))
|
||||
|
||||
assert site_egg.app.instance_path == str(
|
||||
modules_tmpdir.join("var/").join("site_egg-instance")
|
||||
)
|
||||
finally:
|
||||
if 'site_egg' in sys.modules:
|
||||
del sys.modules['site_egg']
|
||||
if "site_egg" in sys.modules:
|
||||
del sys.modules["site_egg"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not PY2, reason='This only works under Python 2.')
|
||||
@pytest.mark.skipif(not PY2, reason="This only works under Python 2.")
|
||||
def test_meta_path_loader_without_is_package(request, modules_tmpdir):
|
||||
app = modules_tmpdir.join('unimportable.py')
|
||||
app.write('import flask\napp = flask.Flask(__name__)')
|
||||
app = modules_tmpdir.join("unimportable.py")
|
||||
app.write("import flask\napp = flask.Flask(__name__)")
|
||||
|
||||
class Loader(object):
|
||||
def find_module(self, name, path=None):
|
||||
|
|
|
|||
|
|
@ -16,18 +16,21 @@ from flask import Markup
|
|||
from flask.json.tag import TaggedJSONSerializer, JSONTag
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data", (
|
||||
{' t': (1, 2, 3)},
|
||||
{' t__': b'a'},
|
||||
{' di': ' di'},
|
||||
{'x': (1, 2, 3), 'y': 4},
|
||||
(1, 2, 3),
|
||||
[(1, 2, 3)],
|
||||
b'\xff',
|
||||
Markup('<html>'),
|
||||
uuid4(),
|
||||
datetime.utcnow().replace(microsecond=0),
|
||||
))
|
||||
@pytest.mark.parametrize(
|
||||
"data",
|
||||
(
|
||||
{" t": (1, 2, 3)},
|
||||
{" t__": b"a"},
|
||||
{" di": " di"},
|
||||
{"x": (1, 2, 3), "y": 4},
|
||||
(1, 2, 3),
|
||||
[(1, 2, 3)],
|
||||
b"\xff",
|
||||
Markup("<html>"),
|
||||
uuid4(),
|
||||
datetime.utcnow().replace(microsecond=0),
|
||||
),
|
||||
)
|
||||
def test_dump_load_unchanged(data):
|
||||
s = TaggedJSONSerializer()
|
||||
assert s.loads(s.dumps(data)) == data
|
||||
|
|
@ -35,12 +38,12 @@ def test_dump_load_unchanged(data):
|
|||
|
||||
def test_duplicate_tag():
|
||||
class TagDict(JSONTag):
|
||||
key = ' d'
|
||||
key = " d"
|
||||
|
||||
s = TaggedJSONSerializer()
|
||||
pytest.raises(KeyError, s.register, TagDict)
|
||||
s.register(TagDict, force=True, index=0)
|
||||
assert isinstance(s.tags[' d'], TagDict)
|
||||
assert isinstance(s.tags[" d"], TagDict)
|
||||
assert isinstance(s.order[0], TagDict)
|
||||
|
||||
|
||||
|
|
@ -51,7 +54,7 @@ def test_custom_tag():
|
|||
|
||||
class TagFoo(JSONTag):
|
||||
__slots__ = ()
|
||||
key = ' f'
|
||||
key = " f"
|
||||
|
||||
def check(self, value):
|
||||
return isinstance(value, Foo)
|
||||
|
|
@ -64,7 +67,7 @@ def test_custom_tag():
|
|||
|
||||
s = TaggedJSONSerializer()
|
||||
s.register(TagFoo)
|
||||
assert s.loads(s.dumps(Foo('bar'))).data == 'bar'
|
||||
assert s.loads(s.dumps(Foo("bar"))).data == "bar"
|
||||
|
||||
|
||||
def test_tag_interface():
|
||||
|
|
@ -76,10 +79,10 @@ def test_tag_interface():
|
|||
|
||||
def test_tag_order():
|
||||
class Tag1(JSONTag):
|
||||
key = ' 1'
|
||||
key = " 1"
|
||||
|
||||
class Tag2(JSONTag):
|
||||
key = ' 2'
|
||||
key = " 2"
|
||||
|
||||
s = TaggedJSONSerializer()
|
||||
|
||||
|
|
|
|||
|
|
@ -13,8 +13,7 @@ import sys
|
|||
import pytest
|
||||
|
||||
from flask._compat import StringIO
|
||||
from flask.logging import default_handler, has_level_handler, \
|
||||
wsgi_errors_stream
|
||||
from flask.logging import default_handler, has_level_handler, wsgi_errors_stream
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
|
|
@ -23,12 +22,11 @@ def reset_logging(pytestconfig):
|
|||
logging.root.handlers = []
|
||||
root_level = logging.root.level
|
||||
|
||||
logger = logging.getLogger('flask.app')
|
||||
logger = logging.getLogger("flask.app")
|
||||
logger.handlers = []
|
||||
logger.setLevel(logging.NOTSET)
|
||||
|
||||
logging_plugin = pytestconfig.pluginmanager.unregister(
|
||||
name='logging-plugin')
|
||||
logging_plugin = pytestconfig.pluginmanager.unregister(name="logging-plugin")
|
||||
|
||||
yield
|
||||
|
||||
|
|
@ -39,11 +37,11 @@ def reset_logging(pytestconfig):
|
|||
logger.setLevel(logging.NOTSET)
|
||||
|
||||
if logging_plugin:
|
||||
pytestconfig.pluginmanager.register(logging_plugin, 'logging-plugin')
|
||||
pytestconfig.pluginmanager.register(logging_plugin, "logging-plugin")
|
||||
|
||||
|
||||
def test_logger(app):
|
||||
assert app.logger.name == 'flask.app'
|
||||
assert app.logger.name == "flask.app"
|
||||
assert app.logger.level == logging.NOTSET
|
||||
assert app.logger.handlers == [default_handler]
|
||||
|
||||
|
|
@ -61,14 +59,14 @@ def test_existing_handler(app):
|
|||
|
||||
|
||||
def test_wsgi_errors_stream(app, client):
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
app.logger.error('test')
|
||||
return ''
|
||||
app.logger.error("test")
|
||||
return ""
|
||||
|
||||
stream = StringIO()
|
||||
client.get('/', errors_stream=stream)
|
||||
assert 'ERROR in test_logging: test' in stream.getvalue()
|
||||
client.get("/", errors_stream=stream)
|
||||
assert "ERROR in test_logging: test" in stream.getvalue()
|
||||
|
||||
assert wsgi_errors_stream._get_current_object() is sys.stderr
|
||||
|
||||
|
|
@ -77,7 +75,7 @@ def test_wsgi_errors_stream(app, client):
|
|||
|
||||
|
||||
def test_has_level_handler():
|
||||
logger = logging.getLogger('flask.app')
|
||||
logger = logging.getLogger("flask.app")
|
||||
assert not has_level_handler(logger)
|
||||
|
||||
handler = logging.StreamHandler()
|
||||
|
|
@ -93,15 +91,15 @@ def test_has_level_handler():
|
|||
|
||||
|
||||
def test_log_view_exception(app, client):
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
raise Exception('test')
|
||||
raise Exception("test")
|
||||
|
||||
app.testing = False
|
||||
stream = StringIO()
|
||||
rv = client.get('/', errors_stream=stream)
|
||||
rv = client.get("/", errors_stream=stream)
|
||||
assert rv.status_code == 500
|
||||
assert rv.data
|
||||
err = stream.getvalue()
|
||||
assert 'Exception on / [GET]' in err
|
||||
assert 'Exception: test' in err
|
||||
assert "Exception on / [GET]" in err
|
||||
assert "Exception: test" in err
|
||||
|
|
|
|||
|
|
@ -22,7 +22,6 @@ _gc_lock = threading.Lock()
|
|||
|
||||
|
||||
class assert_no_leak(object):
|
||||
|
||||
def __enter__(self):
|
||||
gc.disable()
|
||||
_gc_lock.acquire()
|
||||
|
|
@ -32,7 +31,7 @@ class assert_no_leak(object):
|
|||
# This is necessary since Python only starts tracking
|
||||
# dicts if they contain mutable objects. It's a horrible,
|
||||
# horrible hack but makes this kinda testable.
|
||||
loc.__storage__['FOOO'] = [1, 2, 3]
|
||||
loc.__storage__["FOOO"] = [1, 2, 3]
|
||||
|
||||
gc.collect()
|
||||
self.old_objects = len(gc.get_objects())
|
||||
|
|
@ -41,7 +40,7 @@ class assert_no_leak(object):
|
|||
gc.collect()
|
||||
new_objects = len(gc.get_objects())
|
||||
if new_objects > self.old_objects:
|
||||
pytest.fail('Example code leaked')
|
||||
pytest.fail("Example code leaked")
|
||||
_gc_lock.release()
|
||||
gc.enable()
|
||||
|
||||
|
|
@ -49,22 +48,21 @@ class assert_no_leak(object):
|
|||
def test_memory_consumption():
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template('simple_template.html', whiskey=42)
|
||||
return flask.render_template("simple_template.html", whiskey=42)
|
||||
|
||||
def fire():
|
||||
with app.test_client() as c:
|
||||
rv = c.get('/')
|
||||
rv = c.get("/")
|
||||
assert rv.status_code == 200
|
||||
assert rv.data == b'<h1>42</h1>'
|
||||
assert 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'):
|
||||
if sys.version_info >= (2, 7) and not hasattr(sys, "pypy_translation_info"):
|
||||
with assert_no_leak():
|
||||
for x in range(10):
|
||||
fire()
|
||||
|
|
@ -72,8 +70,9 @@ def test_memory_consumption():
|
|||
|
||||
def test_safe_join_toplevel_pardir():
|
||||
from flask.helpers import safe_join
|
||||
|
||||
with pytest.raises(NotFound):
|
||||
safe_join('/foo', '..')
|
||||
safe_join("/foo", "..")
|
||||
|
||||
|
||||
def test_aborting(app):
|
||||
|
|
@ -84,16 +83,16 @@ def test_aborting(app):
|
|||
def handle_foo(e):
|
||||
return str(e.whatever)
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
raise flask.abort(flask.redirect(flask.url_for('test')))
|
||||
raise flask.abort(flask.redirect(flask.url_for("test")))
|
||||
|
||||
@app.route('/test')
|
||||
@app.route("/test")
|
||||
def test():
|
||||
raise Foo()
|
||||
|
||||
with app.test_client() as c:
|
||||
rv = c.get('/')
|
||||
assert rv.headers['Location'] == 'http://localhost/test'
|
||||
rv = c.get('/test')
|
||||
assert rv.data == b'42'
|
||||
rv = c.get("/")
|
||||
assert rv.headers["Location"] == "http://localhost/test"
|
||||
rv = c.get("/test")
|
||||
assert rv.data == b"42"
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ def test_teardown_with_previous_exception(app):
|
|||
buffer.append(exception)
|
||||
|
||||
try:
|
||||
raise Exception('dummy')
|
||||
raise Exception("dummy")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
|
@ -61,35 +61,39 @@ def test_teardown_with_handled_exception(app):
|
|||
with app.test_request_context():
|
||||
assert buffer == []
|
||||
try:
|
||||
raise Exception('dummy')
|
||||
raise Exception("dummy")
|
||||
except Exception:
|
||||
pass
|
||||
assert buffer == [None]
|
||||
|
||||
|
||||
def test_proper_test_request_context(app):
|
||||
app.config.update(
|
||||
SERVER_NAME='localhost.localdomain:5000'
|
||||
)
|
||||
app.config.update(SERVER_NAME="localhost.localdomain:5000")
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return None
|
||||
|
||||
@app.route('/', subdomain='foo')
|
||||
@app.route("/", subdomain="foo")
|
||||
def sub():
|
||||
return None
|
||||
|
||||
with app.test_request_context('/'):
|
||||
assert flask.url_for('index', _external=True) == \
|
||||
'http://localhost.localdomain:5000/'
|
||||
with app.test_request_context("/"):
|
||||
assert (
|
||||
flask.url_for("index", _external=True)
|
||||
== "http://localhost.localdomain:5000/"
|
||||
)
|
||||
|
||||
with app.test_request_context('/'):
|
||||
assert flask.url_for('sub', _external=True) == \
|
||||
'http://foo.localhost.localdomain:5000/'
|
||||
with app.test_request_context("/"):
|
||||
assert (
|
||||
flask.url_for("sub", _external=True)
|
||||
== "http://foo.localhost.localdomain:5000/"
|
||||
)
|
||||
|
||||
try:
|
||||
with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):
|
||||
with app.test_request_context(
|
||||
"/", environ_overrides={"HTTP_HOST": "localhost"}
|
||||
):
|
||||
pass
|
||||
except ValueError as e:
|
||||
assert str(e) == (
|
||||
|
|
@ -98,28 +102,30 @@ def test_proper_test_request_context(app):
|
|||
"server name from the WSGI environment ('localhost')"
|
||||
)
|
||||
|
||||
app.config.update(SERVER_NAME='localhost')
|
||||
with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):
|
||||
app.config.update(SERVER_NAME="localhost")
|
||||
with app.test_request_context("/", environ_overrides={"SERVER_NAME": "localhost"}):
|
||||
pass
|
||||
|
||||
app.config.update(SERVER_NAME='localhost:80')
|
||||
with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):
|
||||
app.config.update(SERVER_NAME="localhost:80")
|
||||
with app.test_request_context(
|
||||
"/", environ_overrides={"SERVER_NAME": "localhost:80"}
|
||||
):
|
||||
pass
|
||||
|
||||
|
||||
def test_context_binding(app):
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return 'Hello %s!' % flask.request.args['name']
|
||||
return "Hello %s!" % flask.request.args["name"]
|
||||
|
||||
@app.route('/meh')
|
||||
@app.route("/meh")
|
||||
def meh():
|
||||
return flask.request.url
|
||||
|
||||
with app.test_request_context('/?name=World'):
|
||||
assert index() == 'Hello World!'
|
||||
with app.test_request_context('/meh'):
|
||||
assert meh() == 'http://localhost/meh'
|
||||
with app.test_request_context("/?name=World"):
|
||||
assert index() == "Hello World!"
|
||||
with app.test_request_context("/meh"):
|
||||
assert meh() == "http://localhost/meh"
|
||||
assert flask._request_ctx_stack.top is None
|
||||
|
||||
|
||||
|
|
@ -136,27 +142,26 @@ def test_context_test(app):
|
|||
|
||||
|
||||
def test_manual_context_binding(app):
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return 'Hello %s!' % flask.request.args['name']
|
||||
return "Hello %s!" % flask.request.args["name"]
|
||||
|
||||
ctx = app.test_request_context('/?name=World')
|
||||
ctx = app.test_request_context("/?name=World")
|
||||
ctx.push()
|
||||
assert index() == 'Hello World!'
|
||||
assert index() == "Hello World!"
|
||||
ctx.pop()
|
||||
with pytest.raises(RuntimeError):
|
||||
index()
|
||||
|
||||
|
||||
@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')
|
||||
@pytest.mark.skipif(greenlet is None, reason="greenlet not installed")
|
||||
class TestGreenletContextCopying(object):
|
||||
|
||||
def test_greenlet_context_copying(self, app, client):
|
||||
greenlets = []
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
flask.session['fizz'] = 'buzz'
|
||||
flask.session["fizz"] = "buzz"
|
||||
reqctx = flask._request_ctx_stack.top.copy()
|
||||
|
||||
def g():
|
||||
|
|
@ -165,17 +170,17 @@ class TestGreenletContextCopying(object):
|
|||
with reqctx:
|
||||
assert flask.request
|
||||
assert flask.current_app == app
|
||||
assert flask.request.path == '/'
|
||||
assert flask.request.args['foo'] == 'bar'
|
||||
assert flask.session.get('fizz') == 'buzz'
|
||||
assert flask.request.path == "/"
|
||||
assert flask.request.args["foo"] == "bar"
|
||||
assert flask.session.get("fizz") == "buzz"
|
||||
assert not flask.request
|
||||
return 42
|
||||
|
||||
greenlets.append(greenlet(g))
|
||||
return 'Hello World!'
|
||||
return "Hello World!"
|
||||
|
||||
rv = client.get('/?foo=bar')
|
||||
assert rv.data == b'Hello World!'
|
||||
rv = client.get("/?foo=bar")
|
||||
assert rv.data == b"Hello World!"
|
||||
|
||||
result = greenlets[0].run()
|
||||
assert result == 42
|
||||
|
|
@ -183,25 +188,25 @@ class TestGreenletContextCopying(object):
|
|||
def test_greenlet_context_copying_api(self, app, client):
|
||||
greenlets = []
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
flask.session['fizz'] = 'buzz'
|
||||
flask.session["fizz"] = "buzz"
|
||||
reqctx = flask._request_ctx_stack.top.copy()
|
||||
|
||||
@flask.copy_current_request_context
|
||||
def g():
|
||||
assert flask.request
|
||||
assert flask.current_app == app
|
||||
assert flask.request.path == '/'
|
||||
assert flask.request.args['foo'] == 'bar'
|
||||
assert flask.session.get('fizz') == 'buzz'
|
||||
assert flask.request.path == "/"
|
||||
assert flask.request.args["foo"] == "bar"
|
||||
assert flask.session.get("fizz") == "buzz"
|
||||
return 42
|
||||
|
||||
greenlets.append(greenlet(g))
|
||||
return 'Hello World!'
|
||||
return "Hello World!"
|
||||
|
||||
rv = client.get('/?foo=bar')
|
||||
assert rv.data == b'Hello World!'
|
||||
rv = client.get("/?foo=bar")
|
||||
assert rv.data == b"Hello World!"
|
||||
|
||||
result = greenlets[0].run()
|
||||
assert result == 42
|
||||
|
|
@ -220,12 +225,12 @@ def test_session_error_pops_context():
|
|||
|
||||
app = CustomFlask(__name__)
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
# shouldn't get here
|
||||
assert False
|
||||
|
||||
response = app.test_client().get('/')
|
||||
response = app.test_client().get("/")
|
||||
assert response.status_code == 500
|
||||
assert not flask.request
|
||||
assert not flask.current_app
|
||||
|
|
@ -239,11 +244,12 @@ def test_bad_environ_raises_bad_request():
|
|||
# However it works when actually passed to the server.
|
||||
|
||||
from flask.testing import make_test_environ_builder
|
||||
|
||||
builder = make_test_environ_builder(app)
|
||||
environ = builder.get_environ()
|
||||
|
||||
# use a non-printable character in the Host - this is key to this test
|
||||
environ['HTTP_HOST'] = u'\x8a'
|
||||
environ["HTTP_HOST"] = u"\x8a"
|
||||
|
||||
with app.request_context(environ):
|
||||
response = app.full_dispatch_request()
|
||||
|
|
@ -253,20 +259,21 @@ def test_bad_environ_raises_bad_request():
|
|||
def test_environ_for_valid_idna_completes():
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return 'Hello World!'
|
||||
return "Hello World!"
|
||||
|
||||
# We cannot use app.test_client() for the Unicode-rich Host header,
|
||||
# because werkzeug enforces latin1 on Python 2.
|
||||
# However it works when actually passed to the server.
|
||||
|
||||
from flask.testing import make_test_environ_builder
|
||||
|
||||
builder = make_test_environ_builder(app)
|
||||
environ = builder.get_environ()
|
||||
|
||||
# these characters are all IDNA-compatible
|
||||
environ['HTTP_HOST'] = u'ąśźäüжŠßя.com'
|
||||
environ["HTTP_HOST"] = u"ąśźäüжŠßя.com"
|
||||
|
||||
with app.request_context(environ):
|
||||
response = app.full_dispatch_request()
|
||||
|
|
@ -277,9 +284,9 @@ def test_environ_for_valid_idna_completes():
|
|||
def test_normal_environ_completes():
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return 'Hello World!'
|
||||
return "Hello World!"
|
||||
|
||||
response = app.test_client().get('/', headers={'host': 'xn--on-0ia.com'})
|
||||
response = app.test_client().get("/", headers={"host": "xn--on-0ia.com"})
|
||||
assert response.status_code == 200
|
||||
|
|
|
|||
|
|
@ -19,15 +19,14 @@ except ImportError:
|
|||
import flask
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
blinker is None,
|
||||
reason='Signals require the blinker library.'
|
||||
blinker is None, reason="Signals require the blinker library."
|
||||
)
|
||||
|
||||
|
||||
def test_template_rendered(app, client):
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template('simple_template.html', whiskey=42)
|
||||
return flask.render_template("simple_template.html", whiskey=42)
|
||||
|
||||
recorded = []
|
||||
|
||||
|
|
@ -36,11 +35,11 @@ def test_template_rendered(app, client):
|
|||
|
||||
flask.template_rendered.connect(record, app)
|
||||
try:
|
||||
client.get('/')
|
||||
client.get("/")
|
||||
assert len(recorded) == 1
|
||||
template, context = recorded[0]
|
||||
assert template.name == 'simple_template.html'
|
||||
assert context['whiskey'] == 42
|
||||
assert template.name == "simple_template.html"
|
||||
assert context["whiskey"] == 42
|
||||
finally:
|
||||
flask.template_rendered.disconnect(record, app)
|
||||
|
||||
|
|
@ -48,24 +47,24 @@ def test_template_rendered(app, client):
|
|||
def test_before_render_template():
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template('simple_template.html', whiskey=42)
|
||||
return flask.render_template("simple_template.html", whiskey=42)
|
||||
|
||||
recorded = []
|
||||
|
||||
def record(sender, template, context):
|
||||
context['whiskey'] = 43
|
||||
context["whiskey"] = 43
|
||||
recorded.append((template, context))
|
||||
|
||||
flask.before_render_template.connect(record, app)
|
||||
try:
|
||||
rv = app.test_client().get('/')
|
||||
rv = app.test_client().get("/")
|
||||
assert len(recorded) == 1
|
||||
template, context = recorded[0]
|
||||
assert template.name == 'simple_template.html'
|
||||
assert context['whiskey'] == 43
|
||||
assert rv.data == b'<h1>43</h1>'
|
||||
assert template.name == "simple_template.html"
|
||||
assert context["whiskey"] == 43
|
||||
assert rv.data == b"<h1>43</h1>"
|
||||
finally:
|
||||
flask.before_render_template.disconnect(record, app)
|
||||
|
||||
|
|
@ -75,36 +74,41 @@ def test_request_signals():
|
|||
calls = []
|
||||
|
||||
def before_request_signal(sender):
|
||||
calls.append('before-signal')
|
||||
calls.append("before-signal")
|
||||
|
||||
def after_request_signal(sender, response):
|
||||
assert response.data == b'stuff'
|
||||
calls.append('after-signal')
|
||||
assert response.data == b"stuff"
|
||||
calls.append("after-signal")
|
||||
|
||||
@app.before_request
|
||||
def before_request_handler():
|
||||
calls.append('before-handler')
|
||||
calls.append("before-handler")
|
||||
|
||||
@app.after_request
|
||||
def after_request_handler(response):
|
||||
calls.append('after-handler')
|
||||
response.data = 'stuff'
|
||||
calls.append("after-handler")
|
||||
response.data = "stuff"
|
||||
return response
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
calls.append('handler')
|
||||
return 'ignored anyway'
|
||||
calls.append("handler")
|
||||
return "ignored anyway"
|
||||
|
||||
flask.request_started.connect(before_request_signal, app)
|
||||
flask.request_finished.connect(after_request_signal, app)
|
||||
|
||||
try:
|
||||
rv = app.test_client().get('/')
|
||||
assert rv.data == b'stuff'
|
||||
rv = app.test_client().get("/")
|
||||
assert rv.data == b"stuff"
|
||||
|
||||
assert calls == ['before-signal', 'before-handler', 'handler',
|
||||
'after-handler', 'after-signal']
|
||||
assert calls == [
|
||||
"before-signal",
|
||||
"before-handler",
|
||||
"handler",
|
||||
"after-handler",
|
||||
"after-signal",
|
||||
]
|
||||
finally:
|
||||
flask.request_started.disconnect(before_request_signal, app)
|
||||
flask.request_finished.disconnect(after_request_signal, app)
|
||||
|
|
@ -114,7 +118,7 @@ def test_request_exception_signal():
|
|||
app = flask.Flask(__name__)
|
||||
recorded = []
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
1 // 0
|
||||
|
||||
|
|
@ -123,7 +127,7 @@ def test_request_exception_signal():
|
|||
|
||||
flask.got_request_exception.connect(record, app)
|
||||
try:
|
||||
assert app.test_client().get('/').status_code == 500
|
||||
assert app.test_client().get("/").status_code == 500
|
||||
assert len(recorded) == 1
|
||||
assert isinstance(recorded[0], ZeroDivisionError)
|
||||
finally:
|
||||
|
|
@ -135,33 +139,33 @@ def test_appcontext_signals():
|
|||
recorded = []
|
||||
|
||||
def record_push(sender, **kwargs):
|
||||
recorded.append('push')
|
||||
recorded.append("push")
|
||||
|
||||
def record_pop(sender, **kwargs):
|
||||
recorded.append('pop')
|
||||
recorded.append("pop")
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return 'Hello'
|
||||
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('/')
|
||||
assert rv.data == b'Hello'
|
||||
assert recorded == ['push']
|
||||
assert recorded == ['push', 'pop']
|
||||
rv = c.get("/")
|
||||
assert rv.data == b"Hello"
|
||||
assert recorded == ["push"]
|
||||
assert recorded == ["push", "pop"]
|
||||
finally:
|
||||
flask.appcontext_pushed.disconnect(record_push, app)
|
||||
flask.appcontext_popped.disconnect(record_pop, app)
|
||||
|
||||
|
||||
def test_flash_signal(app):
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
flask.flash('This is a flash message', category='notice')
|
||||
return flask.redirect('/other')
|
||||
flask.flash("This is a flash message", category="notice")
|
||||
return flask.redirect("/other")
|
||||
|
||||
recorded = []
|
||||
|
||||
|
|
@ -172,11 +176,11 @@ def test_flash_signal(app):
|
|||
try:
|
||||
client = app.test_client()
|
||||
with client.session_transaction():
|
||||
client.get('/')
|
||||
client.get("/")
|
||||
assert len(recorded) == 1
|
||||
message, category = recorded[0]
|
||||
assert message == 'This is a flash message'
|
||||
assert category == 'notice'
|
||||
assert message == "This is a flash message"
|
||||
assert category == "notice"
|
||||
finally:
|
||||
flask.message_flashed.disconnect(record, app)
|
||||
|
||||
|
|
@ -186,18 +190,18 @@ def test_appcontext_tearing_down_signal():
|
|||
recorded = []
|
||||
|
||||
def record_teardown(sender, **kwargs):
|
||||
recorded.append(('tear_down', kwargs))
|
||||
recorded.append(("tear_down", kwargs))
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
1 // 0
|
||||
|
||||
flask.appcontext_tearing_down.connect(record_teardown, app)
|
||||
try:
|
||||
with app.test_client() as c:
|
||||
rv = c.get('/')
|
||||
rv = c.get("/")
|
||||
assert rv.status_code == 500
|
||||
assert recorded == []
|
||||
assert recorded == [('tear_down', {'exc': None})]
|
||||
assert recorded == [("tear_down", {"exc": None})]
|
||||
finally:
|
||||
flask.appcontext_tearing_down.disconnect(record_teardown, app)
|
||||
|
|
|
|||
|
|
@ -23,11 +23,11 @@ def test_suppressed_exception_logging():
|
|||
out = StringIO()
|
||||
app = SuppressedFlask(__name__)
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
raise Exception('test')
|
||||
raise Exception("test")
|
||||
|
||||
rv = app.test_client().get('/', errors_stream=out)
|
||||
rv = app.test_client().get("/", errors_stream=out)
|
||||
assert rv.status_code == 500
|
||||
assert b'Internal Server Error' in rv.data
|
||||
assert b"Internal Server Error" in rv.data
|
||||
assert not out.getvalue()
|
||||
|
|
|
|||
|
|
@ -20,102 +20,104 @@ import werkzeug.serving
|
|||
def test_context_processing(app, client):
|
||||
@app.context_processor
|
||||
def context_processor():
|
||||
return {'injected_value': 42}
|
||||
return {"injected_value": 42}
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template('context_template.html', value=23)
|
||||
return flask.render_template("context_template.html", value=23)
|
||||
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'<p>23|42'
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"<p>23|42"
|
||||
|
||||
|
||||
def test_original_win(app, client):
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template_string('{{ config }}', config=42)
|
||||
return flask.render_template_string("{{ config }}", config=42)
|
||||
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'42'
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"42"
|
||||
|
||||
|
||||
def test_request_less_rendering(app, app_ctx):
|
||||
app.config['WORLD_NAME'] = 'Special World'
|
||||
app.config["WORLD_NAME"] = "Special World"
|
||||
|
||||
@app.context_processor
|
||||
def context_processor():
|
||||
return dict(foo=42)
|
||||
|
||||
rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '
|
||||
'{{ foo }}')
|
||||
assert rv == 'Hello Special World 42'
|
||||
rv = flask.render_template_string("Hello {{ config.WORLD_NAME }} " "{{ foo }}")
|
||||
assert rv == "Hello Special World 42"
|
||||
|
||||
|
||||
def test_standard_context(app, client):
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
flask.g.foo = 23
|
||||
flask.session['test'] = 'aha'
|
||||
return flask.render_template_string('''
|
||||
flask.session["test"] = "aha"
|
||||
return flask.render_template_string(
|
||||
"""
|
||||
{{ request.args.foo }}
|
||||
{{ g.foo }}
|
||||
{{ config.DEBUG }}
|
||||
{{ session.test }}
|
||||
''')
|
||||
"""
|
||||
)
|
||||
|
||||
rv = client.get('/?foo=42')
|
||||
assert rv.data.split() == [b'42', b'23', b'False', b'aha']
|
||||
rv = client.get("/?foo=42")
|
||||
assert rv.data.split() == [b"42", b"23", b"False", b"aha"]
|
||||
|
||||
|
||||
def test_escaping(app, client):
|
||||
text = '<p>Hello World!'
|
||||
text = "<p>Hello World!"
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template('escaping_template.html', text=text,
|
||||
html=flask.Markup(text))
|
||||
return flask.render_template(
|
||||
"escaping_template.html", text=text, html=flask.Markup(text)
|
||||
)
|
||||
|
||||
lines = client.get('/').data.splitlines()
|
||||
lines = client.get("/").data.splitlines()
|
||||
assert 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!'
|
||||
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_no_escaping(app, client):
|
||||
text = '<p>Hello World!'
|
||||
text = "<p>Hello World!"
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template('non_escaping_template.txt', text=text,
|
||||
html=flask.Markup(text))
|
||||
return flask.render_template(
|
||||
"non_escaping_template.txt", text=text, html=flask.Markup(text)
|
||||
)
|
||||
|
||||
lines = client.get('/').data.splitlines()
|
||||
lines = client.get("/").data.splitlines()
|
||||
assert 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!',
|
||||
b'<p>Hello World!',
|
||||
b'<p>Hello World!'
|
||||
b"<p>Hello World!",
|
||||
b"<p>Hello World!",
|
||||
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_escaping_without_template_filename(app, client, req_ctx):
|
||||
assert flask.render_template_string(
|
||||
'{{ foo }}', foo='<test>') == '<test>'
|
||||
assert flask.render_template('mail.txt', foo='<test>') == '<test> Mail'
|
||||
assert flask.render_template_string("{{ foo }}", foo="<test>") == "<test>"
|
||||
assert flask.render_template("mail.txt", foo="<test>") == "<test> Mail"
|
||||
|
||||
|
||||
def test_macros(app, req_ctx):
|
||||
macro = flask.get_template_attribute('_macro.html', 'hello')
|
||||
assert macro('World') == 'Hello World!'
|
||||
macro = flask.get_template_attribute("_macro.html", "hello")
|
||||
assert macro("World") == "Hello World!"
|
||||
|
||||
|
||||
def test_template_filter(app):
|
||||
|
|
@ -123,9 +125,9 @@ def test_template_filter(app):
|
|||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
|
||||
assert 'my_reverse' in app.jinja_env.filters.keys()
|
||||
assert app.jinja_env.filters['my_reverse'] == my_reverse
|
||||
assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'
|
||||
assert "my_reverse" in app.jinja_env.filters.keys()
|
||||
assert app.jinja_env.filters["my_reverse"] == my_reverse
|
||||
assert app.jinja_env.filters["my_reverse"]("abcd") == "dcba"
|
||||
|
||||
|
||||
def test_add_template_filter(app):
|
||||
|
|
@ -133,29 +135,29 @@ def test_add_template_filter(app):
|
|||
return s[::-1]
|
||||
|
||||
app.add_template_filter(my_reverse)
|
||||
assert 'my_reverse' in app.jinja_env.filters.keys()
|
||||
assert app.jinja_env.filters['my_reverse'] == my_reverse
|
||||
assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'
|
||||
assert "my_reverse" in app.jinja_env.filters.keys()
|
||||
assert app.jinja_env.filters["my_reverse"] == my_reverse
|
||||
assert app.jinja_env.filters["my_reverse"]("abcd") == "dcba"
|
||||
|
||||
|
||||
def test_template_filter_with_name(app):
|
||||
@app.template_filter('strrev')
|
||||
@app.template_filter("strrev")
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
|
||||
assert 'strrev' in app.jinja_env.filters.keys()
|
||||
assert app.jinja_env.filters['strrev'] == my_reverse
|
||||
assert app.jinja_env.filters['strrev']('abcd') == 'dcba'
|
||||
assert "strrev" in app.jinja_env.filters.keys()
|
||||
assert app.jinja_env.filters["strrev"] == my_reverse
|
||||
assert app.jinja_env.filters["strrev"]("abcd") == "dcba"
|
||||
|
||||
|
||||
def test_add_template_filter_with_name(app):
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
|
||||
app.add_template_filter(my_reverse, 'strrev')
|
||||
assert 'strrev' in app.jinja_env.filters.keys()
|
||||
assert app.jinja_env.filters['strrev'] == my_reverse
|
||||
assert app.jinja_env.filters['strrev']('abcd') == 'dcba'
|
||||
app.add_template_filter(my_reverse, "strrev")
|
||||
assert "strrev" in app.jinja_env.filters.keys()
|
||||
assert app.jinja_env.filters["strrev"] == my_reverse
|
||||
assert app.jinja_env.filters["strrev"]("abcd") == "dcba"
|
||||
|
||||
|
||||
def test_template_filter_with_template(app, client):
|
||||
|
|
@ -163,12 +165,12 @@ def test_template_filter_with_template(app, client):
|
|||
def super_reverse(s):
|
||||
return s[::-1]
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template('template_filter.html', value='abcd')
|
||||
return flask.render_template("template_filter.html", value="abcd")
|
||||
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'dcba'
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"dcba"
|
||||
|
||||
|
||||
def test_add_template_filter_with_template(app, client):
|
||||
|
|
@ -177,39 +179,39 @@ def test_add_template_filter_with_template(app, client):
|
|||
|
||||
app.add_template_filter(super_reverse)
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template('template_filter.html', value='abcd')
|
||||
return flask.render_template("template_filter.html", value="abcd")
|
||||
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'dcba'
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"dcba"
|
||||
|
||||
|
||||
def test_template_filter_with_name_and_template(app, client):
|
||||
@app.template_filter('super_reverse')
|
||||
@app.template_filter("super_reverse")
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template('template_filter.html', value='abcd')
|
||||
return flask.render_template("template_filter.html", value="abcd")
|
||||
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'dcba'
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"dcba"
|
||||
|
||||
|
||||
def test_add_template_filter_with_name_and_template(app, client):
|
||||
def my_reverse(s):
|
||||
return s[::-1]
|
||||
|
||||
app.add_template_filter(my_reverse, 'super_reverse')
|
||||
app.add_template_filter(my_reverse, "super_reverse")
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template('template_filter.html', value='abcd')
|
||||
return flask.render_template("template_filter.html", value="abcd")
|
||||
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'dcba'
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"dcba"
|
||||
|
||||
|
||||
def test_template_test(app):
|
||||
|
|
@ -217,9 +219,9 @@ def test_template_test(app):
|
|||
def boolean(value):
|
||||
return isinstance(value, bool)
|
||||
|
||||
assert 'boolean' in app.jinja_env.tests.keys()
|
||||
assert app.jinja_env.tests['boolean'] == boolean
|
||||
assert app.jinja_env.tests['boolean'](False)
|
||||
assert "boolean" in app.jinja_env.tests.keys()
|
||||
assert app.jinja_env.tests["boolean"] == boolean
|
||||
assert app.jinja_env.tests["boolean"](False)
|
||||
|
||||
|
||||
def test_add_template_test(app):
|
||||
|
|
@ -227,29 +229,29 @@ def test_add_template_test(app):
|
|||
return isinstance(value, bool)
|
||||
|
||||
app.add_template_test(boolean)
|
||||
assert 'boolean' in app.jinja_env.tests.keys()
|
||||
assert app.jinja_env.tests['boolean'] == boolean
|
||||
assert app.jinja_env.tests['boolean'](False)
|
||||
assert "boolean" in app.jinja_env.tests.keys()
|
||||
assert app.jinja_env.tests["boolean"] == boolean
|
||||
assert app.jinja_env.tests["boolean"](False)
|
||||
|
||||
|
||||
def test_template_test_with_name(app):
|
||||
@app.template_test('boolean')
|
||||
@app.template_test("boolean")
|
||||
def is_boolean(value):
|
||||
return isinstance(value, bool)
|
||||
|
||||
assert 'boolean' in app.jinja_env.tests.keys()
|
||||
assert app.jinja_env.tests['boolean'] == is_boolean
|
||||
assert app.jinja_env.tests['boolean'](False)
|
||||
assert "boolean" in app.jinja_env.tests.keys()
|
||||
assert app.jinja_env.tests["boolean"] == is_boolean
|
||||
assert app.jinja_env.tests["boolean"](False)
|
||||
|
||||
|
||||
def test_add_template_test_with_name(app):
|
||||
def is_boolean(value):
|
||||
return isinstance(value, bool)
|
||||
|
||||
app.add_template_test(is_boolean, 'boolean')
|
||||
assert 'boolean' in app.jinja_env.tests.keys()
|
||||
assert app.jinja_env.tests['boolean'] == is_boolean
|
||||
assert app.jinja_env.tests['boolean'](False)
|
||||
app.add_template_test(is_boolean, "boolean")
|
||||
assert "boolean" in app.jinja_env.tests.keys()
|
||||
assert app.jinja_env.tests["boolean"] == is_boolean
|
||||
assert app.jinja_env.tests["boolean"](False)
|
||||
|
||||
|
||||
def test_template_test_with_template(app, client):
|
||||
|
|
@ -257,12 +259,12 @@ def test_template_test_with_template(app, client):
|
|||
def boolean(value):
|
||||
return isinstance(value, bool)
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template('template_test.html', value=False)
|
||||
return flask.render_template("template_test.html", value=False)
|
||||
|
||||
rv = client.get('/')
|
||||
assert b'Success!' in rv.data
|
||||
rv = client.get("/")
|
||||
assert b"Success!" in rv.data
|
||||
|
||||
|
||||
def test_add_template_test_with_template(app, client):
|
||||
|
|
@ -271,39 +273,39 @@ def test_add_template_test_with_template(app, client):
|
|||
|
||||
app.add_template_test(boolean)
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template('template_test.html', value=False)
|
||||
return flask.render_template("template_test.html", value=False)
|
||||
|
||||
rv = client.get('/')
|
||||
assert b'Success!' in rv.data
|
||||
rv = client.get("/")
|
||||
assert b"Success!" in rv.data
|
||||
|
||||
|
||||
def test_template_test_with_name_and_template(app, client):
|
||||
@app.template_test('boolean')
|
||||
@app.template_test("boolean")
|
||||
def is_boolean(value):
|
||||
return isinstance(value, bool)
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template('template_test.html', value=False)
|
||||
return flask.render_template("template_test.html", value=False)
|
||||
|
||||
rv = client.get('/')
|
||||
assert b'Success!' in rv.data
|
||||
rv = client.get("/")
|
||||
assert b"Success!" in rv.data
|
||||
|
||||
|
||||
def test_add_template_test_with_name_and_template(app, client):
|
||||
def is_boolean(value):
|
||||
return isinstance(value, bool)
|
||||
|
||||
app.add_template_test(is_boolean, 'boolean')
|
||||
app.add_template_test(is_boolean, "boolean")
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template('template_test.html', value=False)
|
||||
return flask.render_template("template_test.html", value=False)
|
||||
|
||||
rv = client.get('/')
|
||||
assert b'Success!' in rv.data
|
||||
rv = client.get("/")
|
||||
assert b"Success!" in rv.data
|
||||
|
||||
|
||||
def test_add_template_global(app, app_ctx):
|
||||
|
|
@ -311,84 +313,89 @@ def test_add_template_global(app, app_ctx):
|
|||
def get_stuff():
|
||||
return 42
|
||||
|
||||
assert 'get_stuff' in app.jinja_env.globals.keys()
|
||||
assert app.jinja_env.globals['get_stuff'] == get_stuff
|
||||
assert app.jinja_env.globals['get_stuff'](), 42
|
||||
assert "get_stuff" in app.jinja_env.globals.keys()
|
||||
assert app.jinja_env.globals["get_stuff"] == get_stuff
|
||||
assert app.jinja_env.globals["get_stuff"](), 42
|
||||
|
||||
rv = flask.render_template_string('{{ get_stuff() }}')
|
||||
assert rv == '42'
|
||||
rv = flask.render_template_string("{{ get_stuff() }}")
|
||||
assert rv == "42"
|
||||
|
||||
|
||||
def test_custom_template_loader(client):
|
||||
class MyFlask(flask.Flask):
|
||||
def create_global_jinja_loader(self):
|
||||
from jinja2 import DictLoader
|
||||
return DictLoader({'index.html': 'Hello Custom World!'})
|
||||
|
||||
return DictLoader({"index.html": "Hello Custom World!"})
|
||||
|
||||
app = MyFlask(__name__)
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template('index.html')
|
||||
return flask.render_template("index.html")
|
||||
|
||||
c = app.test_client()
|
||||
rv = c.get('/')
|
||||
assert rv.data == b'Hello Custom World!'
|
||||
rv = c.get("/")
|
||||
assert rv.data == b"Hello Custom World!"
|
||||
|
||||
|
||||
def test_iterable_loader(app, client):
|
||||
@app.context_processor
|
||||
def context_processor():
|
||||
return {'whiskey': 'Jameson'}
|
||||
return {"whiskey": "Jameson"}
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.render_template(
|
||||
['no_template.xml', # should skip this one
|
||||
'simple_template.html', # should render this
|
||||
'context_template.html'],
|
||||
value=23)
|
||||
[
|
||||
"no_template.xml", # should skip this one
|
||||
"simple_template.html", # should render this
|
||||
"context_template.html",
|
||||
],
|
||||
value=23,
|
||||
)
|
||||
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'<h1>Jameson</h1>'
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"<h1>Jameson</h1>"
|
||||
|
||||
|
||||
def test_templates_auto_reload(app):
|
||||
# debug is False, config option is None
|
||||
assert app.debug is False
|
||||
assert app.config['TEMPLATES_AUTO_RELOAD'] is None
|
||||
assert app.config["TEMPLATES_AUTO_RELOAD"] is None
|
||||
assert app.jinja_env.auto_reload is False
|
||||
# debug is False, config option is False
|
||||
app = flask.Flask(__name__)
|
||||
app.config['TEMPLATES_AUTO_RELOAD'] = False
|
||||
app.config["TEMPLATES_AUTO_RELOAD"] = False
|
||||
assert app.debug is False
|
||||
assert app.jinja_env.auto_reload is False
|
||||
# debug is False, config option is True
|
||||
app = flask.Flask(__name__)
|
||||
app.config['TEMPLATES_AUTO_RELOAD'] = True
|
||||
app.config["TEMPLATES_AUTO_RELOAD"] = True
|
||||
assert app.debug is False
|
||||
assert app.jinja_env.auto_reload is True
|
||||
# debug is True, config option is None
|
||||
app = flask.Flask(__name__)
|
||||
app.config['DEBUG'] = True
|
||||
assert app.config['TEMPLATES_AUTO_RELOAD'] is None
|
||||
app.config["DEBUG"] = True
|
||||
assert app.config["TEMPLATES_AUTO_RELOAD"] is None
|
||||
assert app.jinja_env.auto_reload is True
|
||||
# debug is True, config option is False
|
||||
app = flask.Flask(__name__)
|
||||
app.config['DEBUG'] = True
|
||||
app.config['TEMPLATES_AUTO_RELOAD'] = False
|
||||
app.config["DEBUG"] = True
|
||||
app.config["TEMPLATES_AUTO_RELOAD"] = False
|
||||
assert app.jinja_env.auto_reload is False
|
||||
# debug is True, config option is True
|
||||
app = flask.Flask(__name__)
|
||||
app.config['DEBUG'] = True
|
||||
app.config['TEMPLATES_AUTO_RELOAD'] = True
|
||||
app.config["DEBUG"] = True
|
||||
app.config["TEMPLATES_AUTO_RELOAD"] = True
|
||||
assert app.jinja_env.auto_reload is True
|
||||
|
||||
|
||||
def test_templates_auto_reload_debug_run(app, monkeypatch):
|
||||
def run_simple_mock(*args, **kwargs):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)
|
||||
monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)
|
||||
|
||||
app.run()
|
||||
assert app.templates_auto_reload == False
|
||||
|
|
@ -409,25 +416,26 @@ def test_template_loader_debugging(test_apps, monkeypatch):
|
|||
called.append(True)
|
||||
text = str(record.msg)
|
||||
assert '1: trying loader of application "blueprintapp"' in text
|
||||
assert ('2: trying loader of blueprint "admin" '
|
||||
'(blueprintapp.apps.admin)') in text
|
||||
assert ('trying loader of blueprint "frontend" '
|
||||
'(blueprintapp.apps.frontend)') in text
|
||||
assert 'Error: the template could not be found' in text
|
||||
assert ('looked up from an endpoint that belongs to '
|
||||
'the blueprint "frontend"') in text
|
||||
assert 'See http://flask.pocoo.org/docs/blueprints/#templates' in text
|
||||
assert (
|
||||
'2: trying loader of blueprint "admin" ' "(blueprintapp.apps.admin)"
|
||||
) in text
|
||||
assert (
|
||||
'trying loader of blueprint "frontend" ' "(blueprintapp.apps.frontend)"
|
||||
) in text
|
||||
assert "Error: the template could not be found" in text
|
||||
assert (
|
||||
"looked up from an endpoint that belongs to " 'the blueprint "frontend"'
|
||||
) in text
|
||||
assert "See http://flask.pocoo.org/docs/blueprints/#templates" in text
|
||||
|
||||
with app.test_client() as c:
|
||||
monkeypatch.setitem(app.config, 'EXPLAIN_TEMPLATE_LOADING', True)
|
||||
monkeypatch.setattr(
|
||||
logging.getLogger('flask'), 'handlers', [_TestHandler()]
|
||||
)
|
||||
monkeypatch.setitem(app.config, "EXPLAIN_TEMPLATE_LOADING", True)
|
||||
monkeypatch.setattr(logging.getLogger("flask"), "handlers", [_TestHandler()])
|
||||
|
||||
with pytest.raises(TemplateNotFound) as excinfo:
|
||||
c.get('/missing')
|
||||
c.get("/missing")
|
||||
|
||||
assert 'missing_template.html' in str(excinfo.value)
|
||||
assert "missing_template.html" in str(excinfo.value)
|
||||
|
||||
assert len(called) == 1
|
||||
|
||||
|
|
|
|||
|
|
@ -21,166 +21,166 @@ from flask.testing import make_test_environ_builder, FlaskCliRunner
|
|||
|
||||
|
||||
def test_environ_defaults_from_config(app, client):
|
||||
app.config['SERVER_NAME'] = 'example.com:1234'
|
||||
app.config['APPLICATION_ROOT'] = '/foo'
|
||||
app.config["SERVER_NAME"] = "example.com:1234"
|
||||
app.config["APPLICATION_ROOT"] = "/foo"
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.request.url
|
||||
|
||||
ctx = app.test_request_context()
|
||||
assert ctx.request.url == 'http://example.com:1234/foo/'
|
||||
assert ctx.request.url == "http://example.com:1234/foo/"
|
||||
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'http://example.com:1234/foo/'
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"http://example.com:1234/foo/"
|
||||
|
||||
|
||||
def test_environ_defaults(app, client, app_ctx, req_ctx):
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.request.url
|
||||
|
||||
ctx = app.test_request_context()
|
||||
assert ctx.request.url == 'http://localhost/'
|
||||
assert ctx.request.url == "http://localhost/"
|
||||
with client:
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'http://localhost/'
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"http://localhost/"
|
||||
|
||||
|
||||
def test_environ_base_default(app, client, app_ctx):
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
flask.g.user_agent = flask.request.headers["User-Agent"]
|
||||
return flask.request.remote_addr
|
||||
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'127.0.0.1'
|
||||
assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"127.0.0.1"
|
||||
assert flask.g.user_agent == "werkzeug/" + werkzeug.__version__
|
||||
|
||||
|
||||
def test_environ_base_modified(app, client, app_ctx):
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
flask.g.user_agent = flask.request.headers["User-Agent"]
|
||||
return flask.request.remote_addr
|
||||
|
||||
client.environ_base['REMOTE_ADDR'] = '0.0.0.0'
|
||||
client.environ_base['HTTP_USER_AGENT'] = 'Foo'
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'0.0.0.0'
|
||||
assert flask.g.user_agent == 'Foo'
|
||||
client.environ_base["REMOTE_ADDR"] = "0.0.0.0"
|
||||
client.environ_base["HTTP_USER_AGENT"] = "Foo"
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"0.0.0.0"
|
||||
assert flask.g.user_agent == "Foo"
|
||||
|
||||
client.environ_base['REMOTE_ADDR'] = '0.0.0.1'
|
||||
client.environ_base['HTTP_USER_AGENT'] = 'Bar'
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'0.0.0.1'
|
||||
assert flask.g.user_agent == 'Bar'
|
||||
client.environ_base["REMOTE_ADDR"] = "0.0.0.1"
|
||||
client.environ_base["HTTP_USER_AGENT"] = "Bar"
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"0.0.0.1"
|
||||
assert flask.g.user_agent == "Bar"
|
||||
|
||||
|
||||
def test_client_open_environ(app, client, request):
|
||||
@app.route('/index')
|
||||
@app.route("/index")
|
||||
def index():
|
||||
return flask.request.remote_addr
|
||||
|
||||
builder = make_test_environ_builder(app, path='/index', method='GET')
|
||||
builder = make_test_environ_builder(app, path="/index", method="GET")
|
||||
request.addfinalizer(builder.close)
|
||||
|
||||
rv = client.open(builder)
|
||||
assert rv.data == b'127.0.0.1'
|
||||
assert rv.data == b"127.0.0.1"
|
||||
|
||||
environ = builder.get_environ()
|
||||
client.environ_base['REMOTE_ADDR'] = '127.0.0.2'
|
||||
client.environ_base["REMOTE_ADDR"] = "127.0.0.2"
|
||||
rv = client.open(environ)
|
||||
assert rv.data == b'127.0.0.2'
|
||||
assert rv.data == b"127.0.0.2"
|
||||
|
||||
|
||||
def test_specify_url_scheme(app, client):
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return flask.request.url
|
||||
|
||||
ctx = app.test_request_context(url_scheme='https')
|
||||
assert ctx.request.url == 'https://localhost/'
|
||||
ctx = app.test_request_context(url_scheme="https")
|
||||
assert ctx.request.url == "https://localhost/"
|
||||
|
||||
rv = client.get('/', url_scheme='https')
|
||||
assert rv.data == b'https://localhost/'
|
||||
rv = client.get("/", url_scheme="https")
|
||||
assert rv.data == b"https://localhost/"
|
||||
|
||||
|
||||
def test_path_is_url(app):
|
||||
eb = make_test_environ_builder(app, 'https://example.com/')
|
||||
assert eb.url_scheme == 'https'
|
||||
assert eb.host == 'example.com'
|
||||
assert eb.script_root == ''
|
||||
assert eb.path == '/'
|
||||
eb = make_test_environ_builder(app, "https://example.com/")
|
||||
assert eb.url_scheme == "https"
|
||||
assert eb.host == "example.com"
|
||||
assert eb.script_root == ""
|
||||
assert eb.path == "/"
|
||||
|
||||
|
||||
def test_blueprint_with_subdomain():
|
||||
app = flask.Flask(__name__, subdomain_matching=True)
|
||||
app.config['SERVER_NAME'] = 'example.com:1234'
|
||||
app.config['APPLICATION_ROOT'] = '/foo'
|
||||
app.config["SERVER_NAME"] = "example.com:1234"
|
||||
app.config["APPLICATION_ROOT"] = "/foo"
|
||||
client = app.test_client()
|
||||
|
||||
bp = flask.Blueprint('company', __name__, subdomain='xxx')
|
||||
bp = flask.Blueprint("company", __name__, subdomain="xxx")
|
||||
|
||||
@bp.route('/')
|
||||
@bp.route("/")
|
||||
def index():
|
||||
return flask.request.url
|
||||
|
||||
app.register_blueprint(bp)
|
||||
|
||||
ctx = app.test_request_context('/', subdomain='xxx')
|
||||
assert ctx.request.url == 'http://xxx.example.com:1234/foo/'
|
||||
ctx = app.test_request_context("/", subdomain="xxx")
|
||||
assert ctx.request.url == "http://xxx.example.com:1234/foo/"
|
||||
assert ctx.request.blueprint == bp.name
|
||||
|
||||
rv = client.get('/', subdomain='xxx')
|
||||
assert rv.data == b'http://xxx.example.com:1234/foo/'
|
||||
rv = client.get("/", subdomain="xxx")
|
||||
assert rv.data == b"http://xxx.example.com:1234/foo/"
|
||||
|
||||
|
||||
def test_redirect_keep_session(app, client, app_ctx):
|
||||
@app.route('/', methods=['GET', 'POST'])
|
||||
@app.route("/", methods=["GET", "POST"])
|
||||
def index():
|
||||
if flask.request.method == 'POST':
|
||||
return flask.redirect('/getsession')
|
||||
flask.session['data'] = 'foo'
|
||||
return 'index'
|
||||
if flask.request.method == "POST":
|
||||
return flask.redirect("/getsession")
|
||||
flask.session["data"] = "foo"
|
||||
return "index"
|
||||
|
||||
@app.route('/getsession')
|
||||
@app.route("/getsession")
|
||||
def get_session():
|
||||
return flask.session.get('data', '<missing>')
|
||||
return flask.session.get("data", "<missing>")
|
||||
|
||||
with client:
|
||||
rv = client.get('/getsession')
|
||||
assert rv.data == b'<missing>'
|
||||
rv = client.get("/getsession")
|
||||
assert rv.data == b"<missing>"
|
||||
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'index'
|
||||
assert flask.session.get('data') == 'foo'
|
||||
rv = client.post('/', data={}, follow_redirects=True)
|
||||
assert rv.data == b'foo'
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"index"
|
||||
assert flask.session.get("data") == "foo"
|
||||
rv = client.post("/", data={}, follow_redirects=True)
|
||||
assert rv.data == b"foo"
|
||||
|
||||
# This support requires a new Werkzeug version
|
||||
if not hasattr(client, 'redirect_client'):
|
||||
assert flask.session.get('data') == 'foo'
|
||||
if not hasattr(client, "redirect_client"):
|
||||
assert flask.session.get("data") == "foo"
|
||||
|
||||
rv = client.get('/getsession')
|
||||
assert rv.data == b'foo'
|
||||
rv = client.get("/getsession")
|
||||
assert rv.data == b"foo"
|
||||
|
||||
|
||||
def test_session_transactions(app, client):
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
return text_type(flask.session['foo'])
|
||||
return text_type(flask.session["foo"])
|
||||
|
||||
with client:
|
||||
with client.session_transaction() as sess:
|
||||
assert len(sess) == 0
|
||||
sess['foo'] = [42]
|
||||
sess["foo"] = [42]
|
||||
assert len(sess) == 1
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'[42]'
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"[42]"
|
||||
with client.session_transaction() as sess:
|
||||
assert len(sess) == 1
|
||||
assert sess['foo'] == [42]
|
||||
assert sess["foo"] == [42]
|
||||
|
||||
|
||||
def test_session_transactions_no_null_sessions():
|
||||
|
|
@ -191,11 +191,11 @@ def test_session_transactions_no_null_sessions():
|
|||
with pytest.raises(RuntimeError) as e:
|
||||
with c.session_transaction() as sess:
|
||||
pass
|
||||
assert 'Session backend did not open a session' in str(e.value)
|
||||
assert "Session backend did not open a session" in str(e.value)
|
||||
|
||||
|
||||
def test_session_transactions_keep_context(app, client, req_ctx):
|
||||
rv = client.get('/')
|
||||
rv = client.get("/")
|
||||
req = flask.request._get_current_object()
|
||||
assert req is not None
|
||||
with client.session_transaction():
|
||||
|
|
@ -207,30 +207,30 @@ def test_session_transaction_needs_cookies(app):
|
|||
with pytest.raises(RuntimeError) as e:
|
||||
with c.session_transaction() as s:
|
||||
pass
|
||||
assert 'cookies' in str(e.value)
|
||||
assert "cookies" in str(e.value)
|
||||
|
||||
|
||||
def test_test_client_context_binding(app, client):
|
||||
app.testing = False
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
def index():
|
||||
flask.g.value = 42
|
||||
return 'Hello World!'
|
||||
return "Hello World!"
|
||||
|
||||
@app.route('/other')
|
||||
@app.route("/other")
|
||||
def other():
|
||||
1 // 0
|
||||
|
||||
with client:
|
||||
resp = client.get('/')
|
||||
resp = client.get("/")
|
||||
assert flask.g.value == 42
|
||||
assert resp.data == b'Hello World!'
|
||||
assert resp.data == b"Hello World!"
|
||||
assert resp.status_code == 200
|
||||
|
||||
resp = client.get('/other')
|
||||
assert not hasattr(flask.g, 'value')
|
||||
assert b'Internal Server Error' in resp.data
|
||||
resp = client.get("/other")
|
||||
assert not hasattr(flask.g, "value")
|
||||
assert b"Internal Server Error" in resp.data
|
||||
assert resp.status_code == 500
|
||||
flask.g.value = 23
|
||||
|
||||
|
|
@ -239,17 +239,17 @@ def test_test_client_context_binding(app, client):
|
|||
except (AttributeError, RuntimeError):
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('some kind of exception expected')
|
||||
raise AssertionError("some kind of exception expected")
|
||||
|
||||
|
||||
def test_reuse_client(client):
|
||||
c = client
|
||||
|
||||
with c:
|
||||
assert client.get('/').status_code == 404
|
||||
assert client.get("/").status_code == 404
|
||||
|
||||
with c:
|
||||
assert client.get('/').status_code == 404
|
||||
assert client.get("/").status_code == 404
|
||||
|
||||
|
||||
def test_test_client_calls_teardown_handlers(app, client):
|
||||
|
|
@ -261,40 +261,40 @@ def test_test_client_calls_teardown_handlers(app, client):
|
|||
|
||||
with client:
|
||||
assert called == []
|
||||
client.get('/')
|
||||
client.get("/")
|
||||
assert called == []
|
||||
assert called == [None]
|
||||
|
||||
del called[:]
|
||||
with client:
|
||||
assert called == []
|
||||
client.get('/')
|
||||
client.get("/")
|
||||
assert called == []
|
||||
client.get('/')
|
||||
client.get("/")
|
||||
assert called == [None]
|
||||
assert called == [None, None]
|
||||
|
||||
|
||||
def test_full_url_request(app, client):
|
||||
@app.route('/action', methods=['POST'])
|
||||
@app.route("/action", methods=["POST"])
|
||||
def action():
|
||||
return 'x'
|
||||
return "x"
|
||||
|
||||
with client:
|
||||
rv = client.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 'gin' in flask.request.form
|
||||
assert 'vodka' in flask.request.args
|
||||
assert "gin" in flask.request.form
|
||||
assert "vodka" in flask.request.args
|
||||
|
||||
|
||||
def test_json_request_and_response(app, client):
|
||||
@app.route('/echo', methods=['POST'])
|
||||
@app.route("/echo", methods=["POST"])
|
||||
def echo():
|
||||
return jsonify(flask.request.get_json())
|
||||
|
||||
with client:
|
||||
json_data = {'drink': {'gin': 1, 'tonic': True}, 'price': 10}
|
||||
rv = client.post('/echo', json=json_data)
|
||||
json_data = {"drink": {"gin": 1, "tonic": True}, "price": 10}
|
||||
rv = client.post("/echo", json=json_data)
|
||||
|
||||
# Request should be in JSON
|
||||
assert flask.request.is_json
|
||||
|
|
@ -308,38 +308,38 @@ def test_json_request_and_response(app, client):
|
|||
|
||||
def test_subdomain():
|
||||
app = flask.Flask(__name__, subdomain_matching=True)
|
||||
app.config['SERVER_NAME'] = 'example.com'
|
||||
app.config["SERVER_NAME"] = "example.com"
|
||||
client = app.test_client()
|
||||
|
||||
@app.route('/', subdomain='<company_id>')
|
||||
@app.route("/", subdomain="<company_id>")
|
||||
def view(company_id):
|
||||
return company_id
|
||||
|
||||
with app.test_request_context():
|
||||
url = flask.url_for('view', company_id='xxx')
|
||||
url = flask.url_for("view", company_id="xxx")
|
||||
|
||||
with client:
|
||||
response = client.get(url)
|
||||
|
||||
assert 200 == response.status_code
|
||||
assert b'xxx' == response.data
|
||||
assert b"xxx" == response.data
|
||||
|
||||
|
||||
def test_nosubdomain(app, client):
|
||||
app.config['SERVER_NAME'] = 'example.com'
|
||||
app.config["SERVER_NAME"] = "example.com"
|
||||
|
||||
@app.route('/<company_id>')
|
||||
@app.route("/<company_id>")
|
||||
def view(company_id):
|
||||
return company_id
|
||||
|
||||
with app.test_request_context():
|
||||
url = flask.url_for('view', company_id='xxx')
|
||||
url = flask.url_for("view", company_id="xxx")
|
||||
|
||||
with client:
|
||||
response = client.get(url)
|
||||
|
||||
assert 200 == response.status_code
|
||||
assert b'xxx' == response.data
|
||||
assert b"xxx" == response.data
|
||||
|
||||
|
||||
def test_cli_runner_class(app):
|
||||
|
|
@ -355,17 +355,17 @@ def test_cli_runner_class(app):
|
|||
|
||||
|
||||
def test_cli_invoke(app):
|
||||
@app.cli.command('hello')
|
||||
@app.cli.command("hello")
|
||||
def hello_command():
|
||||
click.echo('Hello, World!')
|
||||
click.echo("Hello, World!")
|
||||
|
||||
runner = app.test_cli_runner()
|
||||
# invoke with command name
|
||||
result = runner.invoke(args=['hello'])
|
||||
assert 'Hello' in result.output
|
||||
result = runner.invoke(args=["hello"])
|
||||
assert "Hello" in result.output
|
||||
# invoke with command object
|
||||
result = runner.invoke(hello_command)
|
||||
assert 'Hello' in result.output
|
||||
assert "Hello" in result.output
|
||||
|
||||
|
||||
def test_cli_custom_obj(app):
|
||||
|
|
@ -376,9 +376,9 @@ def test_cli_custom_obj(app):
|
|||
NS.called = True
|
||||
return app
|
||||
|
||||
@app.cli.command('hello')
|
||||
@app.cli.command("hello")
|
||||
def hello_command():
|
||||
click.echo('Hello, World!')
|
||||
click.echo("Hello, World!")
|
||||
|
||||
script_info = ScriptInfo(create_app=create_app)
|
||||
runner = app.test_cli_runner()
|
||||
|
|
|
|||
|
|
@ -7,40 +7,34 @@ tests.test_user_error_handler
|
|||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
|
||||
from werkzeug.exceptions import (
|
||||
Forbidden,
|
||||
InternalServerError,
|
||||
HTTPException,
|
||||
NotFound
|
||||
)
|
||||
from werkzeug.exceptions import Forbidden, InternalServerError, HTTPException, NotFound
|
||||
import flask
|
||||
|
||||
|
||||
def test_error_handler_no_match(app, client):
|
||||
|
||||
class CustomException(Exception):
|
||||
pass
|
||||
|
||||
@app.errorhandler(CustomException)
|
||||
def custom_exception_handler(e):
|
||||
assert isinstance(e, CustomException)
|
||||
return 'custom'
|
||||
return "custom"
|
||||
|
||||
@app.errorhandler(500)
|
||||
def handle_500(e):
|
||||
return type(e).__name__
|
||||
|
||||
@app.route('/custom')
|
||||
@app.route("/custom")
|
||||
def custom_test():
|
||||
raise CustomException()
|
||||
|
||||
@app.route('/keyerror')
|
||||
@app.route("/keyerror")
|
||||
def key_error():
|
||||
raise KeyError()
|
||||
|
||||
app.testing = False
|
||||
assert client.get('/custom').data == b'custom'
|
||||
assert client.get('/keyerror').data == b'KeyError'
|
||||
assert client.get("/custom").data == b"custom"
|
||||
assert client.get("/keyerror").data == b"KeyError"
|
||||
|
||||
|
||||
def test_error_handler_subclass(app):
|
||||
|
|
@ -56,30 +50,30 @@ def test_error_handler_subclass(app):
|
|||
@app.errorhandler(ParentException)
|
||||
def parent_exception_handler(e):
|
||||
assert isinstance(e, ParentException)
|
||||
return 'parent'
|
||||
return "parent"
|
||||
|
||||
@app.errorhandler(ChildExceptionRegistered)
|
||||
def child_exception_handler(e):
|
||||
assert isinstance(e, ChildExceptionRegistered)
|
||||
return 'child-registered'
|
||||
return "child-registered"
|
||||
|
||||
@app.route('/parent')
|
||||
@app.route("/parent")
|
||||
def parent_test():
|
||||
raise ParentException()
|
||||
|
||||
@app.route('/child-unregistered')
|
||||
@app.route("/child-unregistered")
|
||||
def unregistered_test():
|
||||
raise ChildExceptionUnregistered()
|
||||
|
||||
@app.route('/child-registered')
|
||||
@app.route("/child-registered")
|
||||
def registered_test():
|
||||
raise ChildExceptionRegistered()
|
||||
|
||||
c = app.test_client()
|
||||
|
||||
assert c.get('/parent').data == b'parent'
|
||||
assert c.get('/child-unregistered').data == b'parent'
|
||||
assert c.get('/child-registered').data == b'child-registered'
|
||||
assert c.get("/parent").data == b"parent"
|
||||
assert c.get("/child-unregistered").data == b"parent"
|
||||
assert c.get("/child-registered").data == b"child-registered"
|
||||
|
||||
|
||||
def test_error_handler_http_subclass(app):
|
||||
|
|
@ -92,78 +86,78 @@ def test_error_handler_http_subclass(app):
|
|||
@app.errorhandler(403)
|
||||
def code_exception_handler(e):
|
||||
assert isinstance(e, Forbidden)
|
||||
return 'forbidden'
|
||||
return "forbidden"
|
||||
|
||||
@app.errorhandler(ForbiddenSubclassRegistered)
|
||||
def subclass_exception_handler(e):
|
||||
assert isinstance(e, ForbiddenSubclassRegistered)
|
||||
return 'forbidden-registered'
|
||||
return "forbidden-registered"
|
||||
|
||||
@app.route('/forbidden')
|
||||
@app.route("/forbidden")
|
||||
def forbidden_test():
|
||||
raise Forbidden()
|
||||
|
||||
@app.route('/forbidden-registered')
|
||||
@app.route("/forbidden-registered")
|
||||
def registered_test():
|
||||
raise ForbiddenSubclassRegistered()
|
||||
|
||||
@app.route('/forbidden-unregistered')
|
||||
@app.route("/forbidden-unregistered")
|
||||
def unregistered_test():
|
||||
raise ForbiddenSubclassUnregistered()
|
||||
|
||||
c = app.test_client()
|
||||
|
||||
assert c.get('/forbidden').data == b'forbidden'
|
||||
assert c.get('/forbidden-unregistered').data == b'forbidden'
|
||||
assert c.get('/forbidden-registered').data == b'forbidden-registered'
|
||||
assert c.get("/forbidden").data == b"forbidden"
|
||||
assert c.get("/forbidden-unregistered").data == b"forbidden"
|
||||
assert c.get("/forbidden-registered").data == b"forbidden-registered"
|
||||
|
||||
|
||||
def test_error_handler_blueprint(app):
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
bp = flask.Blueprint("bp", __name__)
|
||||
|
||||
@bp.errorhandler(500)
|
||||
def bp_exception_handler(e):
|
||||
return 'bp-error'
|
||||
return "bp-error"
|
||||
|
||||
@bp.route('/error')
|
||||
@bp.route("/error")
|
||||
def bp_test():
|
||||
raise InternalServerError()
|
||||
|
||||
@app.errorhandler(500)
|
||||
def app_exception_handler(e):
|
||||
return 'app-error'
|
||||
return "app-error"
|
||||
|
||||
@app.route('/error')
|
||||
@app.route("/error")
|
||||
def app_test():
|
||||
raise InternalServerError()
|
||||
|
||||
app.register_blueprint(bp, url_prefix='/bp')
|
||||
app.register_blueprint(bp, url_prefix="/bp")
|
||||
|
||||
c = app.test_client()
|
||||
|
||||
assert c.get('/error').data == b'app-error'
|
||||
assert c.get('/bp/error').data == b'bp-error'
|
||||
assert c.get("/error").data == b"app-error"
|
||||
assert c.get("/bp/error").data == b"bp-error"
|
||||
|
||||
|
||||
def test_default_error_handler():
|
||||
bp = flask.Blueprint('bp', __name__)
|
||||
bp = flask.Blueprint("bp", __name__)
|
||||
|
||||
@bp.errorhandler(HTTPException)
|
||||
def bp_exception_handler(e):
|
||||
assert isinstance(e, HTTPException)
|
||||
assert isinstance(e, NotFound)
|
||||
return 'bp-default'
|
||||
return "bp-default"
|
||||
|
||||
@bp.errorhandler(Forbidden)
|
||||
def bp_exception_handler(e):
|
||||
assert isinstance(e, Forbidden)
|
||||
return 'bp-forbidden'
|
||||
return "bp-forbidden"
|
||||
|
||||
@bp.route('/undefined')
|
||||
@bp.route("/undefined")
|
||||
def bp_registered_test():
|
||||
raise NotFound()
|
||||
|
||||
@bp.route('/forbidden')
|
||||
@bp.route("/forbidden")
|
||||
def bp_forbidden_test():
|
||||
raise Forbidden()
|
||||
|
||||
|
|
@ -173,14 +167,14 @@ def test_default_error_handler():
|
|||
def catchall_errorhandler(e):
|
||||
assert isinstance(e, HTTPException)
|
||||
assert isinstance(e, NotFound)
|
||||
return 'default'
|
||||
return "default"
|
||||
|
||||
@app.errorhandler(Forbidden)
|
||||
def catchall_errorhandler(e):
|
||||
assert isinstance(e, Forbidden)
|
||||
return 'forbidden'
|
||||
return "forbidden"
|
||||
|
||||
@app.route('/forbidden')
|
||||
@app.route("/forbidden")
|
||||
def forbidden():
|
||||
raise Forbidden()
|
||||
|
||||
|
|
@ -188,12 +182,12 @@ def test_default_error_handler():
|
|||
def slash():
|
||||
return "slash"
|
||||
|
||||
app.register_blueprint(bp, url_prefix='/bp')
|
||||
app.register_blueprint(bp, url_prefix="/bp")
|
||||
|
||||
c = app.test_client()
|
||||
assert c.get('/bp/undefined').data == b'bp-default'
|
||||
assert c.get('/bp/forbidden').data == b'bp-forbidden'
|
||||
assert c.get('/undefined').data == b'default'
|
||||
assert c.get('/forbidden').data == b'forbidden'
|
||||
assert c.get("/bp/undefined").data == b"bp-default"
|
||||
assert c.get("/bp/forbidden").data == b"bp-forbidden"
|
||||
assert c.get("/undefined").data == b"default"
|
||||
assert c.get("/forbidden").data == b"forbidden"
|
||||
# Don't handle RequestRedirect raised when adding slash.
|
||||
assert c.get("/slash", follow_redirects=True).data == b"slash"
|
||||
|
|
|
|||
|
|
@ -20,33 +20,33 @@ from werkzeug.http import parse_set_header
|
|||
def common_test(app):
|
||||
c = app.test_client()
|
||||
|
||||
assert c.get('/').data == b'GET'
|
||||
assert c.post('/').data == b'POST'
|
||||
assert c.put('/').status_code == 405
|
||||
meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])
|
||||
assert sorted(meths) == ['GET', 'HEAD', 'OPTIONS', 'POST']
|
||||
assert c.get("/").data == b"GET"
|
||||
assert c.post("/").data == b"POST"
|
||||
assert c.put("/").status_code == 405
|
||||
meths = parse_set_header(c.open("/", method="OPTIONS").headers["Allow"])
|
||||
assert sorted(meths) == ["GET", "HEAD", "OPTIONS", "POST"]
|
||||
|
||||
|
||||
def test_basic_view(app):
|
||||
class Index(flask.views.View):
|
||||
methods = ['GET', 'POST']
|
||||
methods = ["GET", "POST"]
|
||||
|
||||
def dispatch_request(self):
|
||||
return flask.request.method
|
||||
|
||||
app.add_url_rule('/', view_func=Index.as_view('index'))
|
||||
app.add_url_rule("/", view_func=Index.as_view("index"))
|
||||
common_test(app)
|
||||
|
||||
|
||||
def test_method_based_view(app):
|
||||
class Index(flask.views.MethodView):
|
||||
def get(self):
|
||||
return 'GET'
|
||||
return "GET"
|
||||
|
||||
def post(self):
|
||||
return 'POST'
|
||||
return "POST"
|
||||
|
||||
app.add_url_rule('/', view_func=Index.as_view('index'))
|
||||
app.add_url_rule("/", view_func=Index.as_view("index"))
|
||||
|
||||
common_test(app)
|
||||
|
||||
|
|
@ -61,40 +61,40 @@ def test_view_patching(app):
|
|||
|
||||
class Other(Index):
|
||||
def get(self):
|
||||
return 'GET'
|
||||
return "GET"
|
||||
|
||||
def post(self):
|
||||
return 'POST'
|
||||
return "POST"
|
||||
|
||||
view = Index.as_view('index')
|
||||
view = Index.as_view("index")
|
||||
view.view_class = Other
|
||||
app.add_url_rule('/', view_func=view)
|
||||
app.add_url_rule("/", view_func=view)
|
||||
common_test(app)
|
||||
|
||||
|
||||
def test_view_inheritance(app, client):
|
||||
class Index(flask.views.MethodView):
|
||||
def get(self):
|
||||
return 'GET'
|
||||
return "GET"
|
||||
|
||||
def post(self):
|
||||
return 'POST'
|
||||
return "POST"
|
||||
|
||||
class BetterIndex(Index):
|
||||
def delete(self):
|
||||
return 'DELETE'
|
||||
return "DELETE"
|
||||
|
||||
app.add_url_rule('/', view_func=BetterIndex.as_view('index'))
|
||||
app.add_url_rule("/", view_func=BetterIndex.as_view("index"))
|
||||
|
||||
meths = parse_set_header(client.open('/', method='OPTIONS').headers['Allow'])
|
||||
assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']
|
||||
meths = parse_set_header(client.open("/", method="OPTIONS").headers["Allow"])
|
||||
assert sorted(meths) == ["DELETE", "GET", "HEAD", "OPTIONS", "POST"]
|
||||
|
||||
|
||||
def test_view_decorators(app, client):
|
||||
def add_x_parachute(f):
|
||||
def new_function(*args, **kwargs):
|
||||
resp = flask.make_response(f(*args, **kwargs))
|
||||
resp.headers['X-Parachute'] = 'awesome'
|
||||
resp.headers["X-Parachute"] = "awesome"
|
||||
return resp
|
||||
|
||||
return new_function
|
||||
|
|
@ -103,12 +103,12 @@ def test_view_decorators(app, client):
|
|||
decorators = [add_x_parachute]
|
||||
|
||||
def dispatch_request(self):
|
||||
return 'Awesome'
|
||||
return "Awesome"
|
||||
|
||||
app.add_url_rule('/', view_func=Index.as_view('index'))
|
||||
rv = client.get('/')
|
||||
assert rv.headers['X-Parachute'] == 'awesome'
|
||||
assert rv.data == b'Awesome'
|
||||
app.add_url_rule("/", view_func=Index.as_view("index"))
|
||||
rv = client.get("/")
|
||||
assert rv.headers["X-Parachute"] == "awesome"
|
||||
assert rv.data == b"Awesome"
|
||||
|
||||
|
||||
def test_view_provide_automatic_options_attr():
|
||||
|
|
@ -118,84 +118,82 @@ def test_view_provide_automatic_options_attr():
|
|||
provide_automatic_options = False
|
||||
|
||||
def dispatch_request(self):
|
||||
return 'Hello World!'
|
||||
return "Hello World!"
|
||||
|
||||
app.add_url_rule('/', view_func=Index1.as_view('index'))
|
||||
app.add_url_rule("/", view_func=Index1.as_view("index"))
|
||||
c = app.test_client()
|
||||
rv = c.open('/', method='OPTIONS')
|
||||
rv = c.open("/", method="OPTIONS")
|
||||
assert rv.status_code == 405
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
class Index2(flask.views.View):
|
||||
methods = ['OPTIONS']
|
||||
methods = ["OPTIONS"]
|
||||
provide_automatic_options = True
|
||||
|
||||
def dispatch_request(self):
|
||||
return 'Hello World!'
|
||||
return "Hello World!"
|
||||
|
||||
app.add_url_rule('/', view_func=Index2.as_view('index'))
|
||||
app.add_url_rule("/", view_func=Index2.as_view("index"))
|
||||
c = app.test_client()
|
||||
rv = c.open('/', method='OPTIONS')
|
||||
assert sorted(rv.allow) == ['OPTIONS']
|
||||
rv = c.open("/", method="OPTIONS")
|
||||
assert sorted(rv.allow) == ["OPTIONS"]
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
class Index3(flask.views.View):
|
||||
def dispatch_request(self):
|
||||
return 'Hello World!'
|
||||
return "Hello World!"
|
||||
|
||||
app.add_url_rule('/', view_func=Index3.as_view('index'))
|
||||
app.add_url_rule("/", view_func=Index3.as_view("index"))
|
||||
c = app.test_client()
|
||||
rv = c.open('/', method='OPTIONS')
|
||||
assert 'OPTIONS' in rv.allow
|
||||
rv = c.open("/", method="OPTIONS")
|
||||
assert "OPTIONS" in rv.allow
|
||||
|
||||
|
||||
def test_implicit_head(app, client):
|
||||
class Index(flask.views.MethodView):
|
||||
def get(self):
|
||||
return flask.Response('Blub', headers={
|
||||
'X-Method': flask.request.method
|
||||
})
|
||||
return flask.Response("Blub", headers={"X-Method": flask.request.method})
|
||||
|
||||
app.add_url_rule('/', view_func=Index.as_view('index'))
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'Blub'
|
||||
assert rv.headers['X-Method'] == 'GET'
|
||||
rv = client.head('/')
|
||||
assert rv.data == b''
|
||||
assert rv.headers['X-Method'] == 'HEAD'
|
||||
app.add_url_rule("/", view_func=Index.as_view("index"))
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"Blub"
|
||||
assert rv.headers["X-Method"] == "GET"
|
||||
rv = client.head("/")
|
||||
assert rv.data == b""
|
||||
assert rv.headers["X-Method"] == "HEAD"
|
||||
|
||||
|
||||
def test_explicit_head(app, client):
|
||||
class Index(flask.views.MethodView):
|
||||
def get(self):
|
||||
return 'GET'
|
||||
return "GET"
|
||||
|
||||
def head(self):
|
||||
return flask.Response('', headers={'X-Method': 'HEAD'})
|
||||
return flask.Response("", headers={"X-Method": "HEAD"})
|
||||
|
||||
app.add_url_rule('/', view_func=Index.as_view('index'))
|
||||
rv = client.get('/')
|
||||
assert rv.data == b'GET'
|
||||
rv = client.head('/')
|
||||
assert rv.data == b''
|
||||
assert rv.headers['X-Method'] == 'HEAD'
|
||||
app.add_url_rule("/", view_func=Index.as_view("index"))
|
||||
rv = client.get("/")
|
||||
assert rv.data == b"GET"
|
||||
rv = client.head("/")
|
||||
assert rv.data == b""
|
||||
assert rv.headers["X-Method"] == "HEAD"
|
||||
|
||||
|
||||
def test_endpoint_override(app):
|
||||
app.debug = True
|
||||
|
||||
class Index(flask.views.View):
|
||||
methods = ['GET', 'POST']
|
||||
methods = ["GET", "POST"]
|
||||
|
||||
def dispatch_request(self):
|
||||
return flask.request.method
|
||||
|
||||
app.add_url_rule('/', view_func=Index.as_view('index'))
|
||||
app.add_url_rule("/", view_func=Index.as_view("index"))
|
||||
|
||||
with pytest.raises(AssertionError):
|
||||
app.add_url_rule('/', view_func=Index.as_view('index'))
|
||||
app.add_url_rule("/", view_func=Index.as_view("index"))
|
||||
|
||||
# But these tests should still pass. We just log a warning.
|
||||
common_test(app)
|
||||
|
|
@ -204,36 +202,36 @@ def test_endpoint_override(app):
|
|||
def test_multiple_inheritance(app, client):
|
||||
class GetView(flask.views.MethodView):
|
||||
def get(self):
|
||||
return 'GET'
|
||||
return "GET"
|
||||
|
||||
class DeleteView(flask.views.MethodView):
|
||||
def delete(self):
|
||||
return 'DELETE'
|
||||
return "DELETE"
|
||||
|
||||
class GetDeleteView(GetView, DeleteView):
|
||||
pass
|
||||
|
||||
app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))
|
||||
app.add_url_rule("/", view_func=GetDeleteView.as_view("index"))
|
||||
|
||||
assert client.get('/').data == b'GET'
|
||||
assert client.delete('/').data == b'DELETE'
|
||||
assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']
|
||||
assert client.get("/").data == b"GET"
|
||||
assert client.delete("/").data == b"DELETE"
|
||||
assert sorted(GetDeleteView.methods) == ["DELETE", "GET"]
|
||||
|
||||
|
||||
def test_remove_method_from_parent(app, client):
|
||||
class GetView(flask.views.MethodView):
|
||||
def get(self):
|
||||
return 'GET'
|
||||
return "GET"
|
||||
|
||||
class OtherView(flask.views.MethodView):
|
||||
def post(self):
|
||||
return 'POST'
|
||||
return "POST"
|
||||
|
||||
class View(GetView, OtherView):
|
||||
methods = ['GET']
|
||||
methods = ["GET"]
|
||||
|
||||
app.add_url_rule('/', view_func=View.as_view('index'))
|
||||
app.add_url_rule("/", view_func=View.as_view("index"))
|
||||
|
||||
assert client.get('/').data == b'GET'
|
||||
assert client.post('/').status_code == 405
|
||||
assert sorted(View.methods) == ['GET']
|
||||
assert client.get("/").data == b"GET"
|
||||
assert client.post("/").status_code == 405
|
||||
assert sorted(View.methods) == ["GET"]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue