f-strings everywhere

This commit is contained in:
David Lord 2020-04-04 11:39:03 -07:00
parent 524fd0bc8c
commit 2ae740dd49
No known key found for this signature in database
GPG key ID: 7A1C87E3F5BC42A8
35 changed files with 227 additions and 245 deletions

View file

@ -116,9 +116,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
raise AttributeError(msg)
if name in {"archive", "get_filename"}:
raise AttributeError(f"Mocking a loader which does not have {name!r}.")
return getattr(self.loader, name)
old_get_loader = pkgutil.get_loader
@ -148,7 +147,7 @@ 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(f"python{sys.version_info.major}.{sys.version_info.minor}")
.mkdir("site-packages")
)
monkeypatch.syspath_prepend(str(rv))
@ -161,23 +160,21 @@ def install_egg(modules_tmpdir, monkeypatch):
sys.path."""
def inner(name, base=modules_tmpdir):
if not isinstance(name, str):
raise ValueError(name)
base.join(name).ensure_dir()
base.join(name).join("__init__.py").ensure()
egg_setup = base.join("setup.py")
egg_setup.write(
textwrap.dedent(
"""
from setuptools import setup
setup(name='{}',
version='1.0',
packages=['site_egg'],
zip_safe=True)
""".format(
name
f"""
from setuptools import setup
setup(
name="{name}",
version="1.0",
packages=["site_egg"],
zip_safe=True,
)
"""
)
)

View file

@ -361,7 +361,7 @@ def test_session_localhost_warning(recwarn, app, client):
rv = client.get("/", "http://localhost:5000/")
assert "domain" not in rv.headers["set-cookie"].lower()
w = recwarn.pop(UserWarning)
assert '"localhost" is not a valid cookie domain' in str(w.message)
assert "'localhost' is not a valid cookie domain" in str(w.message)
def test_session_ip_warning(recwarn, app, client):
@ -1095,7 +1095,7 @@ def test_enctype_debug_helper(app, client):
with pytest.raises(DebugFilesKeyError) as e:
client.post("/fail", data={"foo": "index.txt"})
assert "no file contents were transmitted" in str(e.value)
assert 'This was submitted: "index.txt"' in str(e.value)
assert "This was submitted: 'index.txt'" in str(e.value)
def test_response_types(app, client):
@ -1821,7 +1821,7 @@ def test_subdomain_matching():
@app.route("/", subdomain="<user>")
def index(user):
return "index for %s" % user
return f"index for {user}"
rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")
assert rv.data == b"index for mitsuhiko"
@ -1834,7 +1834,7 @@ def test_subdomain_matching_with_ports():
@app.route("/", subdomain="<user>")
def index(user):
return "index for %s" % user
return f"index for {user}"
rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")
assert rv.data == b"index for mitsuhiko"

View file

@ -144,7 +144,7 @@ def test_blueprint_url_defaults(app, client):
@bp.route("/foo", defaults={"baz": 42})
def foo(bar, baz):
return "%s/%d" % (bar, baz)
return f"{bar}/{baz:d}"
@bp.route("/bar")
def bar(bar):

View file

@ -268,9 +268,9 @@ def test_get_version(test_apps, capsys):
ctx = MockCtx()
get_version(ctx, None, "test")
out, err = capsys.readouterr()
assert "Python " + python_version() in out
assert "Flask " + flask_version in out
assert "Werkzeug " + werkzeug_version in out
assert f"Python {python_version()}" in out
assert f"Flask {flask_version}" in out
assert f"Werkzeug {werkzeug_version}" in out
def test_scriptinfo(test_apps, monkeypatch):
@ -288,7 +288,7 @@ def test_scriptinfo(test_apps, monkeypatch):
app = obj.load_app()
assert app.name == "testapp"
assert obj.load_app() is app
obj = ScriptInfo(app_import_path=cli_app_path + ":testapp")
obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")
app = obj.load_app()
assert app.name == "testapp"
assert obj.load_app() is app
@ -406,7 +406,7 @@ def test_flaskgroup_debug(runner, set_debug_flag):
result = runner.invoke(cli, ["test"])
assert result.exit_code == 0
assert result.output == "%s\n" % str(not set_debug_flag)
assert result.output == f"{not set_debug_flag}\n"
def test_print_exceptions(runner):
@ -656,4 +656,4 @@ def test_cli_empty(app):
app.register_blueprint(bp)
result = app.test_cli_runner().invoke(args=["blue", "--help"])
assert result.exit_code == 2, "Unexpected success:\n\n" + result.output
assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"

View file

@ -28,7 +28,7 @@ def common_object_test(app):
def test_config_from_pyfile():
app = flask.Flask(__name__)
app.config.from_pyfile(__file__.rsplit(".", 1)[0] + ".py")
app.config.from_pyfile(f"{__file__.rsplit('.', 1)[0]}.py")
common_object_test(app)
@ -84,7 +84,7 @@ def test_config_from_envvar(monkeypatch):
assert not app.config.from_envvar("FOO_SETTINGS", silent=True)
monkeypatch.setattr(
"os.environ", {"FOO_SETTINGS": __file__.rsplit(".", 1)[0] + ".py"}
"os.environ", {"FOO_SETTINGS": f"{__file__.rsplit('.', 1)[0]}.py"}
)
assert app.config.from_envvar("FOO_SETTINGS")
common_object_test(app)
@ -185,12 +185,10 @@ def test_from_pyfile_weird_encoding(tmpdir, encoding):
f = tmpdir.join("my_config.py")
f.write_binary(
textwrap.dedent(
f"""
# -*- coding: {encoding} -*-
TEST_VALUE = "föö"
"""
# -*- coding: {} -*-
TEST_VALUE = "föö"
""".format(
encoding
)
).encode(encoding)
)
app = flask.Flask(__name__)

View file

@ -286,7 +286,7 @@ class TestJSON:
class MyEncoder(flask.json.JSONEncoder):
def default(self, o):
if isinstance(o, X):
return "<%d>" % o.val
return f"<{o.val}>"
return flask.json.JSONEncoder.default(self, o)
class MyDecoder(flask.json.JSONDecoder):
@ -314,14 +314,16 @@ class TestJSON:
assert rv.data == b'"<42>"'
def test_blueprint_json_customization(self, app, client):
class X: # noqa: B903, for Python2 compatibility
class X:
__slots__ = ("val",)
def __init__(self, val):
self.val = val
class MyEncoder(flask.json.JSONEncoder):
def default(self, o):
if isinstance(o, X):
return "<%d>" % o.val
return f"<{o.val}>"
return flask.json.JSONEncoder.default(self, o)
@ -687,9 +689,9 @@ class TestSendfile:
)
rv.close()
content_disposition = rv.headers["Content-Disposition"]
assert "filename=%s" % ascii in content_disposition
assert f"filename={ascii}" in content_disposition
if utf8:
assert "filename*=UTF-8''" + utf8 in content_disposition
assert f"filename*=UTF-8''{utf8}" in content_disposition
else:
assert "filename*=UTF-8''" not in content_disposition
@ -818,7 +820,7 @@ class TestUrlFor:
def get(self, id=None):
if id is None:
return "List"
return "Get %d" % id
return f"Get {id:d}"
def post(self):
return "Create"

View file

@ -110,7 +110,7 @@ def test_proper_test_request_context(app):
def test_context_binding(app):
@app.route("/")
def index():
return "Hello %s!" % flask.request.args["name"]
return f"Hello {flask.request.args['name']}!"
@app.route("/meh")
def meh():
@ -138,7 +138,7 @@ def test_context_test(app):
def test_manual_context_binding(app):
@app.route("/")
def index():
return "Hello %s!" % flask.request.args["name"]
return f"Hello {flask.request.args['name']}!"
ctx = app.test_request_context("/?name=World")
ctx.push()

View file

@ -414,16 +414,16 @@ def test_template_loader_debugging(test_apps, monkeypatch):
def handle(self, record):
called.append(True)
text = str(record.msg)
assert '1: trying loader of application "blueprintapp"' in text
assert "1: trying loader of application 'blueprintapp'" in text
assert (
'2: trying loader of blueprint "admin" (blueprintapp.apps.admin)'
"2: trying loader of blueprint 'admin' (blueprintapp.apps.admin)"
) in text
assert (
'trying loader of blueprint "frontend" (blueprintapp.apps.frontend)'
"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"'
"looked up from an endpoint that belongs to the blueprint 'frontend'"
) in text
assert "See https://flask.palletsprojects.com/blueprints/#templates" in text

View file

@ -59,7 +59,7 @@ def test_environ_base_default(app, client, app_ctx):
rv = client.get("/")
assert rv.data == b"127.0.0.1"
assert flask.g.user_agent == "werkzeug/" + werkzeug.__version__
assert flask.g.user_agent == f"werkzeug/{werkzeug.__version__}"
def test_environ_base_modified(app, client, app_ctx):
@ -321,7 +321,7 @@ def test_json_request_and_response(app, client):
def test_client_json_no_app_context(app, client):
@app.route("/hello", methods=["POST"])
def hello():
return "Hello, {}!".format(flask.request.json["name"])
return f"Hello, {flask.request.json['name']}!"
class Namespace:
count = 0

View file

@ -29,7 +29,7 @@ def test_error_handler_no_match(app, client):
original = getattr(e, "original_exception", None)
if original is not None:
return "wrapped " + type(original).__name__
return f"wrapped {type(original).__name__}"
return "direct"
@ -238,9 +238,9 @@ class TestGenericHandlers:
original = getattr(e, "original_exception", None)
if original is not None:
return "wrapped " + type(original).__name__
return f"wrapped {type(original).__name__}"
return "direct " + type(e).__name__
return f"direct {type(e).__name__}"
@pytest.mark.parametrize("to_handle", (InternalServerError, 500))
def test_handle_class_or_code(self, app, client, to_handle):