Reformat with black

https://github.com/python/black
This commit is contained in:
David Baumgold 2019-05-06 15:39:41 -04:00
parent 5b309831ec
commit 025589ee76
63 changed files with 3784 additions and 3459 deletions

View file

@ -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__])