From 57a80856a58af73372e96f05f65cb3474de3405c Mon Sep 17 00:00:00 2001 From: Anders Kaseorg Date: Fri, 12 Jun 2020 23:57:35 -0700 Subject: [PATCH] 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 --- scripts/lib/sharding.py | 6 +++--- tools/droplets/create.py | 7 ++----- tools/lib/html_branches.py | 6 +++--- tools/lib/template_parser.py | 6 +++--- zerver/lib/export.py | 13 +++++-------- zerver/lib/import_realm.py | 6 +++--- zerver/lib/test_classes.py | 6 +++--- zerver/openapi/markdown_extension.py | 8 ++++---- zerver/openapi/openapi.py | 2 +- zerver/openapi/python_examples.py | 2 +- zerver/tests/test_openapi.py | 12 ++++++------ zerver/tests/test_signup.py | 8 ++++---- zerver/tests/test_users.py | 20 ++++++++++---------- zerver/webhooks/beanstalk/tests.py | 8 ++++---- 14 files changed, 52 insertions(+), 58 deletions(-) diff --git a/scripts/lib/sharding.py b/scripts/lib/sharding.py index fad230cca0..9ef6563951 100755 --- a/scripts/lib/sharding.py +++ b/scripts/lib/sharding.py @@ -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: - f.write("""if ($host = '{}') {{ - set $tornado_server http://tornado{}; -}}\n""".format(host, port)) + f.write(f"""if ($host = '{host}') {{ + set $tornado_server http://tornado{port}; +}}\n""") # Basic system to do Tornado sharding. Writes two output .tmp files that need # to be renamed to the following files to finalize the changes: diff --git a/tools/droplets/create.py b/tools/droplets/create.py index 320f01fbb4..8428435b6e 100644 --- a/tools/droplets/create.py +++ b/tools/droplets/create.py @@ -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") python_api_repo_setup = setup_repo.format(username, "python-zulip-api") - cloudconf = """\ + cloudconf = f"""\ #!/bin/bash {setup_zulipdev_ssh_keys} @@ -130,10 +130,7 @@ su -c '{server_repo_setup}' zulipdev su -c '{python_api_repo_setup}' zulipdev su -c 'git config --global core.editor nano' 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.") return cloudconf diff --git a/tools/lib/html_branches.py b/tools/lib/html_branches.py index 56d7311889..0d6b36fd47 100644 --- a/tools/lib/html_branches.py +++ b/tools/lib/html_branches.py @@ -181,9 +181,9 @@ def build_id_dict(templates: List[str]) -> (Dict[str, List[str]]): try: list_tags = tokenize(text) except FormattedException as e: - raise Exception(''' - fn: {} - {}'''.format(fn, e)) + raise Exception(f''' + fn: {fn} + {e}''') for tag in list_tags: info = get_tag_info(tag) diff --git a/tools/lib/template_parser.py b/tools/lib/template_parser.py index b53bde07ba..5f1695f3aa 100644 --- a/tools/lib/template_parser.py +++ b/tools/lib/template_parser.py @@ -213,9 +213,9 @@ def validate(fn: Optional[str] = None, text: Optional[str] = None, check_indent: try: tokens = tokenize(text) except FormattedException as e: - raise TemplateParserException(''' - fn: {} - {}'''.format(fn, e)) + raise TemplateParserException(f''' + fn: {fn} + {e}''') class State: def __init__(self, func: Callable[[Token], None]) -> None: diff --git a/zerver/lib/export.py b/zerver/lib/export.py index 090a40187f..4c2bc589c4 100644 --- a/zerver/lib/export.py +++ b/zerver/lib/export.py @@ -447,17 +447,14 @@ class Config: You must specify a virtual_parent if you are using id_source.''') if self.id_source[0] != self.virtual_parent.table: - raise AssertionError(''' - Configuration error. To populate {}, you - want data from {}, but that differs from - the table name of your virtual parent ({}), + raise AssertionError(f''' + Configuration error. To populate {self.table}, you + want data from {self.id_source[0]}, but that differs from + the table name of your virtual parent ({self.virtual_parent.table}), which suggests you many not have set up the ordering correctly. You may simply need to assign a virtual_parent, or there - may be deeper issues going on.'''.format( - self.table, - self.id_source[0], - self.virtual_parent.table)) + may be deeper issues going on.''') def export_from_config(response: TableData, config: Config, seed_object: Optional[Any]=None, diff --git a/zerver/lib/import_realm.py b/zerver/lib/import_realm.py index ab58601a13..c58238214a 100644 --- a/zerver/lib/import_realm.py +++ b/zerver/lib/import_realm.py @@ -127,11 +127,11 @@ path_maps: Dict[str, Dict[str, str]] = { def update_id_map(table: TableName, old_id: int, new_id: int) -> None: if table not in ID_MAP: - raise Exception(''' - Table {} is not initialized in ID_MAP, which could + raise Exception(f''' + Table {table} is not initialized in ID_MAP, which could mean that we have not thought through circular dependencies. - '''.format(table)) + ''') ID_MAP[table][old_id] = new_id def fix_datetime_fields(data: TableData, table: TableName) -> None: diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.py index 8317d4f82c..a6fd960b22 100644 --- a/zerver/lib/test_classes.py +++ b/zerver/lib/test_classes.py @@ -684,11 +684,11 @@ class ZulipTestCase(TestCase): history_public_to_subscribers=history_public_to_subscribers, ) except IntegrityError: # nocoverage -- this is for bugs in the tests - raise Exception(''' - {} already exists + raise Exception(f''' + {stream_name} already exists 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) stream.recipient = recipient diff --git a/zerver/openapi/markdown_extension.py b/zerver/openapi/markdown_extension.py index f5f561a7a9..861e25f9bf 100644 --- a/zerver/openapi/markdown_extension.py +++ b/zerver/openapi/markdown_extension.py @@ -197,10 +197,10 @@ def get_openapi_param_example_value_as_string(endpoint: str, method: str, param: if param_type in ["object", "array"]: example_value = param.get("example", None) if not example_value: - msg = """All array and object type request parameters must have -concrete examples. The openAPI documentation for {}/{} is missing an example -value for the {} parameter. Without this we cannot automatically generate a -cURL example.""".format(endpoint, method, param_name) + msg = f"""All array and object type request parameters must have +concrete examples. The openAPI documentation for {endpoint}/{method} is missing an example +value for the {param_name} parameter. Without this we cannot automatically generate a +cURL example.""" raise ValueError(msg) ordered_ex_val_str = json.dumps(example_value, sort_keys=True) if curl_argument: diff --git a/zerver/openapi/openapi.py b/zerver/openapi/openapi.py index 67ae468638..27cd70f6d6 100644 --- a/zerver/openapi/openapi.py +++ b/zerver/openapi/openapi.py @@ -207,7 +207,7 @@ def validate_object(content: Dict[str, Any], schema: Dict[str, Any]) -> None: if req_key in exclusion_list: continue 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: """Transform an OpenAPI-like type to a Python one. diff --git a/zerver/openapi/python_examples.py b/zerver/openapi/python_examples.py index 5739b7f278..ad2f8ad956 100644 --- a/zerver/openapi/python_examples.py +++ b/zerver/openapi/python_examples.py @@ -258,7 +258,7 @@ def get_subscription_status(client: Client) -> None: user_id = 7 stream_id = 1 result = client.call_endpoint( - url='/users/{}/subscriptions/{}'.format(user_id, stream_id), + url=f'/users/{user_id}/subscriptions/{stream_id}', method='GET', ) # {code_example|end} diff --git a/zerver/tests/test_openapi.py b/zerver/tests/test_openapi.py index eff148c035..6ea3d33626 100644 --- a/zerver/tests/test_openapi.py +++ b/zerver/tests/test_openapi.py @@ -336,10 +336,10 @@ class OpenAPIArgumentsTest(ZulipTestCase): try: get_openapi_parameters(url_pattern, method) if not msg: # nocoverage - msg = """ + msg = f""" We found some OpenAPI documentation for {method} {url_pattern}, so maybe we shouldn't mark it as intentionally undocumented in the urls. -""".format(method=method, url_pattern=url_pattern) +""" raise AssertionError(msg) # nocoverage except KeyError: 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 (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 -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 += "{:<10s}{:^30s}{:>10s}\n".format("Parameter", "OpenAPI 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: # HACK: After all pending_endpoints have been resolved, we should remove # this segment and the "msg" part of the `ensure_no_...` method. - msg = """ + msg = f""" We found some OpenAPI documentation for {method} {url_pattern}, 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, method, msg) continue diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.py index 9255b1e3ef..7125f19b2d 100644 --- a/zerver/tests/test_signup.py +++ b/zerver/tests/test_signup.py @@ -880,12 +880,12 @@ class InviteUserTest(InviteUserBase): actual_count = len(queries) expected_count = 312 if abs(actual_count - expected_count) > 1: - raise AssertionError(''' + raise AssertionError(f''' Unexpected number of queries: - expected query count: {} - actual: {} - '''.format(expected_count, actual_count)) + expected query count: {expected_count} + actual: {actual_count} + ''') self.assert_json_success(result) diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py index cf9213d117..1e07529a89 100644 --- a/zerver/tests/test_users.py +++ b/zerver/tests/test_users.py @@ -494,7 +494,7 @@ class PermissionTest(ZulipTestCase): req = dict(role=UserProfile.ROLE_GUEST) events: List[Mapping[str, Any]] = [] 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) iago = self.example_user("iago") @@ -518,7 +518,7 @@ class PermissionTest(ZulipTestCase): req = dict(role=UserProfile.ROLE_REALM_OWNER) events: List[Mapping[str, Any]] = [] 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) polonius = self.example_user("polonius") @@ -542,7 +542,7 @@ class PermissionTest(ZulipTestCase): req = dict(role=UserProfile.ROLE_REALM_OWNER) events: List[Mapping[str, Any]] = [] 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) iago = self.example_user("iago") @@ -565,7 +565,7 @@ class PermissionTest(ZulipTestCase): req = dict(role=UserProfile.ROLE_REALM_ADMINISTRATOR) events: List[Mapping[str, Any]] = [] 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) iago = self.example_user("iago") @@ -1103,20 +1103,20 @@ class UserProfileTest(ZulipTestCase): stream = get_stream('Rome', iago.realm) # 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") # 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") - 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']) # Subscribe to the stream. self.subscribe(iago, stream.name) 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.assertTrue(result['is_subscribed']) @@ -1126,7 +1126,7 @@ class UserProfileTest(ZulipTestCase): self.login('polonius') 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") class ActivateTest(ZulipTestCase): @@ -1178,7 +1178,7 @@ class ActivateTest(ZulipTestCase): result = self.client_delete('/json/users/{}'.format(self.example_user("webhook_bot").id)) 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) result = self.client_delete(f'/json/users/{iago.id}') diff --git a/zerver/webhooks/beanstalk/tests.py b/zerver/webhooks/beanstalk/tests.py index fe6f56e022..6ba55f817a 100644 --- a/zerver/webhooks/beanstalk/tests.py +++ b/zerver/webhooks/beanstalk/tests.py @@ -71,9 +71,9 @@ class BeanstalkHookTests(WebhookTestCase): def test_git_more_than_limit(self) -> None: commits_info = "* add some stuff ([e50508d](http://lfranchi-svn.beanstalkapp.com/work-test/changesets/e50508df))\n" 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, content_type=None) @@ -81,9 +81,9 @@ class BeanstalkHookTests(WebhookTestCase): 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" 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, content_type=None)