Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
python: Convert more "".format to Python 3.6 f-strings.
Anders Kaseorg57a80856a58a
diff --git a/scripts/lib/sharding.py b/scripts/lib/sharding.pyindex fad230cca06..9ef65639518 100755--- a/scripts/lib/sharding.py+++ b/scripts/lib/sharding.py@@ -15,9 +15,9 @@ from scripts.lib.zulip_tools import get_config_filedef 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.pyindex 320f01fbb40..8428435b6e6 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}' zulipdevsu -c '{python_api_repo_setup}' zulipdevsu -c 'git config --global core.editor nano' zulipdevsu -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 cloudconfdiff --git a/tools/lib/html_branches.py b/tools/lib/html_branches.pyindex 56d73118892..0d6b36fd475 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.pyindex b53bde07ba6..5f1695f3aa1 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.pyindex 090a40187f0..4c2bc589c4c 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 areusing 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 upthe ordering correctly. You may simplyneed 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.pyindex ab58601a13c..c58238214a4 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 couldmean that we have not thought through circulardependencies.- '''.format(table))+ ''')ID_MAP[table][old_id] = new_iddef fix_datetime_fields(data: TableData, table: TableName) -> None:diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.pyindex 8317d4f82c8..a6fd960b22c 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 existsPlease 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 = recipientdiff --git a/zerver/openapi/markdown_extension.py b/zerver/openapi/markdown_extension.pyindex f5f561a7a9a..861e25f9bf6 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.pyindex 67ae4686380..27cd70f6d69 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:continueif 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.pyindex 5739b7f2780..ad2f8ad9563 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 = 7stream_id = 1result = 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.pyindex eff148c035b..6ea3d336269 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) # nocoverageexcept 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(functioif 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)continuediff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.pyindex 9255b1e3ef3..7125f19b2d3 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 = 312if 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.pyindex cf9213d117d..1e07529a897 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.pyindex fe6f56e0220..6ba55f817a2 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)