Skip to content

Commit

Permalink
Update old string formatting to f-strings (#1018)
Browse files Browse the repository at this point in the history
  • Loading branch information
akx committed Oct 21, 2022
1 parent 9c64b44 commit 1f3708a
Show file tree
Hide file tree
Showing 9 changed files with 32 additions and 40 deletions.
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

# General information about the project.
project = 'pytest-django'
copyright = '%d, Andreas Pelme and contributors' % datetime.date.today().year
copyright = f'{datetime.date.today().year}, Andreas Pelme and contributors'

exclude_patterns = ['_build']

Expand Down
16 changes: 7 additions & 9 deletions pytest_django/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def teardown_database() -> None:
except Exception as exc:
request.node.warn(
pytest.PytestWarning(
"Error when trying to teardown test databases: %r" % exc
f"Error when trying to teardown test databases: {exc!r}"
)
)

Expand Down Expand Up @@ -287,7 +287,7 @@ def _set_suffix_to_test_databases(suffix: str) -> None:
if not test_name:
if db_settings["ENGINE"] == "django.db.backends.sqlite3":
continue
test_name = "test_{}".format(db_settings["NAME"])
test_name = f"test_{db_settings['NAME']}"

if test_name == ":memory:":
continue
Expand Down Expand Up @@ -591,13 +591,11 @@ def _assert_num_queries(
else:
failed = num_performed > num
if failed:
msg = "Expected to perform {} queries {}{}".format(
num,
"" if exact else "or less ",
"but {} done".format(
num_performed == 1 and "1 was" or f"{num_performed} were"
),
)
msg = f"Expected to perform {num} queries "
if not exact:
msg += "or less "
verb = "was" if num_performed == 1 else "were"
msg += f"but {num_performed} {verb} done"
if info:
msg += f"\n{info}"
if verbose:
Expand Down
2 changes: 1 addition & 1 deletion pytest_django/live_server_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,4 @@ def __add__(self, other) -> str:
return f"{self}{other}"

def __repr__(self) -> str:
return "<LiveServer listening at %s>" % self.url
return f"<LiveServer listening at {self.url}>"
6 changes: 3 additions & 3 deletions pytest_django/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,9 +251,9 @@ def _get_boolean_value(
try:
return possible_values[x.lower()]
except KeyError:
possible = ", ".join(possible_values)
raise ValueError(
"{} is not a valid value for {}. "
"It must be one of {}.".format(x, name, ", ".join(possible_values.keys()))
f"{x} is not a valid value for {name}. It must be one of {possible}."
)


Expand Down Expand Up @@ -621,7 +621,7 @@ def __mod__(self, var: str) -> str:
if origin:
msg = f"Undefined template variable '{var}' in '{origin}'"
else:
msg = "Undefined template variable '%s'" % var
msg = f"Undefined template variable '{var}'"
if self.fail:
pytest.fail(msg)
else:
Expand Down
2 changes: 1 addition & 1 deletion pytest_django_test/app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ def admin_required_view(request: HttpRequest) -> HttpResponse:


def item_count(request: HttpRequest) -> HttpResponse:
return HttpResponse("Item count: %d" % Item.objects.count())
return HttpResponse(f"Item count: {Item.objects.count()}")
12 changes: 6 additions & 6 deletions pytest_django_test/db_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,18 +102,18 @@ def drop_database(db_suffix=None):
db_engine = get_db_engine()

if db_engine == "postgresql":
r = run_psql("postgres", "-c", "DROP DATABASE %s" % name)
r = run_psql("postgres", "-c", f"DROP DATABASE {name}")
assert "DROP DATABASE" in force_str(
r.std_out
) or "does not exist" in force_str(r.std_err)
return

if db_engine == "mysql":
r = run_mysql("-e", "DROP DATABASE %s" % name)
r = run_mysql("-e", f"DROP DATABASE {name}")
assert "database doesn't exist" in force_str(r.std_err) or r.status_code == 0
return

assert db_engine == "sqlite3", "%s cannot be tested properly!" % db_engine
assert db_engine == "sqlite3", f"{db_engine} cannot be tested properly!"
assert name != ":memory:", "sqlite in-memory database cannot be dropped!"
if os.path.exists(name): # pragma: no branch
os.unlink(name)
Expand All @@ -131,7 +131,7 @@ def db_exists(db_suffix=None):
r = run_mysql(name, "-e", "SELECT 1")
return r.status_code == 0

assert db_engine == "sqlite3", "%s cannot be tested properly!" % db_engine
assert db_engine == "sqlite3", f"{db_engine} cannot be tested properly!"
assert TEST_DB_NAME != ":memory:", (
"sqlite in-memory database cannot be checked for existence!")
return os.path.exists(name)
Expand All @@ -150,7 +150,7 @@ def mark_database():
assert r.status_code == 0
return

assert db_engine == "sqlite3", "%s cannot be tested properly!" % db_engine
assert db_engine == "sqlite3", f"{db_engine} cannot be tested properly!"
assert TEST_DB_NAME != ":memory:", (
"sqlite in-memory database cannot be marked!")

Expand All @@ -175,7 +175,7 @@ def mark_exists():

return r.status_code == 0

assert db_engine == "sqlite3", "%s cannot be tested properly!" % db_engine
assert db_engine == "sqlite3", f"{db_engine} cannot be tested properly!"
assert TEST_DB_NAME != ":memory:", (
"sqlite in-memory database cannot be checked for mark!")

Expand Down
22 changes: 9 additions & 13 deletions tests/test_django_settings_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,12 +310,10 @@ def test_debug_is_false():
@pytest.mark.parametrize('django_debug_mode', (False, True))
def test_django_debug_mode_true_false(testdir, monkeypatch, django_debug_mode: bool) -> None:
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
testdir.makeini(
"""
testdir.makeini(f"""
[pytest]
django_debug_mode = {}
""".format(django_debug_mode)
)
django_debug_mode = {django_debug_mode}
""")
testdir.makeconftest(
"""
from django.conf import settings
Expand All @@ -331,13 +329,11 @@ def pytest_configure():
""" % (not django_debug_mode)
)

testdir.makepyfile(
"""
testdir.makepyfile(f"""
from django.conf import settings
def test_debug_is_false():
assert settings.DEBUG is {}
""".format(django_debug_mode)
)
assert settings.DEBUG is {django_debug_mode}
""")

r = testdir.runpytest_subprocess()
assert r.ret == 0
Expand Down Expand Up @@ -368,11 +364,11 @@ def pytest_configure():
)

testdir.makepyfile(
"""
f"""
from django.conf import settings
def test_debug_is_false():
assert settings.DEBUG is {}
""".format(settings_debug)
assert settings.DEBUG is {settings_debug}
"""
)

r = testdir.runpytest_subprocess()
Expand Down
4 changes: 1 addition & 3 deletions tests/test_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,7 @@ def test_ignore(client):
result.stdout.fnmatch_lines_random(
[
"tpkg/test_the_test.py F.*",
"E * Failed: Undefined template variable 'invalid_var' in {}".format(
origin
),
f"E * Failed: Undefined template variable 'invalid_var' in {origin}",
]
)

Expand Down
6 changes: 3 additions & 3 deletions tests/test_fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,7 +546,7 @@ def test_with_live_server(live_server):
% port
)

django_testdir.runpytest_subprocess("--liveserver=localhost:%s" % port)
django_testdir.runpytest_subprocess(f"--liveserver=localhost:{port}")


@pytest.mark.parametrize("username_field", ("email", "identifier"))
Expand All @@ -565,7 +565,7 @@ def test_with_live_server(live_server):
)
def test_custom_user_model(django_testdir, username_field) -> None:
django_testdir.create_app_file(
"""
f"""
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
Expand Down Expand Up @@ -599,7 +599,7 @@ class MyCustomUser(AbstractBaseUser, PermissionsMixin):
objects = MyCustomUserManager()
USERNAME_FIELD = '{username_field}'
""".format(username_field=username_field),
""",
"models.py",
)
django_testdir.create_app_file(
Expand Down

0 comments on commit 1f3708a

Please sign in to comment.