python: Convert more "".format to Python 3.6 f-strings.

Generated by pyupgrade --py36-plus --keep-percent-format.

Now including %d, %i, %u, and multi-line strings.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg 2020-06-12 23:57:35 -07:00 committed by Tim Abbott
parent 4aeb02f73d
commit 57a80856a5
14 changed files with 52 additions and 58 deletions

View File

@ -15,9 +15,9 @@ from scripts.lib.zulip_tools import get_config_file
def write_realm_nginx_config_line(f: Any, host: str, port: str) -> None: def write_realm_nginx_config_line(f: Any, host: str, port: str) -> None:
f.write("""if ($host = '{}') {{ f.write(f"""if ($host = '{host}') {{
set $tornado_server http://tornado{}; set $tornado_server http://tornado{port};
}}\n""".format(host, port)) }}\n""")
# Basic system to do Tornado sharding. Writes two output .tmp files that need # Basic system to do Tornado sharding. Writes two output .tmp files that need
# to be renamed to the following files to finalize the changes: # to be renamed to the following files to finalize the changes:

View File

@ -118,7 +118,7 @@ def set_user_data(username: str, userkey_dicts: List[Dict[str, Any]]) -> str:
server_repo_setup = setup_repo.format(username, "zulip") server_repo_setup = setup_repo.format(username, "zulip")
python_api_repo_setup = setup_repo.format(username, "python-zulip-api") python_api_repo_setup = setup_repo.format(username, "python-zulip-api")
cloudconf = """\ cloudconf = f"""\
#!/bin/bash #!/bin/bash
{setup_zulipdev_ssh_keys} {setup_zulipdev_ssh_keys}
@ -130,10 +130,7 @@ su -c '{server_repo_setup}' zulipdev
su -c '{python_api_repo_setup}' zulipdev su -c '{python_api_repo_setup}' zulipdev
su -c 'git config --global core.editor nano' zulipdev su -c 'git config --global core.editor nano' zulipdev
su -c 'git config --global pull.rebase true' zulipdev su -c 'git config --global pull.rebase true' zulipdev
""".format(setup_root_ssh_keys=setup_root_ssh_keys, """
setup_zulipdev_ssh_keys=setup_zulipdev_ssh_keys,
hostname_setup=hostname_setup,
server_repo_setup=server_repo_setup, python_api_repo_setup=python_api_repo_setup)
print("...returning cloud-config data.") print("...returning cloud-config data.")
return cloudconf return cloudconf

View File

@ -181,9 +181,9 @@ def build_id_dict(templates: List[str]) -> (Dict[str, List[str]]):
try: try:
list_tags = tokenize(text) list_tags = tokenize(text)
except FormattedException as e: except FormattedException as e:
raise Exception(''' raise Exception(f'''
fn: {} fn: {fn}
{}'''.format(fn, e)) {e}''')
for tag in list_tags: for tag in list_tags:
info = get_tag_info(tag) info = get_tag_info(tag)

View File

@ -213,9 +213,9 @@ def validate(fn: Optional[str] = None, text: Optional[str] = None, check_indent:
try: try:
tokens = tokenize(text) tokens = tokenize(text)
except FormattedException as e: except FormattedException as e:
raise TemplateParserException(''' raise TemplateParserException(f'''
fn: {} fn: {fn}
{}'''.format(fn, e)) {e}''')
class State: class State:
def __init__(self, func: Callable[[Token], None]) -> None: def __init__(self, func: Callable[[Token], None]) -> None:

View File

@ -447,17 +447,14 @@ class Config:
You must specify a virtual_parent if you are You must specify a virtual_parent if you are
using id_source.''') using id_source.''')
if self.id_source[0] != self.virtual_parent.table: if self.id_source[0] != self.virtual_parent.table:
raise AssertionError(''' raise AssertionError(f'''
Configuration error. To populate {}, you Configuration error. To populate {self.table}, you
want data from {}, but that differs from want data from {self.id_source[0]}, but that differs from
the table name of your virtual parent ({}), the table name of your virtual parent ({self.virtual_parent.table}),
which suggests you many not have set up which suggests you many not have set up
the ordering correctly. You may simply the ordering correctly. You may simply
need to assign a virtual_parent, or there need to assign a virtual_parent, or there
may be deeper issues going on.'''.format( may be deeper issues going on.''')
self.table,
self.id_source[0],
self.virtual_parent.table))
def export_from_config(response: TableData, config: Config, seed_object: Optional[Any]=None, def export_from_config(response: TableData, config: Config, seed_object: Optional[Any]=None,

View File

@ -127,11 +127,11 @@ path_maps: Dict[str, Dict[str, str]] = {
def update_id_map(table: TableName, old_id: int, new_id: int) -> None: def update_id_map(table: TableName, old_id: int, new_id: int) -> None:
if table not in ID_MAP: if table not in ID_MAP:
raise Exception(''' raise Exception(f'''
Table {} is not initialized in ID_MAP, which could Table {table} is not initialized in ID_MAP, which could
mean that we have not thought through circular mean that we have not thought through circular
dependencies. dependencies.
'''.format(table)) ''')
ID_MAP[table][old_id] = new_id ID_MAP[table][old_id] = new_id
def fix_datetime_fields(data: TableData, table: TableName) -> None: def fix_datetime_fields(data: TableData, table: TableName) -> None:

View File

@ -684,11 +684,11 @@ class ZulipTestCase(TestCase):
history_public_to_subscribers=history_public_to_subscribers, history_public_to_subscribers=history_public_to_subscribers,
) )
except IntegrityError: # nocoverage -- this is for bugs in the tests except IntegrityError: # nocoverage -- this is for bugs in the tests
raise Exception(''' raise Exception(f'''
{} already exists {stream_name} already exists
Please call make_stream with a stream name Please call make_stream with a stream name
that is not already in use.'''.format(stream_name)) that is not already in use.''')
recipient = Recipient.objects.create(type_id=stream.id, type=Recipient.STREAM) recipient = Recipient.objects.create(type_id=stream.id, type=Recipient.STREAM)
stream.recipient = recipient stream.recipient = recipient

View File

@ -197,10 +197,10 @@ def get_openapi_param_example_value_as_string(endpoint: str, method: str, param:
if param_type in ["object", "array"]: if param_type in ["object", "array"]:
example_value = param.get("example", None) example_value = param.get("example", None)
if not example_value: if not example_value:
msg = """All array and object type request parameters must have msg = f"""All array and object type request parameters must have
concrete examples. The openAPI documentation for {}/{} is missing an example concrete examples. The openAPI documentation for {endpoint}/{method} is missing an example
value for the {} parameter. Without this we cannot automatically generate a value for the {param_name} parameter. Without this we cannot automatically generate a
cURL example.""".format(endpoint, method, param_name) cURL example."""
raise ValueError(msg) raise ValueError(msg)
ordered_ex_val_str = json.dumps(example_value, sort_keys=True) ordered_ex_val_str = json.dumps(example_value, sort_keys=True)
if curl_argument: if curl_argument:

View File

@ -207,7 +207,7 @@ def validate_object(content: Dict[str, Any], schema: Dict[str, Any]) -> None:
if req_key in exclusion_list: if req_key in exclusion_list:
continue continue
if req_key not in content.keys(): if req_key not in content.keys():
raise SchemaError('Expected to find the "{}" required key'.format(req_key)) raise SchemaError(f'Expected to find the "{req_key}" required key')
def to_python_type(py_type: str) -> type: def to_python_type(py_type: str) -> type:
"""Transform an OpenAPI-like type to a Python one. """Transform an OpenAPI-like type to a Python one.

View File

@ -258,7 +258,7 @@ def get_subscription_status(client: Client) -> None:
user_id = 7 user_id = 7
stream_id = 1 stream_id = 1
result = client.call_endpoint( result = client.call_endpoint(
url='/users/{}/subscriptions/{}'.format(user_id, stream_id), url=f'/users/{user_id}/subscriptions/{stream_id}',
method='GET', method='GET',
) )
# {code_example|end} # {code_example|end}

View File

@ -336,10 +336,10 @@ class OpenAPIArgumentsTest(ZulipTestCase):
try: try:
get_openapi_parameters(url_pattern, method) get_openapi_parameters(url_pattern, method)
if not msg: # nocoverage if not msg: # nocoverage
msg = """ msg = f"""
We found some OpenAPI documentation for {method} {url_pattern}, We found some OpenAPI documentation for {method} {url_pattern},
so maybe we shouldn't mark it as intentionally undocumented in the urls. so maybe we shouldn't mark it as intentionally undocumented in the urls.
""".format(method=method, url_pattern=url_pattern) """
raise AssertionError(msg) # nocoverage raise AssertionError(msg) # nocoverage
except KeyError: except KeyError:
return return
@ -427,9 +427,9 @@ so maybe we shouldn't mark it as intentionally undocumented in the urls.
""" Print a *VERY* clear and verbose error message for when the types """ Print a *VERY* clear and verbose error message for when the types
(between the OpenAPI documentation and the function declaration) don't match. """ (between the OpenAPI documentation and the function declaration) don't match. """
msg = """ msg = f"""
The types for the request parameters in zerver/openapi/zulip.yaml The types for the request parameters in zerver/openapi/zulip.yaml
do not match the types declared in the implementation of {}.\n""".format(function.__name__) do not match the types declared in the implementation of {function.__name__}.\n"""
msg += '='*65 + '\n' msg += '='*65 + '\n'
msg += "{:<10s}{:^30s}{:>10s}\n".format("Parameter", "OpenAPI Type", msg += "{:<10s}{:^30s}{:>10s}\n".format("Parameter", "OpenAPI Type",
"Function Declaration Type") "Function Declaration Type")
@ -582,10 +582,10 @@ do not match the types declared in the implementation of {}.\n""".format(functio
if url_pattern in self.pending_endpoints: if url_pattern in self.pending_endpoints:
# HACK: After all pending_endpoints have been resolved, we should remove # HACK: After all pending_endpoints have been resolved, we should remove
# this segment and the "msg" part of the `ensure_no_...` method. # this segment and the "msg" part of the `ensure_no_...` method.
msg = """ msg = f"""
We found some OpenAPI documentation for {method} {url_pattern}, We found some OpenAPI documentation for {method} {url_pattern},
so maybe we shouldn't include it in pending_endpoints. so maybe we shouldn't include it in pending_endpoints.
""".format(method=method, url_pattern=url_pattern) """
self.ensure_no_documentation_if_intentionally_undocumented(url_pattern, self.ensure_no_documentation_if_intentionally_undocumented(url_pattern,
method, msg) method, msg)
continue continue

View File

@ -880,12 +880,12 @@ class InviteUserTest(InviteUserBase):
actual_count = len(queries) actual_count = len(queries)
expected_count = 312 expected_count = 312
if abs(actual_count - expected_count) > 1: if abs(actual_count - expected_count) > 1:
raise AssertionError(''' raise AssertionError(f'''
Unexpected number of queries: Unexpected number of queries:
expected query count: {} expected query count: {expected_count}
actual: {} actual: {actual_count}
'''.format(expected_count, actual_count)) ''')
self.assert_json_success(result) self.assert_json_success(result)

View File

@ -494,7 +494,7 @@ class PermissionTest(ZulipTestCase):
req = dict(role=UserProfile.ROLE_GUEST) req = dict(role=UserProfile.ROLE_GUEST)
events: List[Mapping[str, Any]] = [] events: List[Mapping[str, Any]] = []
with tornado_redirected_to_list(events): with tornado_redirected_to_list(events):
result = self.client_patch('/json/users/{}'.format(iago.id), req) result = self.client_patch(f'/json/users/{iago.id}', req)
self.assert_json_success(result) self.assert_json_success(result)
iago = self.example_user("iago") iago = self.example_user("iago")
@ -518,7 +518,7 @@ class PermissionTest(ZulipTestCase):
req = dict(role=UserProfile.ROLE_REALM_OWNER) req = dict(role=UserProfile.ROLE_REALM_OWNER)
events: List[Mapping[str, Any]] = [] events: List[Mapping[str, Any]] = []
with tornado_redirected_to_list(events): with tornado_redirected_to_list(events):
result = self.client_patch('/json/users/{}'.format(polonius.id), req) result = self.client_patch(f'/json/users/{polonius.id}', req)
self.assert_json_success(result) self.assert_json_success(result)
polonius = self.example_user("polonius") polonius = self.example_user("polonius")
@ -542,7 +542,7 @@ class PermissionTest(ZulipTestCase):
req = dict(role=UserProfile.ROLE_REALM_OWNER) req = dict(role=UserProfile.ROLE_REALM_OWNER)
events: List[Mapping[str, Any]] = [] events: List[Mapping[str, Any]] = []
with tornado_redirected_to_list(events): with tornado_redirected_to_list(events):
result = self.client_patch('/json/users/{}'.format(iago.id), req) result = self.client_patch(f'/json/users/{iago.id}', req)
self.assert_json_success(result) self.assert_json_success(result)
iago = self.example_user("iago") iago = self.example_user("iago")
@ -565,7 +565,7 @@ class PermissionTest(ZulipTestCase):
req = dict(role=UserProfile.ROLE_REALM_ADMINISTRATOR) req = dict(role=UserProfile.ROLE_REALM_ADMINISTRATOR)
events: List[Mapping[str, Any]] = [] events: List[Mapping[str, Any]] = []
with tornado_redirected_to_list(events): with tornado_redirected_to_list(events):
result = self.client_patch('/json/users/{}'.format(iago.id), req) result = self.client_patch(f'/json/users/{iago.id}', req)
self.assert_json_success(result) self.assert_json_success(result)
iago = self.example_user("iago") iago = self.example_user("iago")
@ -1103,20 +1103,20 @@ class UserProfileTest(ZulipTestCase):
stream = get_stream('Rome', iago.realm) stream = get_stream('Rome', iago.realm)
# Invalid User ID. # Invalid User ID.
result = self.client_get("/json/users/25/subscriptions/{}".format(stream.id)) result = self.client_get(f"/json/users/25/subscriptions/{stream.id}")
self.assert_json_error(result, "No such user") self.assert_json_error(result, "No such user")
# Invalid Stream ID. # Invalid Stream ID.
result = self.client_get("/json/users/{}/subscriptions/25".format(iago.id)) result = self.client_get(f"/json/users/{iago.id}/subscriptions/25")
self.assert_json_error(result, "Invalid stream id") self.assert_json_error(result, "Invalid stream id")
result = ujson.loads(self.client_get("/json/users/{}/subscriptions/{}".format(iago.id, stream.id)).content) result = ujson.loads(self.client_get(f"/json/users/{iago.id}/subscriptions/{stream.id}").content)
self.assertFalse(result['is_subscribed']) self.assertFalse(result['is_subscribed'])
# Subscribe to the stream. # Subscribe to the stream.
self.subscribe(iago, stream.name) self.subscribe(iago, stream.name)
with queries_captured() as queries: with queries_captured() as queries:
result = ujson.loads(self.client_get("/json/users/{}/subscriptions/{}".format(iago.id, stream.id)).content) result = ujson.loads(self.client_get(f"/json/users/{iago.id}/subscriptions/{stream.id}").content)
self.assert_length(queries, 7) self.assert_length(queries, 7)
self.assertTrue(result['is_subscribed']) self.assertTrue(result['is_subscribed'])
@ -1126,7 +1126,7 @@ class UserProfileTest(ZulipTestCase):
self.login('polonius') self.login('polonius')
self.assertTrue(polonius.is_guest) self.assertTrue(polonius.is_guest)
result = self.client_get("/json/users/{}/subscriptions/{}".format(iago.id, stream.id)) result = self.client_get(f"/json/users/{iago.id}/subscriptions/{stream.id}")
self.assert_json_error(result, "Invalid stream id") self.assert_json_error(result, "Invalid stream id")
class ActivateTest(ZulipTestCase): class ActivateTest(ZulipTestCase):
@ -1178,7 +1178,7 @@ class ActivateTest(ZulipTestCase):
result = self.client_delete('/json/users/{}'.format(self.example_user("webhook_bot").id)) result = self.client_delete('/json/users/{}'.format(self.example_user("webhook_bot").id))
self.assert_json_error(result, 'No such user') self.assert_json_error(result, 'No such user')
result = self.client_delete('/json/users/{}'.format(desdemona.id)) result = self.client_delete(f'/json/users/{desdemona.id}')
self.assert_json_success(result) self.assert_json_success(result)
result = self.client_delete(f'/json/users/{iago.id}') result = self.client_delete(f'/json/users/{iago.id}')

View File

@ -71,9 +71,9 @@ class BeanstalkHookTests(WebhookTestCase):
def test_git_more_than_limit(self) -> None: def test_git_more_than_limit(self) -> None:
commits_info = "* add some stuff ([e50508d](http://lfranchi-svn.beanstalkapp.com/work-test/changesets/e50508df))\n" commits_info = "* add some stuff ([e50508d](http://lfranchi-svn.beanstalkapp.com/work-test/changesets/e50508df))\n"
expected_topic = "work-test / master" expected_topic = "work-test / master"
expected_message = """Leo Franchi [pushed](http://lfranchi-svn.beanstalkapp.com/work-test) 50 commits to branch master. expected_message = f"""Leo Franchi [pushed](http://lfranchi-svn.beanstalkapp.com/work-test) 50 commits to branch master.
{}[and {} more commit(s)]""".format((commits_info * COMMITS_LIMIT), 50 - COMMITS_LIMIT) {(commits_info * COMMITS_LIMIT)}[and {50 - COMMITS_LIMIT} more commit(s)]"""
self.api_stream_message(self.test_user, 'git_morethanlimitcommits', expected_topic, expected_message, self.api_stream_message(self.test_user, 'git_morethanlimitcommits', expected_topic, expected_message,
content_type=None) content_type=None)
@ -81,9 +81,9 @@ class BeanstalkHookTests(WebhookTestCase):
self.url = self.build_webhook_url(branches='master,development') self.url = self.build_webhook_url(branches='master,development')
commits_info = "* add some stuff ([e50508d](http://lfranchi-svn.beanstalkapp.com/work-test/changesets/e50508df))\n" commits_info = "* add some stuff ([e50508d](http://lfranchi-svn.beanstalkapp.com/work-test/changesets/e50508df))\n"
expected_topic = "work-test / master" expected_topic = "work-test / master"
expected_message = """Leo Franchi [pushed](http://lfranchi-svn.beanstalkapp.com/work-test) 50 commits to branch master. expected_message = f"""Leo Franchi [pushed](http://lfranchi-svn.beanstalkapp.com/work-test) 50 commits to branch master.
{}[and {} more commit(s)]""".format((commits_info * COMMITS_LIMIT), 50 - COMMITS_LIMIT) {(commits_info * COMMITS_LIMIT)}[and {50 - COMMITS_LIMIT} more commit(s)]"""
self.api_stream_message(self.test_user, 'git_morethanlimitcommits', expected_topic, expected_message, self.api_stream_message(self.test_user, 'git_morethanlimitcommits', expected_topic, expected_message,
content_type=None) content_type=None)