Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

python: Mark regexes as raw strings.

Anders Kaseorg96fbe060a676
diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.py
index 4f695eb7f65..63b1d20a8bb 100644
--- a/corporate/tests/test_stripe.py
+++ b/corporate/tests/test_stripe.py
@@ -245,19 +245,19 @@ def normalize_fixture_data(
]
# We'll replace cus_D7OT2jf5YAtZQ2 with something like cus_NORMALIZED0001
pattern_translations = {
- f"{prefix}_[A-Za-z0-9]{{{length}}}": f"{prefix}_NORMALIZED%0{length - 10}d"
+ rf"{prefix}_[A-Za-z0-9]{{{length}}}": f"{prefix}_NORMALIZED%0{length - 10}d"
for prefix, length in id_lengths
}
# We'll replace "invoice_prefix": "A35BC4Q" with something like "invoice_prefix": "NORMA01"
pattern_translations.update(
{
- '"invoice_prefix": "([A-Za-z0-9]{7,8})"': "NORMA%02d",
- '"fingerprint": "([A-Za-z0-9]{16})"': "NORMALIZED%06d",
- '"number": "([A-Za-z0-9]{7,8}-[A-Za-z0-9]{4})"': "NORMALI-%04d",
- '"address": "([A-Za-z0-9]{9}-test_[A-Za-z0-9]{12})"': "000000000-test_NORMALIZED%02d",
+ r'"invoice_prefix": "([A-Za-z0-9]{7,8})"': "NORMA%02d",
+ r'"fingerprint": "([A-Za-z0-9]{16})"': "NORMALIZED%06d",
+ r'"number": "([A-Za-z0-9]{7,8}-[A-Za-z0-9]{4})"': "NORMALI-%04d",
+ r'"address": "([A-Za-z0-9]{9}-test_[A-Za-z0-9]{12})"': "000000000-test_NORMALIZED%02d",
# Don't use (..) notation, since the matched strings may be small integers that will also match
# elsewhere in the file
- '"realm_id": "[0-9]+"': '"realm_id": "%d"',
+ r'"realm_id": "[0-9]+"': '"realm_id": "%d"',
r'"account_name": "[\w\s]+"': '"account_name": "NORMALIZED-%d"',
}
)
@@ -265,7 +265,7 @@ def normalize_fixture_data(
# why we're doing something a bit more complicated
for i, timestamp_field in enumerate(tested_timestamp_fields):
# Don't use (..) notation, since the matched timestamp can easily appear in other fields
- pattern_translations[f'"{timestamp_field}": 1[5-9][0-9]{{8}}(?![0-9-])'] = (
+ pattern_translations[rf'"{timestamp_field}": 1[5-9][0-9]{{8}}(?![0-9-])'] = (
f'"{timestamp_field}": 1{i + 1:02}%07d'
)
diff --git a/corporate/views/realm_activity.py b/corporate/views/realm_activity.py
index 7a03aa54990..1cfcd9120b9 100644
--- a/corporate/views/realm_activity.py
+++ b/corporate/views/realm_activity.py
@@ -79,7 +79,7 @@ def get_user_activity_summary(records: Collection[UserActivity]) -> UserActivity
else:
heard_from = max(visit, heard_from)
- if ("send_message" in query) or re.search("/api/.*/external/.*", query):
+ if ("send_message" in query) or re.search(r"/api/.*/external/.*", query):
messages += record.count
if last_sent is None:
last_sent = visit
diff --git a/tools/check-capitalization b/tools/check-capitalization
index 4fe8cd8bb10..789759ae669 100755
--- a/tools/check-capitalization
+++ b/tools/check-capitalization
@@ -17,7 +17,7 @@ sanity_check.check_venv(__file__)
from scripts.lib.zulip_tools import ENDC, FAIL, WARNING
from tools.lib.capitalization import check_capitalization
-DJANGO_PO_REGEX = re.compile('msgid "(.*?)"')
+DJANGO_PO_REGEX = re.compile(r'msgid "(.*?)"')
if __name__ == "__main__":
parser = argparse.ArgumentParser()
diff --git a/tools/lib/capitalization.py b/tools/lib/capitalization.py
index 351420cb4e6..03917d1e757 100644
--- a/tools/lib/capitalization.py
+++ b/tools/lib/capitalization.py
@@ -166,10 +166,10 @@ IGNORED_PHRASES.sort(key=len, reverse=True)
# text using BeautifulSoup and then removes extra whitespaces from
# it. This step enables us to add HTML in our regexes directly.
COMPILED_IGNORED_PHRASES = [
- re.compile(" ".join(BeautifulSoup(regex, "lxml").text.split())) for regex in IGNORED_PHRASES
+ re.compile(r" ".join(BeautifulSoup(regex, "lxml").text.split())) for regex in IGNORED_PHRASES
]
-SPLIT_BOUNDARY = "?.!" # Used to split string into sentences.
+SPLIT_BOUNDARY = r"?.!" # Used to split string into sentences.
SPLIT_BOUNDARY_REGEX = re.compile(rf"[{SPLIT_BOUNDARY}]")
# Regexes which check capitalization in sentences.
diff --git a/tools/setup/emoji/generate_emoji_names b/tools/setup/emoji/generate_emoji_names
index 045be36fcc0..2b0ea235dbe 100755
--- a/tools/setup/emoji/generate_emoji_names
+++ b/tools/setup/emoji/generate_emoji_names
@@ -90,7 +90,7 @@ def cleanup_name(name: str) -> str:
}
for before, after in replacements.items():
name = name.replace(before, after)
- name = re.sub("_{2,}", "_", name)
+ name = re.sub(r"_{2,}", "_", name)
return name.lower()
diff --git a/zerver/data_import/mattermost.py b/zerver/data_import/mattermost.py
index 2d08216cf13..2740c297177 100644
--- a/zerver/data_import/mattermost.py
+++ b/zerver/data_import/mattermost.py
@@ -317,7 +317,7 @@ def get_mentioned_user_ids(raw_message: Dict[str, Any], user_id_mapper: IdMapper
content = raw_message["content"]
# usernames can be of the form user.name, user_name, username., username_, user.name_ etc
- matches = re.findall("(?<=^|(?<=[^a-zA-Z0-9-_.]))@(([A-Za-z0-9]+[_.]?)+)", content)
+ matches = re.findall(r"(?<=^|(?<=[^a-zA-Z0-9-_.]))@(([A-Za-z0-9]+[_.]?)+)", content)
for match in matches:
possible_username = match[0]
@@ -574,8 +574,8 @@ def process_posts(
content = post_dict["message"]
if masking_content:
- content = re.sub("[a-z]", "x", content)
- content = re.sub("[A-Z]", "X", content)
+ content = re.sub(r"[a-z]", "x", content)
+ content = re.sub(r"[A-Z]", "X", content)
if "reactions" in post_dict:
reactions = post_dict["reactions"] or []
diff --git a/zerver/forms.py b/zerver/forms.py
index 9f38874ff09..010bf360e26 100644
--- a/zerver/forms.py
+++ b/zerver/forms.py
@@ -101,7 +101,7 @@ def check_subdomain_available(subdomain: str, allow_reserved_subdomain: bool = F
raise ValidationError(error_strings["unavailable"])
if subdomain[0] == "-" or subdomain[-1] == "-":
raise ValidationError(error_strings["extremal dash"])
- if not re.match("^[a-z0-9-]*$", subdomain):
+ if not re.match(r"^[a-z0-9-]*$", subdomain):
raise ValidationError(error_strings["bad character"])
if len(subdomain) < 3:
raise ValidationError(error_strings["too short"])
diff --git a/zerver/lib/domains.py b/zerver/lib/domains.py
index 95b146e3aaa..6ec4cd57a9c 100644
--- a/zerver/lib/domains.py
+++ b/zerver/lib/domains.py
@@ -19,5 +19,5 @@ def validate_domain(domain: Optional[str]) -> None:
raise ValidationError(_("Consecutive '.' are not allowed."))
if subdomain[0] == "-" or subdomain[-1] == "-":
raise ValidationError(_("Subdomains cannot start or end with a '-'."))
- if not re.match("^[a-z0-9-]*$", subdomain):
+ if not re.match(r"^[a-z0-9-]*$", subdomain):
raise ValidationError(_("Domain can only have letters, numbers, '.' and '-'s."))
diff --git a/zerver/lib/email_mirror.py b/zerver/lib/email_mirror.py
index 999c6ea4e93..34b2a162f86 100644
--- a/zerver/lib/email_mirror.py
+++ b/zerver/lib/email_mirror.py
@@ -370,7 +370,7 @@ def find_emailgateway_recipient(message: EmailMessage) -> str:
]
pattern_parts = [re.escape(part) for part in settings.EMAIL_GATEWAY_PATTERN.split("%s")]
- match_email_re = re.compile(".*?".join(pattern_parts))
+ match_email_re = re.compile(r".*?".join(pattern_parts))
for header_name in recipient_headers:
for header_value in message.get_all(header_name, []):
diff --git a/zerver/lib/email_mirror_helpers.py b/zerver/lib/email_mirror_helpers.py
index 44558783771..6ee9a897bdf 100644
--- a/zerver/lib/email_mirror_helpers.py
+++ b/zerver/lib/email_mirror_helpers.py
@@ -36,7 +36,7 @@ def get_email_gateway_message_string_from_address(address: str) -> str:
if settings.EMAIL_GATEWAY_EXTRA_PATTERN_HACK:
# Accept mails delivered to any Zulip server
pattern_parts[-1] = settings.EMAIL_GATEWAY_EXTRA_PATTERN_HACK
- match_email_re = re.compile("(.*?)".join(pattern_parts))
+ match_email_re = re.compile(r"(.*?)".join(pattern_parts))
match = match_email_re.match(address)
if not match:
diff --git a/zerver/lib/email_notifications.py b/zerver/lib/email_notifications.py
index 52f1df0852d..b3ea4f584ad 100644
--- a/zerver/lib/email_notifications.py
+++ b/zerver/lib/email_notifications.py
@@ -55,7 +55,7 @@ def relative_to_full_url(fragment: lxml.html.HtmlElement, base_url: str) -> None
# is not possible with `make_links_absolute()`.
for link_info in fragment.iterlinks():
elem, attrib, link, pos = link_info
- match = re.match("/?#narrow/", link)
+ match = re.match(r"/?#narrow/", link)
if match is not None:
link = re.sub(r"^/?#narrow/", base_url + "/#narrow/", link)
elem.set(attrib, link)
@@ -937,4 +937,4 @@ def convert_html_to_markdown(html: str) -> str:
# ugly. Run a regex over the resulting description, turning links of the
# form `![](http://foo.com/image.png?12345)` into
# `[image.png](http://foo.com/image.png)`.
- return re.sub("!\\[\\]\\((\\S*)/(\\S*)\\?(\\S*)\\)", "[\\2](\\1/\\2)", markdown)
+ return re.sub(r"!\[\]\((\S*)/(\S*)\?(\S*)\)", "[\\2](\\1/\\2)", markdown)
diff --git a/zerver/lib/emoji.py b/zerver/lib/emoji.py
index b14c564b59d..8ad9f2b2c1a 100644
--- a/zerver/lib/emoji.py
+++ b/zerver/lib/emoji.py
@@ -33,11 +33,11 @@ EMOTICON_CONVERSIONS = emoji_codes["emoticon_conversions"]
possible_emoticons = EMOTICON_CONVERSIONS.keys()
possible_emoticon_regexes = (re.escape(emoticon) for emoticon in possible_emoticons)
-terminal_symbols = ",.;?!()\\[\\] \"'\\n\\t" # from composebox_typeahead.js
+terminal_symbols = r",.;?!()\[\] \"'\n\t" # from composebox_typeahead.js
EMOTICON_RE = (
- f"(?<![^{terminal_symbols}])(?P<emoticon>("
- + ")|(".join(possible_emoticon_regexes)
- + f"))(?![^{terminal_symbols}])"
+ rf"(?<![^{terminal_symbols}])(?P<emoticon>("
+ + r")|(".join(possible_emoticon_regexes)
+ + rf"))(?![^{terminal_symbols}])"
)
diff --git a/zerver/lib/markdown/__init__.py b/zerver/lib/markdown/__init__.py
index 451bef9d29d..4941c8376a5 100644
--- a/zerver/lib/markdown/__init__.py
+++ b/zerver/lib/markdown/__init__.py
@@ -151,7 +151,7 @@ EMOJI_REGEX = r"(?P<syntax>:[\w\-\+]+:)"
def verbose_compile(pattern: str) -> Pattern[str]:
return re.compile(
- f"^(.*?){pattern}(.*?)$",
+ rf"^(.*?){pattern}(.*?)$",
re.DOTALL | re.VERBOSE,
)
@@ -207,7 +207,7 @@ def get_web_link_regex() -> Pattern[str]:
# extra costs. It's roughly 75ms to run this code, so
# caching the value is super important here.
- tlds = "|".join(list_of_tlds())
+ tlds = r"|".join(list_of_tlds())
# A link starts at a word boundary, and ends at space, punctuation, or end-of-input.
#
@@ -2553,7 +2553,7 @@ def maybe_update_markdown_engines(linkifiers_key: int, email_gateway: bool) -> N
#
# We also use repr() to improve reproducibility, and to escape terminal control
# codes, which can do surprisingly nasty things.
-_privacy_re = re.compile("\\w")
+_privacy_re = re.compile(r"\w")
def privacy_clean_markdown(content: str) -> str:
diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.py
index 25d7f867e09..c2d8f093549 100644
--- a/zerver/lib/test_classes.py
+++ b/zerver/lib/test_classes.py
@@ -287,7 +287,9 @@ Output:
django_client to fool the regex.
"""
DEFAULT_SUBDOMAIN = "zulip"
- TOKENIZED_NOREPLY_REGEX = settings.TOKENIZED_NOREPLY_EMAIL_ADDRESS.format(token="[a-z0-9_]{24}")
+ TOKENIZED_NOREPLY_REGEX = settings.TOKENIZED_NOREPLY_EMAIL_ADDRESS.format(
+ token=r"[a-z0-9_]{24}"
+ )
def set_http_headers(self, extra: Dict[str, str], skip_user_agent: bool = False) -> None:
if "subdomain" in extra:
@@ -2416,7 +2418,7 @@ class BouncerTestCase(ZulipTestCase):
def add_mock_response(self) -> None:
# Match any endpoint with the PUSH_NOTIFICATION_BOUNCER_URL.
assert settings.PUSH_NOTIFICATION_BOUNCER_URL is not None
- COMPILED_URL = re.compile(settings.PUSH_NOTIFICATION_BOUNCER_URL + ".*")
+ COMPILED_URL = re.compile(settings.PUSH_NOTIFICATION_BOUNCER_URL + r".*")
responses.add_callback(responses.POST, COMPILED_URL, callback=self.request_callback)
responses.add_callback(responses.GET, COMPILED_URL, callback=self.request_callback)
diff --git a/zerver/lib/test_helpers.py b/zerver/lib/test_helpers.py
index ef46e0acbe7..69b8fdf438d 100644
--- a/zerver/lib/test_helpers.py
+++ b/zerver/lib/test_helpers.py
@@ -261,7 +261,7 @@ def make_client(name: str) -> Client:
def find_key_by_email(address: str) -> Optional[str]:
from django.core.mail import outbox
- key_regex = re.compile("accounts/do_confirm/([a-z0-9]{24})>")
+ key_regex = re.compile(r"accounts/do_confirm/([a-z0-9]{24})>")
for message in reversed(outbox):
if address in message.to:
match = key_regex.search(str(message.body))
diff --git a/zerver/lib/user_agent.py b/zerver/lib/user_agent.py
index 961d77ce052..b80dc15dfcd 100644
--- a/zerver/lib/user_agent.py
+++ b/zerver/lib/user_agent.py
@@ -5,7 +5,7 @@ from typing import Dict
# zerver/tests/test_decorators.py
# And extend zerver/tests/fixtures/user_agents_unique with any new test cases
pattern = re.compile(
- """^ (?P<name> [^/ ]* [^0-9/(]* )
+ r"""^ (?P<name> [^/ ]* [^0-9/(]* )
(/ (?P<version> [^/ ]* ))?
([ /] .*)?
$""",
diff --git a/zerver/management/commands/makemessages.py b/zerver/management/commands/makemessages.py
index ae20d768cda..1a59dc45fa5 100644
--- a/zerver/management/commands/makemessages.py
+++ b/zerver/management/commands/makemessages.py
@@ -47,10 +47,10 @@ from django.utils.translation import template
from typing_extensions import override
strip_whitespace_right = re.compile(
- f"({BLOCK_TAG_START}-?\\s*(trans|pluralize).*?-{BLOCK_TAG_END})\\s+"
+ rf"({BLOCK_TAG_START}-?\s*(trans|pluralize).*?-{BLOCK_TAG_END})\s+"
)
strip_whitespace_left = re.compile(
- f"\\s+({BLOCK_TAG_START}-\\s*(endtrans|pluralize).*?-?{BLOCK_TAG_END})"
+ rf"\s+({BLOCK_TAG_START}-\s*(endtrans|pluralize).*?-?{BLOCK_TAG_END})"
)
regexes = [
@@ -67,7 +67,7 @@ tags = [
frontend_compiled_regexes = [re.compile(regex) for regex in regexes]
multiline_js_comment = re.compile(r"/\*.*?\*/", re.DOTALL)
-singleline_js_comment = re.compile("//.*?\n")
+singleline_js_comment = re.compile(r"//.*?\n")
def strip_whitespaces(src: str) -> str:
@@ -135,13 +135,13 @@ class Command(makemessages.Command):
# Extend the regular expressions that are used to detect
# translation blocks with an "OR jinja-syntax" clause.
template.endblock_re = re.compile(
- template.endblock_re.pattern + "|" + r"""^-?\s*endtrans\s*-?$"""
+ template.endblock_re.pattern + r"|" + r"""^-?\s*endtrans\s*-?$"""
)
template.block_re = re.compile(
- template.block_re.pattern + "|" + r"""^-?\s*trans(?:\s+(?!'|")(?=.*?=.*?)|\s*-?$)"""
+ template.block_re.pattern + r"|" + r"""^-?\s*trans(?:\s+(?!'|")(?=.*?=.*?)|\s*-?$)"""
)
template.plural_re = re.compile(
- template.plural_re.pattern + "|" + r"""^-?\s*pluralize(?:\s+.+|-?$)"""
+ template.plural_re.pattern + r"|" + r"""^-?\s*pluralize(?:\s+.+|-?$)"""
)
template.constant_re = re.compile(r"""_\(((?:".*?")|(?:'.*?')).*\)""")
diff --git a/zerver/migrations/0041_create_attachments_for_old_messages.py b/zerver/migrations/0041_create_attachments_for_old_messages.py
index 18aa8da1c19..6b8d593a193 100644
--- a/zerver/migrations/0041_create_attachments_for_old_messages.py
+++ b/zerver/migrations/0041_create_attachments_for_old_messages.py
@@ -11,7 +11,7 @@ attachment_url_re = re.compile(r"[/\-]user[\-_]uploads[/\.-].*?(?=[ )]|\Z)")
def attachment_url_to_path_id(attachment_url: str) -> str:
path_id_raw = re.sub(r"[/\-]user[\-_]uploads[/\.-]", "", attachment_url)
# Remove any extra '.' after file extension. These are probably added by the user
- return re.sub("[.]+$", "", path_id_raw, flags=re.M)
+ return re.sub(r"[.]+$", "", path_id_raw, flags=re.M)
def check_and_create_attachments(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.py
index 9571b7e4216..574ef8454d9 100644
--- a/zerver/tests/test_auth_backends.py
+++ b/zerver/tests/test_auth_backends.py
@@ -4654,7 +4654,7 @@ class GoogleAuthBackendTest(SocialAuthBase):
self.assert_in_response('action="http://zulip.testserver/accounts/do_confirm/', result)
url = re.findall(
- 'action="(http://zulip.testserver/accounts/do_confirm[^"]*)"',
+ r'action="(http://zulip.testserver/accounts/do_confirm[^"]*)"',
result.content.decode(),
)[0]
confirmation = Confirmation.objects.all().first()
diff --git a/zerver/tests/test_decorators.py b/zerver/tests/test_decorators.py
index 4cd3a5150ec..5cd7625e676 100644
--- a/zerver/tests/test_decorators.py
+++ b/zerver/tests/test_decorators.py
@@ -1426,7 +1426,7 @@ class TestUserAgentParsing(ZulipTestCase):
with open(user_agents_path) as f:
for line in f:
line = line.strip()
- match = re.match('^(?P<count>[0-9]+) "(?P<user_agent>.*)"$', line)
+ match = re.match(r'^(?P<count>[0-9]+) "(?P<user_agent>.*)"$', line)
assert match is not None
groupdict = match.groupdict()
count = groupdict["count"]
diff --git a/zerver/tests/test_delete_unclaimed_attachments.py b/zerver/tests/test_delete_unclaimed_attachments.py
index 807db51d365..cbb3c5cadc5 100644
--- a/zerver/tests/test_delete_unclaimed_attachments.py
+++ b/zerver/tests/test_delete_unclaimed_attachments.py
@@ -33,7 +33,7 @@ class UnclaimedAttachmentTest(UploadSerializeMixin, ZulipTestCase):
response = self.assert_json_success(
self.client_post("/json/user_uploads", {"file": file_obj})
)
- path_id = re.sub("/user_uploads/", "", response["uri"])
+ path_id = re.sub(r"/user_uploads/", "", response["uri"])
return Attachment.objects.get(path_id=path_id)
def assert_exists(
diff --git a/zerver/tests/test_realm.py b/zerver/tests/test_realm.py
index 9300a70689f..fa661073236 100644
--- a/zerver/tests/test_realm.py
+++ b/zerver/tests/test_realm.py
@@ -1831,7 +1831,7 @@ class ScrubRealmTest(ZulipTestCase):
)
base = "/user_uploads/"
self.assertEqual(base, url[: len(base)])
- path_id = re.sub("/user_uploads/", "", url)
+ path_id = re.sub(r"/user_uploads/", "", url)
self.assertTrue(os.path.isfile(os.path.join(settings.LOCAL_FILES_DIR, path_id)))
path_ids.append(path_id)
@@ -1908,7 +1908,7 @@ class ScrubRealmTest(ZulipTestCase):
)
base = "/user_uploads/"
self.assertEqual(base, url[: len(base)])
- file_path = os.path.join(settings.LOCAL_FILES_DIR, re.sub("/user_uploads/", "", url))
+ file_path = os.path.join(settings.LOCAL_FILES_DIR, re.sub(r"/user_uploads/", "", url))
self.assertTrue(os.path.isfile(file_path))
file_paths.append(file_path)
diff --git a/zerver/tests/test_scheduled_messages.py b/zerver/tests/test_scheduled_messages.py
index 364af0601c4..9166445517f 100644
--- a/zerver/tests/test_scheduled_messages.py
+++ b/zerver/tests/test_scheduled_messages.py
@@ -656,13 +656,13 @@ class ScheduledMessageTest(ZulipTestCase):
attachment_file1 = StringIO("zulip!")
attachment_file1.name = "dummy_1.txt"
result = self.client_post("/json/user_uploads", {"file": attachment_file1})
- path_id1 = re.sub("/user_uploads/", "", result.json()["uri"])
+ path_id1 = re.sub(r"/user_uploads/", "", result.json()["uri"])
attachment_object1 = Attachment.objects.get(path_id=path_id1)
attachment_file2 = StringIO("zulip!")
attachment_file2.name = "dummy_1.txt"
result = self.client_post("/json/user_uploads", {"file": attachment_file2})
- path_id2 = re.sub("/user_uploads/", "", result.json()["uri"])
+ path_id2 = re.sub(r"/user_uploads/", "", result.json()["uri"])
attachment_object2 = Attachment.objects.get(path_id=path_id2)
content = f"Test [zulip.txt](http://{hamlet.realm.host}/user_uploads/{path_id1})"
diff --git a/zerver/tests/test_upload.py b/zerver/tests/test_upload.py
index 23781df1755..fb7b49ad6ca 100644
--- a/zerver/tests/test_upload.py
+++ b/zerver/tests/test_upload.py
@@ -423,7 +423,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
d1.name = "dummy_1.txt"
result = self.client_post("/json/user_uploads", {"file": d1})
response_dict = self.assert_json_success(result)
- d1_path_id = re.sub("/user_uploads/", "", response_dict["uri"])
+ d1_path_id = re.sub(r"/user_uploads/", "", response_dict["uri"])
self.subscribe(self.example_user("hamlet"), "Denmark")
host = self.example_user("hamlet").realm.host
@@ -442,7 +442,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
d1.name = "dummy_1.txt"
result = self.client_post("/json/user_uploads", {"file": d1})
response_dict = self.assert_json_success(result)
- d1_path_id = re.sub("/user_uploads/", "", response_dict["uri"])
+ d1_path_id = re.sub(r"/user_uploads/", "", response_dict["uri"])
host = self.example_user("hamlet").realm.host
self.make_stream("private_stream", invite_only=True)
@@ -502,11 +502,11 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
self.login_user(hamlet)
result = self.client_post("/json/user_uploads", {"file": f1})
response_dict = self.assert_json_success(result)
- f1_path_id = re.sub("/user_uploads/", "", response_dict["uri"])
+ f1_path_id = re.sub(r"/user_uploads/", "", response_dict["uri"])
result = self.client_post("/json/user_uploads", {"file": f2})
response_dict = self.assert_json_success(result)
- f2_path_id = re.sub("/user_uploads/", "", response_dict["uri"])
+ f2_path_id = re.sub(r"/user_uploads/", "", response_dict["uri"])
self.subscribe(hamlet, "test")
body = (
@@ -517,7 +517,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
result = self.client_post("/json/user_uploads", {"file": f3})
response_dict = self.assert_json_success(result)
- f3_path_id = re.sub("/user_uploads/", "", response_dict["uri"])
+ f3_path_id = re.sub(r"/user_uploads/", "", response_dict["uri"])
new_body = (
f"[f3.txt](http://{host}/user_uploads/" + f3_path_id + ") "
@@ -600,7 +600,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
d1.name = "dummy_1.txt"
result = self.client_post("/json/user_uploads", {"file": d1})
response_dict = self.assert_json_success(result)
- d1_path_id = re.sub("/user_uploads/", "", response_dict["uri"])
+ d1_path_id = re.sub(r"/user_uploads/", "", response_dict["uri"])
d1_attachment = Attachment.objects.get(path_id=d1_path_id)
realm = get_realm("zulip")
@@ -660,7 +660,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
fp.name = "zulip.txt"
result = self.client_post("/json/user_uploads", {"file": fp})
url = self.assert_json_success(result)["uri"]
- fp_path_id = re.sub("/user_uploads/", "", url)
+ fp_path_id = re.sub(r"/user_uploads/", "", url)
body = f"First message ...[zulip.txt](http://{host}/user_uploads/" + fp_path_id + ")"
with self.settings(CROSS_REALM_BOT_EMAILS={user_2.email, user_3.email}):
internal_send_private_message(
@@ -706,7 +706,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
fp.name = "zulip.txt"
result = self.client_post("/json/user_uploads", {"file": fp})
url = self.assert_json_success(result)["uri"]
- fp_path_id = re.sub("/user_uploads/", "", url)
+ fp_path_id = re.sub(r"/user_uploads/", "", url)
body = f"First message ...[zulip.txt](http://{realm.host}/user_uploads/" + fp_path_id + ")"
self.send_stream_message(hamlet, stream_name, body, "test")
self.logout()
@@ -758,7 +758,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
fp.name = "zulip.txt"
result = self.client_post("/json/user_uploads", {"file": fp})
url = self.assert_json_success(result)["uri"]
- fp_path_id = re.sub("/user_uploads/", "", url)
+ fp_path_id = re.sub(r"/user_uploads/", "", url)
body = (
f"First message ...[zulip.txt](http://{user.realm.host}/user_uploads/"
+ fp_path_id
@@ -827,7 +827,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
fp.name = "zulip.txt"
result = self.client_post("/json/user_uploads", {"file": fp})
url = self.assert_json_success(result)["uri"]
- fp_path_id = re.sub("/user_uploads/", "", url)
+ fp_path_id = re.sub(r"/user_uploads/", "", url)
for i in range(20):
body = (
f"First message ...[zulip.txt](http://{hamlet.realm.host}/user_uploads/"
@@ -872,7 +872,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
fp.name = "zulip.txt"
result = self.client_post("/json/user_uploads", {"file": fp})
url = self.assert_json_success(result)["uri"]
- fp_path_id = re.sub("/user_uploads/", "", url)
+ fp_path_id = re.sub(r"/user_uploads/", "", url)
body = f"First message ...[zulip.txt](http://{realm.host}/user_uploads/" + fp_path_id + ")"
self.send_stream_message(self.example_user("hamlet"), "test-subscribe", body, "test")
self.logout()
@@ -896,7 +896,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
fp.name = name
result = self.client_post("/json/user_uploads", {"file": fp})
url = self.assert_json_success(result)["uri"]
- fp_path_id = re.sub("/user_uploads/", "", url)
+ fp_path_id = re.sub(r"/user_uploads/", "", url)
fp_path = os.path.split(fp_path_id)[0]
if download:
url = url.replace("/user_uploads/", "/user_uploads/download/")
diff --git a/zerver/tests/test_upload_local.py b/zerver/tests/test_upload_local.py
index 850726a2933..156524ddf54 100644
--- a/zerver/tests/test_upload_local.py
+++ b/zerver/tests/test_upload_local.py
@@ -36,7 +36,7 @@ class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):
base = "/user_uploads/"
self.assertEqual(base, url[: len(base)])
- path_id = re.sub("/user_uploads/", "", url)
+ path_id = re.sub(r"/user_uploads/", "", url)
assert settings.LOCAL_UPLOADS_DIR is not None
assert settings.LOCAL_FILES_DIR is not None
file_path = os.path.join(settings.LOCAL_FILES_DIR, path_id)
@@ -51,7 +51,7 @@ class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):
"dummy.txt", len(b"zulip!"), "text/plain", b"zulip!", user_profile
)
- path_id = re.sub("/user_uploads/", "", url)
+ path_id = re.sub(r"/user_uploads/", "", url)
output = BytesIO()
save_attachment_contents(path_id, output)
self.assertEqual(output.getvalue(), b"zulip!")
@@ -80,7 +80,7 @@ class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):
result = self.client_post("/json/user_uploads", {"file": fp})
response_dict = self.assert_json_success(result)
- path_id = re.sub("/user_uploads/", "", response_dict["uri"])
+ path_id = re.sub(r"/user_uploads/", "", response_dict["uri"])
assert settings.LOCAL_FILES_DIR is not None
file_path = os.path.join(settings.LOCAL_FILES_DIR, path_id)
@@ -101,7 +101,7 @@ class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):
)
base = "/user_uploads/"
self.assertEqual(base, url[: len(base)])
- path_id = re.sub("/user_uploads/", "", url)
+ path_id = re.sub(r"/user_uploads/", "", url)
path_ids.append(path_id)
file_path = os.path.join(settings.LOCAL_FILES_DIR, path_id)
self.assertTrue(os.path.isfile(file_path))
diff --git a/zerver/tests/test_upload_s3.py b/zerver/tests/test_upload_s3.py
index 6e5c4c19931..76e032a0a22 100644
--- a/zerver/tests/test_upload_s3.py
+++ b/zerver/tests/test_upload_s3.py
@@ -53,7 +53,7 @@ class S3Test(ZulipTestCase):
base = "/user_uploads/"
self.assertEqual(base, url[: len(base)])
- path_id = re.sub("/user_uploads/", "", url)
+ path_id = re.sub(r"/user_uploads/", "", url)
content = bucket.Object(path_id).get()["Body"].read()
self.assertEqual(b"zulip!", content)
@@ -72,7 +72,7 @@ class S3Test(ZulipTestCase):
"dummy.txt", len(b"zulip!"), "text/plain", b"zulip!", user_profile
)
- path_id = re.sub("/user_uploads/", "", url)
+ path_id = re.sub(r"/user_uploads/", "", url)
output = BytesIO()
save_attachment_contents(path_id, output)
self.assertEqual(output.getvalue(), b"zulip!")
@@ -103,7 +103,7 @@ class S3Test(ZulipTestCase):
user_profile = self.example_user("hamlet")
url = upload_message_attachment("dummy.txt", len(b"zulip!"), None, b"zulip!", user_profile)
- path_id = re.sub("/user_uploads/", "", url)
+ path_id = re.sub(r"/user_uploads/", "", url)
self.assertEqual(b"zulip!", bucket.Object(path_id).get()["Body"].read())
uploaded_file = Attachment.objects.get(owner=user_profile, path_id=path_id)
self.assert_length(b"zulip!", uploaded_file.size)
@@ -117,7 +117,7 @@ class S3Test(ZulipTestCase):
"dummy.txt", len(b"zulip!"), "text/plain", b"zulip!", user_profile
)
- path_id = re.sub("/user_uploads/", "", url)
+ path_id = re.sub(r"/user_uploads/", "", url)
self.assertIsNotNone(bucket.Object(path_id).get())
self.assertTrue(delete_message_attachment(path_id))
with self.assertRaises(botocore.exceptions.ClientError):
@@ -133,7 +133,7 @@ class S3Test(ZulipTestCase):
url = upload_message_attachment(
"dummy.txt", len(b"zulip!"), "text/plain", b"zulip!", user_profile
)
- path_id = re.sub("/user_uploads/", "", url)
+ path_id = re.sub(r"/user_uploads/", "", url)
self.assertIsNotNone(bucket.Object(path_id).get())
path_ids.append(path_id)
@@ -168,7 +168,7 @@ class S3Test(ZulipTestCase):
url = upload_message_attachment(
"dummy.txt", len(b"zulip!"), "text/plain", b"zulip!", user_profile
)
- path_ids.append(re.sub("/user_uploads/", "", url))
+ path_ids.append(re.sub(r"/user_uploads/", "", url))
found_paths = [r[0] for r in all_message_attachments()]
self.assertEqual(sorted(found_paths), sorted(path_ids))
diff --git a/zerver/views/documentation.py b/zerver/views/documentation.py
index c0f51e5c3d6..cb699c06a91 100644
--- a/zerver/views/documentation.py
+++ b/zerver/views/documentation.py
@@ -105,7 +105,7 @@ class MarkdownDirectoryView(ApiURLView):
elif "/" in article:
article = "missing"
http_status = 404
- elif len(article) > 100 or not re.match("^[0-9a-zA-Z_-]+$", article):
+ elif len(article) > 100 or not re.match(r"^[0-9a-zA-Z_-]+$", article):
article = "missing"
http_status = 404
diff --git a/zerver/webhooks/bitbucket2/view.py b/zerver/webhooks/bitbucket2/view.py
index b95f7fa190d..dedf5ab886f 100644
--- a/zerver/webhooks/bitbucket2/view.py
+++ b/zerver/webhooks/bitbucket2/view.py
@@ -187,7 +187,7 @@ def get_type(request: HttpRequest, payload: WildValue) -> str:
# Note that we only need the HTTP header to determine pullrequest events.
# We rely on the payload itself to determine the other ones.
event_key = validate_extract_webhook_http_header(request, "X-Event-Key", "BitBucket")
- action = re.match("pullrequest:(?P<action>.*)$", event_key)
+ action = re.match(r"pullrequest:(?P<action>.*)$", event_key)
if action:
action_group = action.group("action")
if action_group in PULL_REQUEST_SUPPORTED_ACTIONS:
diff --git a/zerver/webhooks/gitlab/view.py b/zerver/webhooks/gitlab/view.py
index 1665d7e1831..ec25040d924 100644
--- a/zerver/webhooks/gitlab/view.py
+++ b/zerver/webhooks/gitlab/view.py
@@ -92,7 +92,7 @@ def get_issue_created_event_body(payload: WildValue, include_title: bool) -> str
if description:
stringified_description = description.tame(check_string)
stringified_description = re.sub(
- "<!--.*?-->", "", stringified_description, count=0, flags=re.DOTALL
+ r"<!--.*?-->", "", stringified_description, count=0, flags=re.DOTALL
)
stringified_description = stringified_description.rstrip()
else:
diff --git a/zerver/webhooks/jira/view.py b/zerver/webhooks/jira/view.py
index f322e1abdf3..aeec57b0aa7 100644
--- a/zerver/webhooks/jira/view.py
+++ b/zerver/webhooks/jira/view.py
@@ -81,7 +81,7 @@ def convert_jira_markup(content: str, realm: Realm) -> str:
# Try to convert a Jira user mention of format [~username] into a
# Zulip user mention. We don't know the email, just the Jira username,
# so we naively guess at their Zulip account using this
- mention_re = re.compile("\\[~(.*?)\\]")
+ mention_re = re.compile(r"\[~(.*?)\]")
for username in mention_re.findall(content):
# Try to look up username
user_profile = guess_zulip_user_from_jira(username, realm)
diff --git a/zerver/webhooks/slack_incoming/view.py b/zerver/webhooks/slack_incoming/view.py
index 238abf5f748..addc8c5981c 100644
--- a/zerver/webhooks/slack_incoming/view.py
+++ b/zerver/webhooks/slack_incoming/view.py
@@ -55,7 +55,7 @@ def api_slack_incoming_webhook(
if user_specified_topic is None and "channel" in payload:
channel = payload["channel"].tame(check_string)
- user_specified_topic = re.sub("^[@#]", "", channel)
+ user_specified_topic = re.sub(r"^[@#]", "", channel)
if user_specified_topic is None:
user_specified_topic = "(no topic)"
diff --git a/zerver/webhooks/updown/view.py b/zerver/webhooks/updown/view.py
index 367c75ad639..20047967e8b 100644
--- a/zerver/webhooks/updown/view.py
+++ b/zerver/webhooks/updown/view.py
@@ -88,7 +88,7 @@ def api_updown_webhook(
def get_event_type(event: WildValue) -> str:
- event_type_match = re.match("check.(.*)", event["event"].tame(check_string))
+ event_type_match = re.match(r"check.(.*)", event["event"].tame(check_string))
if event_type_match:
event_type = event_type_match.group(1)
if event_type in EVENT_TYPE_BODY_MAPPER: