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: Close opened files.

Anders Kaseorg31d0141a3091
diff --git a/scripts/lib/hash_reqs.py b/scripts/lib/hash_reqs.py
index ddc0ada928f..c338e43454c 100755
--- a/scripts/lib/hash_reqs.py
+++ b/scripts/lib/hash_reqs.py
@@ -10,12 +10,13 @@ from typing import Iterable, List
def expand_reqs_helper(fpath: str) -> List[str]:
result = [] # type: List[str]
- for line in open(fpath):
- if line.strip().startswith(('#', '--hash')):
- continue
- dep = line.split(" \\", 1)[0].strip()
- if dep:
- result.append(dep)
+ with open(fpath) as f:
+ for line in f:
+ if line.strip().startswith(('#', '--hash')):
+ continue
+ dep = line.split(" \\", 1)[0].strip()
+ if dep:
+ result.append(dep)
return result
def expand_reqs(fpath: str) -> List[str]:
diff --git a/scripts/lib/setup_path.py b/scripts/lib/setup_path.py
index 20a190242aa..de2f090dfe7 100644
--- a/scripts/lib/setup_path.py
+++ b/scripts/lib/setup_path.py
@@ -11,7 +11,8 @@ def setup_path() -> None:
venv = os.path.join(BASE_DIR, "zulip-py3-venv")
activate_this = os.path.join(venv, "bin", "activate_this.py")
activate_locals = dict(__file__=activate_this)
- exec(open(activate_this).read(), activate_locals)
+ with open(activate_this) as f:
+ exec(f.read(), activate_locals)
# Check that the python version running this function
# is same as python version that created the virtualenv.
python_version = "python{}.{}".format(*sys.version_info[:2])
diff --git a/tools/lib/provision.py b/tools/lib/provision.py
index f4eef30c01e..58d28b48fc3 100755
--- a/tools/lib/provision.py
+++ b/tools/lib/provision.py
@@ -324,14 +324,17 @@ def main(options: argparse.Namespace) -> "NoReturn":
for apt_depedency in SYSTEM_DEPENDENCIES:
sha_sum.update(apt_depedency.encode('utf8'))
if "debian" in os_families():
- sha_sum.update(open('scripts/lib/setup-apt-repo', 'rb').read())
+ with open('scripts/lib/setup-apt-repo', 'rb') as fb:
+ sha_sum.update(fb.read())
else:
# hash the content of setup-yum-repo*
- sha_sum.update(open('scripts/lib/setup-yum-repo', 'rb').read())
+ with open('scripts/lib/setup-yum-repo', 'rb') as fb:
+ sha_sum.update(fb.read())
# hash the content of build-pgroonga if PGroonga is built from source
if BUILD_PGROONGA_FROM_SOURCE:
- sha_sum.update(open('scripts/lib/build-pgroonga', 'rb').read())
+ with open('scripts/lib/build-pgroonga', 'rb') as fb:
+ sha_sum.update(fb.read())
new_apt_dependencies_hash = sha_sum.hexdigest()
last_apt_dependencies_hash = None
@@ -408,7 +411,8 @@ def main(options: argparse.Namespace) -> "NoReturn":
# process inside the virtualenv.
activate_this = "/srv/zulip-py3-venv/bin/activate_this.py"
provision_inner = os.path.join(ZULIP_PATH, "tools", "lib", "provision_inner.py")
- exec(open(activate_this).read(), dict(__file__=activate_this))
+ with open(activate_this) as f:
+ exec(f.read(), dict(__file__=activate_this))
os.execvp(
provision_inner,
[
diff --git a/tools/lib/provision_inner.py b/tools/lib/provision_inner.py
index 573c37be7b6..a18f6404f4d 100755
--- a/tools/lib/provision_inner.py
+++ b/tools/lib/provision_inner.py
@@ -319,7 +319,8 @@ def main(options: argparse.Namespace) -> int:
version_file = os.path.join(UUID_VAR_PATH, 'provision_version')
print(f'writing to {version_file}\n')
- open(version_file, 'w').write(PROVISION_VERSION + '\n')
+ with open(version_file, 'w') as f:
+ f.write(PROVISION_VERSION + '\n')
print()
print(OKBLUE + "Zulip development environment setup succeeded!" + ENDC)
diff --git a/zerver/lib/dev_ldap_directory.py b/zerver/lib/dev_ldap_directory.py
index e13e08413f4..fcd6d72e5f4 100644
--- a/zerver/lib/dev_ldap_directory.py
+++ b/zerver/lib/dev_ldap_directory.py
@@ -22,8 +22,10 @@ def generate_dev_ldap_dir(mode: str, num_users: int=8) -> Dict[str, Dict[str, An
birthdate = f'19{i:02}-{i:02}-{i:02}'
ldap_data.append((name, email, phone_number, birthdate))
- profile_images = [open(path, "rb").read() for path in
- glob.glob(os.path.join(static_path("images/team"), "*"))]
+ profile_images = []
+ for path in glob.glob(os.path.join(static_path("images/team"), "*")):
+ with open(path, "rb") as f:
+ profile_images.append(f.read())
ldap_dir = {}
for i, user_data in enumerate(ldap_data):
email = user_data[1].lower()
diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.py
index 1fb9eb0c1b7..458c0fd2db0 100644
--- a/zerver/lib/test_classes.py
+++ b/zerver/lib/test_classes.py
@@ -814,7 +814,8 @@ Output:
os.path.dirname(__file__),
f"../webhooks/{type}/fixtures/{action}.{file_type}",
)
- return open(fn).read()
+ with open(fn) as f:
+ return f.read()
def fixture_file_name(self, file_name: str, type: str='') -> str:
return os.path.join(
@@ -824,7 +825,8 @@ Output:
def fixture_data(self, file_name: str, type: str='') -> str:
fn = self.fixture_file_name(file_name, type)
- return open(fn).read()
+ with open(fn) as f:
+ return f.read()
def make_stream(self, stream_name: str, realm: Optional[Realm]=None,
invite_only: bool=False,
diff --git a/zerver/openapi/test_curl_examples.py b/zerver/openapi/test_curl_examples.py
index 12e877da6f9..2c704d7575c 100644
--- a/zerver/openapi/test_curl_examples.py
+++ b/zerver/openapi/test_curl_examples.py
@@ -35,39 +35,39 @@ def test_generated_curl_examples_for_success(client: Client) -> None:
# should try to either avoid ordering dependencies or make them
# very explicit.
for file_name in sorted(glob.glob("templates/zerver/api/*.md")):
- documentation_lines = open(file_name).readlines()
- for line in documentation_lines:
- # A typical example from the Markdown source looks like this:
- # {generate_code_example(curl, ...}
- if not line.startswith("{generate_code_example(curl"):
- continue
- # To do an end-to-end test on the documentation examples
- # that will be actually shown to users, we use the
- # Markdown rendering pipeline to compute the user-facing
- # example, and then run that to test it.
- curl_command_html = md_engine.convert(line.strip())
- unescaped_html = html.unescape(curl_command_html)
- curl_command_text = unescaped_html[len("<p><code>curl\n"):-len("</code></p>")]
+ with open(file_name) as f:
+ for line in f:
+ # A typical example from the Markdown source looks like this:
+ # {generate_code_example(curl, ...}
+ if not line.startswith("{generate_code_example(curl"):
+ continue
+ # To do an end-to-end test on the documentation examples
+ # that will be actually shown to users, we use the
+ # Markdown rendering pipeline to compute the user-facing
+ # example, and then run that to test it.
+ curl_command_html = md_engine.convert(line.strip())
+ unescaped_html = html.unescape(curl_command_html)
+ curl_command_text = unescaped_html[len("<p><code>curl\n"):-len("</code></p>")]
- curl_command_text = curl_command_text.replace(
- "BOT_EMAIL_ADDRESS:BOT_API_KEY", authentication_line)
+ curl_command_text = curl_command_text.replace(
+ "BOT_EMAIL_ADDRESS:BOT_API_KEY", authentication_line)
- print("Testing {} ...".format(curl_command_text.split("\n")[0]))
+ print("Testing {} ...".format(curl_command_text.split("\n")[0]))
- # Turn the text into an arguments list.
- generated_curl_command = [
- x for x in shlex.split(curl_command_text) if x != "\n"]
+ # Turn the text into an arguments list.
+ generated_curl_command = [
+ x for x in shlex.split(curl_command_text) if x != "\n"]
- response_json = None
- response = None
- try:
- # We split this across two lines so if curl fails and
- # returns non-JSON output, we'll still print it.
- response_json = subprocess.check_output(generated_curl_command).decode('utf-8')
- response = json.loads(response_json)
- assert(response["result"] == "success")
- except (AssertionError, Exception):
- error_template = """
+ response_json = None
+ response = None
+ try:
+ # We split this across two lines so if curl fails and
+ # returns non-JSON output, we'll still print it.
+ response_json = subprocess.check_output(generated_curl_command).decode('utf-8')
+ response = json.loads(response_json)
+ assert(response["result"] == "success")
+ except (AssertionError, Exception):
+ error_template = """
Error verifying the success of the API documentation curl example.
File: {file_name}
@@ -89,12 +89,12 @@ Common reasons for why this could occur:
To learn more about the test itself, see zerver/openapi/test_curl_examples.py.
"""
- print(error_template.format(
- file_name=file_name,
- line=line,
- curl_command=generated_curl_command,
- response=response_json if response is None else json.dumps(response, indent=4)))
- raise
+ print(error_template.format(
+ file_name=file_name,
+ line=line,
+ curl_command=generated_curl_command,
+ response=response_json if response is None else json.dumps(response, indent=4)))
+ raise
if REGISTERED_GENERATOR_FUNCTIONS != CALLED_GENERATOR_FUNCTIONS:
raise Exception("Some registered generator functions were not called:\n"
diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.py
index d0355ef232b..212a84697b0 100644
--- a/zerver/tests/test_auth_backends.py
+++ b/zerver/tests/test_auth_backends.py
@@ -4657,8 +4657,7 @@ class TestZulipLDAPUserPopulator(ZulipLDAPTestCase):
@use_s3_backend
def test_update_user_avatar_for_s3(self) -> None:
bucket = create_s3_buckets(settings.S3_AVATAR_BUCKET)[0]
- test_image_file = get_test_image_file('img.png').name
- with open(test_image_file, 'rb') as f:
+ with get_test_image_file('img.png') as f:
test_image_data = f.read()
self.change_ldap_user_attr('hamlet', 'jpegPhoto', test_image_data)
with self.settings(AUTH_LDAP_USER_ATTR_MAP={'full_name': 'cn',
diff --git a/zerver/tests/test_decorators.py b/zerver/tests/test_decorators.py
index c2b0bba6239..6f61ce23f32 100644
--- a/zerver/tests/test_decorators.py
+++ b/zerver/tests/test_decorators.py
@@ -1802,15 +1802,16 @@ class TestUserAgentParsing(ZulipTestCase):
"""Test for our user agent parsing logic, using a large data set."""
user_agents_parsed: Dict[str, int] = defaultdict(int)
user_agents_path = os.path.join(settings.DEPLOY_ROOT, "zerver/tests/fixtures/user_agents_unique")
- for line in open(user_agents_path).readlines():
- line = line.strip()
- match = re.match('^(?P<count>[0-9]+) "(?P<user_agent>.*)"$', line)
- assert match is not None
- groupdict = match.groupdict()
- count = groupdict["count"]
- user_agent = groupdict["user_agent"]
- ret = parse_user_agent(user_agent)
- user_agents_parsed[ret["name"]] += int(count)
+ 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)
+ assert match is not None
+ groupdict = match.groupdict()
+ count = groupdict["count"]
+ user_agent = groupdict["user_agent"]
+ ret = parse_user_agent(user_agent)
+ user_agents_parsed[ret["name"]] += int(count)
class TestIgnoreUnhashableLRUCache(ZulipTestCase):
diff --git a/zerver/tests/test_import_export.py b/zerver/tests/test_import_export.py
index 8968da4923f..118b6fb1c92 100644
--- a/zerver/tests/test_import_export.py
+++ b/zerver/tests/test_import_export.py
@@ -275,8 +275,6 @@ class ImportExportTest(ZulipTestCase):
upload_emoji_image(img_file, '1.png', user_profile)
with get_test_image_file('img.png') as img_file:
upload_avatar_image(img_file, user_profile, user_profile)
- with open(get_test_image_file('img.png').name, 'rb') as f:
- test_image = f.read()
with get_test_image_file('img.png') as img_file:
upload.upload_backend.upload_realm_icon_image(img_file, user_profile)
@@ -289,7 +287,8 @@ class ImportExportTest(ZulipTestCase):
upload.upload_backend.upload_realm_logo_image(img_file, user_profile, night=True)
do_change_logo_source(realm, Realm.LOGO_UPLOADED, True, acting_user=user_profile)
- test_image = get_test_image_file('img.png').read()
+ with get_test_image_file('img.png') as img_file:
+ test_image = img_file.read()
message.sender.avatar_source = 'U'
message.sender.save()
@@ -334,7 +333,8 @@ class ImportExportTest(ZulipTestCase):
for record in records:
image_path = os.path.join(full_data['realm_icons_dir'], record["path"])
if image_path[-9:] == ".original":
- image_data = open(image_path, 'rb').read()
+ with open(image_path, 'rb') as image_file:
+ image_data = image_file.read()
self.assertEqual(image_data, test_image)
else:
self.assertTrue(os.path.exists(image_path))
@@ -400,7 +400,8 @@ class ImportExportTest(ZulipTestCase):
for record in records:
image_path = os.path.join(full_data['realm_icons_dir'], record["s3_path"])
if image_path[-9:] == ".original":
- image_data = open(image_path, 'rb').read()
+ with open(image_path, 'rb') as image_file:
+ image_data = image_file.read()
self.assertEqual(image_data, test_image)
else:
self.assertTrue(os.path.exists(image_path))
@@ -1053,7 +1054,7 @@ class ImportExportTest(ZulipTestCase):
upload_path = upload.upload_backend.realm_avatar_and_logo_path(imported_realm)
full_upload_path = os.path.join(settings.LOCAL_UPLOADS_DIR, upload_path)
- with open(get_test_image_file('img.png').name, 'rb') as f:
+ with get_test_image_file('img.png') as f:
test_image_data = f.read()
self.assertIsNotNone(test_image_data)
@@ -1086,7 +1087,7 @@ class ImportExportTest(ZulipTestCase):
with patch('logging.info'):
do_import_realm(os.path.join(settings.TEST_WORKER_DIR, 'test-export'), 'test-zulip')
imported_realm = Realm.objects.get(string_id='test-zulip')
- with open(get_test_image_file('img.png').name, 'rb') as f:
+ with get_test_image_file('img.png') as f:
test_image_data = f.read()
# Test attachments
diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.py
index 64ed4fe0e78..54f74371f8f 100644
--- a/zerver/tests/test_signup.py
+++ b/zerver/tests/test_signup.py
@@ -3099,8 +3099,10 @@ class UserSignUpTest(InviteUserBase):
zulip_path_id = avatar_disk_path(hamlet_in_zulip)
lear_path_id = avatar_disk_path(hamlet_in_lear)
- zulip_avatar_bits = open(zulip_path_id, 'rb').read()
- lear_avatar_bits = open(lear_path_id, 'rb').read()
+ with open(zulip_path_id, 'rb') as f:
+ zulip_avatar_bits = f.read()
+ with open(lear_path_id, 'rb') as f:
+ lear_avatar_bits = f.read()
self.assertTrue(len(zulip_avatar_bits) > 500)
self.assertEqual(zulip_avatar_bits, lear_avatar_bits)
diff --git a/zerver/tests/test_slack_importer.py b/zerver/tests/test_slack_importer.py
index e74723c05df..c47ef75f1e3 100644
--- a/zerver/tests/test_slack_importer.py
+++ b/zerver/tests/test_slack_importer.py
@@ -1,5 +1,6 @@
import os
import shutil
+from io import BytesIO
from typing import Any, Dict, Iterator, List, Optional, Set, Tuple
from unittest import mock
from unittest.mock import ANY, call
@@ -767,7 +768,8 @@ class SlackImporter(ZulipTestCase):
user_data_fixture = orjson.loads(self.fixture_data('user_data.json', type='slack_fixtures'))
team_info_fixture = orjson.loads(self.fixture_data('team_info.json', type='slack_fixtures'))
mock_get_slack_api_data.side_effect = [user_data_fixture['members'], {}, team_info_fixture["team"]]
- mock_requests_get.return_value.raw = get_test_image_file("img.png")
+ with get_test_image_file("img.png") as f:
+ mock_requests_get.return_value.raw = BytesIO(f.read())
with self.assertLogs(level="INFO"):
do_convert_data(test_slack_zip_file, output_dir, token)
diff --git a/zerver/tests/test_thumbnail.py b/zerver/tests/test_thumbnail.py
index 66ba1df24f6..cba70725c09 100644
--- a/zerver/tests/test_thumbnail.py
+++ b/zerver/tests/test_thumbnail.py
@@ -62,10 +62,10 @@ class ThumbnailTest(ZulipTestCase):
# Test custom emoji URLs in Zulip messages.
user_profile = self.example_user("hamlet")
- image_file = get_test_image_file("img.png")
file_name = "emoji.png"
- upload_emoji_image(image_file, file_name, user_profile)
+ with get_test_image_file("img.png") as image_file:
+ upload_emoji_image(image_file, file_name, user_profile)
custom_emoji_url = upload_backend.get_emoji_url(file_name, user_profile.realm_id)
emoji_url_base = '/user_avatars/'
self.assertEqual(emoji_url_base, custom_emoji_url[:len(emoji_url_base)])
@@ -206,10 +206,10 @@ class ThumbnailTest(ZulipTestCase):
# Test custom emoji urls in Zulip messages.
user_profile = self.example_user("hamlet")
- image_file = get_test_image_file("img.png")
file_name = "emoji.png"
- upload_emoji_image(image_file, file_name, user_profile)
+ with get_test_image_file("img.png") as image_file:
+ upload_emoji_image(image_file, file_name, user_profile)
custom_emoji_url = upload_backend.get_emoji_url(file_name, user_profile.realm_id)
emoji_url_base = '/user_avatars/'
self.assertEqual(emoji_url_base, custom_emoji_url[:len(emoji_url_base)])
diff --git a/zerver/tests/test_transfer.py b/zerver/tests/test_transfer.py
index ab12fe8ee28..561f8321c06 100644
--- a/zerver/tests/test_transfer.py
+++ b/zerver/tests/test_transfer.py
@@ -47,9 +47,12 @@ class TransferUploadsToS3Test(ZulipTestCase):
medium_image_key = bucket.Object(path_id + "-medium.png")
self.assertEqual(len(list(bucket.objects.all())), 3)
- self.assertEqual(image_key.get()['Body'].read(), open(avatar_disk_path(user), "rb").read())
- self.assertEqual(original_image_key.get()['Body'].read(), open(avatar_disk_path(user, original=True), "rb").read())
- self.assertEqual(medium_image_key.get()['Body'].read(), open(avatar_disk_path(user, medium=True), "rb").read())
+ with open(avatar_disk_path(user), "rb") as f:
+ self.assertEqual(image_key.get()['Body'].read(), f.read())
+ with open(avatar_disk_path(user, original=True), "rb") as f:
+ self.assertEqual(original_image_key.get()['Body'].read(), f.read())
+ with open(avatar_disk_path(user, medium=True), "rb") as f:
+ self.assertEqual(medium_image_key.get()['Body'].read(), f.read())
@mock_s3
def test_transfer_message_files(self) -> None:
@@ -76,9 +79,9 @@ class TransferUploadsToS3Test(ZulipTestCase):
RealmEmoji.objects.all().delete()
emoji_name = "emoji.png"
- image_file = get_test_image_file("img.png")
- emoji = check_add_realm_emoji(othello.realm, emoji_name, othello, image_file)
+ with get_test_image_file("img.png") as image_file:
+ emoji = check_add_realm_emoji(othello.realm, emoji_name, othello, image_file)
if not emoji:
raise AssertionError("Unable to add emoji.")
@@ -94,8 +97,8 @@ class TransferUploadsToS3Test(ZulipTestCase):
original_key = bucket.Object(emoji_path + ".original")
resized_key = bucket.Object(emoji_path)
- image_file.seek(0)
- image_data = image_file.read()
+ with get_test_image_file("img.png") as image_file:
+ image_data = image_file.read()
resized_image_data = resize_emoji(image_data)
self.assertEqual(image_data, original_key.get()['Body'].read())
diff --git a/zerver/tests/test_upload.py b/zerver/tests/test_upload.py
index 35a58e64ad7..04b30f9b909 100644
--- a/zerver/tests/test_upload.py
+++ b/zerver/tests/test_upload.py
@@ -1096,15 +1096,18 @@ class AvatarTest(UploadSerializeMixin, ZulipTestCase):
source_path_id = avatar_disk_path(source_user_profile)
target_path_id = avatar_disk_path(target_user_profile)
self.assertNotEqual(source_path_id, target_path_id)
- self.assertEqual(open(source_path_id, "rb").read(), open(target_path_id, "rb").read())
+ with open(source_path_id, "rb") as source, open(target_path_id, "rb") as target:
+ self.assertEqual(source.read(), target.read())
source_original_path_id = avatar_disk_path(source_user_profile, original=True)
target_original_path_id = avatar_disk_path(target_user_profile, original=True)
- self.assertEqual(open(source_original_path_id, "rb").read(), open(target_original_path_id, "rb").read())
+ with open(source_original_path_id, "rb") as source, open(target_original_path_id, "rb") as target:
+ self.assertEqual(source.read(), target.read())
source_medium_path_id = avatar_disk_path(source_user_profile, medium=True)
target_medium_path_id = avatar_disk_path(target_user_profile, medium=True)
- self.assertEqual(open(source_medium_path_id, "rb").read(), open(target_medium_path_id, "rb").read())
+ with open(source_medium_path_id, "rb") as source, open(target_medium_path_id, "rb") as target:
+ self.assertEqual(source.read(), target.read())
def test_delete_avatar_image(self) -> None:
self.login('hamlet')
@@ -1184,33 +1187,38 @@ class EmojiTest(UploadSerializeMixin, ZulipTestCase):
# with a corresponding increase in the duration of the previous frame.
def test_resize_emoji(self) -> None:
# Test unequal width and height of animated GIF image
- animated_unequal_img_data = get_test_image_file('animated_unequal_img.gif').read()
+ with get_test_image_file('animated_unequal_img.gif') as f:
+ animated_unequal_img_data = f.read()
resized_img_data = resize_emoji(animated_unequal_img_data, size=50)
im = Image.open(io.BytesIO(resized_img_data))
self.assertEqual((50, 50), im.size)
# Test corrupt image exception
- corrupted_img_data = get_test_image_file('corrupt.gif').read()
+ with get_test_image_file('corrupt.gif') as f:
+ corrupted_img_data = f.read()
with self.assertRaises(BadImageError):
resize_emoji(corrupted_img_data)
# Test an image larger than max is resized
+ with get_test_image_file('animated_large_img.gif') as f:
+ animated_large_img_data = f.read()
with patch('zerver.lib.upload.MAX_EMOJI_GIF_SIZE', 128):
- animated_large_img_data = get_test_image_file('animated_large_img.gif').read()
resized_img_data = resize_emoji(animated_large_img_data, size=50)
im = Image.open(io.BytesIO(resized_img_data))
self.assertEqual((50, 50), im.size)
# Test an image file larger than max is resized
+ with get_test_image_file('animated_large_img.gif') as f:
+ animated_large_img_data = f.read()
with patch('zerver.lib.upload.MAX_EMOJI_GIF_FILE_SIZE_BYTES', 3 * 1024 * 1024):
- animated_large_img_data = get_test_image_file('animated_large_img.gif').read()
resized_img_data = resize_emoji(animated_large_img_data, size=50)
im = Image.open(io.BytesIO(resized_img_data))
self.assertEqual((50, 50), im.size)
# Test an image smaller than max and smaller than file size max is not resized
+ with get_test_image_file('animated_large_img.gif') as f:
+ animated_large_img_data = f.read()
with patch('zerver.lib.upload.MAX_EMOJI_GIF_SIZE', 512):
- animated_large_img_data = get_test_image_file('animated_large_img.gif').read()
resized_img_data = resize_emoji(animated_large_img_data, size=50)
im = Image.open(io.BytesIO(resized_img_data))
self.assertEqual((256, 256), im.size)
@@ -1543,10 +1551,10 @@ class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):
def test_emoji_upload_local(self) -> None:
user_profile = self.example_user("hamlet")
- image_file = get_test_image_file("img.png")
file_name = "emoji.png"
- upload_emoji_image(image_file, file_name, user_profile)
+ with get_test_image_file("img.png") as image_file:
+ upload_emoji_image(image_file, file_name, user_profile)
emoji_path = RealmEmoji.PATH_ID_TEMPLATE.format(
realm_id=user_profile.realm_id,
@@ -1557,16 +1565,16 @@ class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):
with get_test_image_file("img.png") as image_file, open(file_path + ".original", "rb") as original_file:
self.assertEqual(image_file.read(), original_file.read())
- resized_image = Image.open(open(file_path, "rb"))
expected_size = (DEFAULT_EMOJI_SIZE, DEFAULT_EMOJI_SIZE)
- self.assertEqual(expected_size, resized_image.size)
+ with Image.open(file_path) as resized_image:
+ self.assertEqual(expected_size, resized_image.size)
def test_get_emoji_url_local(self) -> None:
user_profile = self.example_user("hamlet")
- image_file = get_test_image_file("img.png")
file_name = "emoji.png"
- upload_emoji_image(image_file, file_name, user_profile)
+ with get_test_image_file("img.png") as image_file:
+ upload_emoji_image(image_file, file_name, user_profile)
url = zerver.lib.upload.upload_backend.get_emoji_url(file_name, user_profile.realm_id)
emoji_path = RealmEmoji.PATH_ID_TEMPLATE.format(
@@ -1816,13 +1824,13 @@ class S3Test(ZulipTestCase):
bucket = create_s3_buckets(settings.S3_AVATAR_BUCKET)[0]
user_profile = self.example_user("hamlet")
- image_file = get_test_image_file("img.png")
- zerver.lib.upload.upload_backend.upload_realm_icon_image(image_file, user_profile)
+ with get_test_image_file("img.png") as image_file:
+ zerver.lib.upload.upload_backend.upload_realm_icon_image(image_file, user_profile)
original_path_id = os.path.join(str(user_profile.realm.id), "realm", "icon.original")
original_key = bucket.Object(original_path_id)
- image_file.seek(0)
- self.assertEqual(image_file.read(), original_key.get()['Body'].read())
+ with get_test_image_file("img.png") as image_file:
+ self.assertEqual(image_file.read(), original_key.get()['Body'].read())
resized_path_id = os.path.join(str(user_profile.realm.id), "realm", "icon.png")
resized_data = bucket.Object(resized_path_id).get()['Body'].read()
@@ -1835,13 +1843,13 @@ class S3Test(ZulipTestCase):
bucket = create_s3_buckets(settings.S3_AVATAR_BUCKET)[0]
user_profile = self.example_user("hamlet")
- image_file = get_test_image_file("img.png")
- zerver.lib.upload.upload_backend.upload_realm_logo_image(image_file, user_profile, night)
+ with get_test_image_file("img.png") as image_file:
+ zerver.lib.upload.upload_backend.upload_realm_logo_image(image_file, user_profile, night)
original_path_id = os.path.join(str(user_profile.realm.id), "realm", f"{file_name}.original")
original_key = bucket.Object(original_path_id)
- image_file.seek(0)
- self.assertEqual(image_file.read(), original_key.get()['Body'].read())
+ with get_test_image_file("img.png") as image_file:
+ self.assertEqual(image_file.read(), original_key.get()['Body'].read())
resized_path_id = os.path.join(str(user_profile.realm.id), "realm", f"{file_name}.png")
resized_data = bucket.Object(resized_path_id).get()['Body'].read()
@@ -1857,17 +1865,17 @@ class S3Test(ZulipTestCase):
bucket = create_s3_buckets(settings.S3_AVATAR_BUCKET)[0]
user_profile = self.example_user("hamlet")
- image_file = get_test_image_file("img.png")
emoji_name = "emoji.png"
- zerver.lib.upload.upload_backend.upload_emoji_image(image_file, emoji_name, user_profile)
+ with get_test_image_file("img.png") as image_file:
+ zerver.lib.upload.upload_backend.upload_emoji_image(image_file, emoji_name, user_profile)
emoji_path = RealmEmoji.PATH_ID_TEMPLATE.format(
realm_id=user_profile.realm_id,
emoji_file_name=emoji_name,
)
original_key = bucket.Object(emoji_path + ".original")
- image_file.seek(0)
- self.assertEqual(image_file.read(), original_key.get()['Body'].read())
+ with get_test_image_file("img.png") as image_file:
+ self.assertEqual(image_file.read(), original_key.get()['Body'].read())
resized_data = bucket.Object(emoji_path).get()['Body'].read()
resized_image = Image.open(io.BytesIO(resized_data))
@@ -1973,39 +1981,33 @@ class UploadSpaceTests(UploadSerializeMixin, ZulipTestCase):
class ExifRotateTests(ZulipTestCase):
def test_image_do_not_rotate(self) -> None:
# Image does not have _getexif method.
- img_data = get_test_image_file('img.png').read()
- img = Image.open(io.BytesIO(img_data))
- result = exif_rotate(img)
- self.assertEqual(result, img)
+ with get_test_image_file('img.png') as f, Image.open(f) as img:
+ result = exif_rotate(img)
+ self.assertEqual(result, img)
# Image with no exif data.
- img_data = get_test_image_file('img_no_exif.jpg').read()
- img = Image.open(io.BytesIO(img_data))
- result = exif_rotate(img)
- self.assertEqual(result, img)
+ with get_test_image_file('img_no_exif.jpg') as f, Image.open(f) as img:
+ result = exif_rotate(img)
+ self.assertEqual(result, img)
# Orientation of the image is 1.
- img_data = get_test_image_file('img.jpg').read()
- img = Image.open(io.BytesIO(img_data))
- result = exif_rotate(img)
- self.assertEqual(result, img)
+ with get_test_image_file('img.jpg') as f, Image.open(f) as img:
+ result = exif_rotate(img)
+ self.assertEqual(result, img)
def test_image_rotate(self) -> None:
with mock.patch('PIL.Image.Image.rotate') as rotate:
- img_data = get_test_image_file('img_orientation_3.jpg').read()
- img = Image.open(io.BytesIO(img_data))
- exif_rotate(img)
- rotate.assert_called_with(180, expand=True)
-
- img_data = get_test_image_file('img_orientation_6.jpg').read()
- img = Image.open(io.BytesIO(img_data))
- exif_rotate(img)
- rotate.assert_called_with(270, expand=True)
-
- img_data = get_test_image_file('img_orientation_8.jpg').read()
- img = Image.open(io.BytesIO(img_data))
- exif_rotate(img)
- rotate.assert_called_with(90, expand=True)
+ with get_test_image_file('img_orientation_3.jpg') as f, Image.open(f) as img:
+ exif_rotate(img)
+ rotate.assert_called_with(180, expand=True)
+
+ with get_test_image_file('img_orientation_6.jpg') as f, Image.open(f) as img:
+ exif_rotate(img)
+ rotate.assert_called_with(270, expand=True)
+
+ with get_test_image_file('img_orientation_8.jpg') as f, Image.open(f) as img:
+ exif_rotate(img)
+ rotate.assert_called_with(90, expand=True)
class DecompressionBombTests(ZulipTestCase):
def setUp(self) -> None:
diff --git a/zilencer/management/commands/add_mock_conversation.py b/zilencer/management/commands/add_mock_conversation.py
index a86313f7206..19eb9c169e7 100644
--- a/zilencer/management/commands/add_mock_conversation.py
+++ b/zilencer/management/commands/add_mock_conversation.py
@@ -37,7 +37,8 @@ From image editing program:
"""
def set_avatar(self, user: UserProfile, filename: str) -> None:
- upload_avatar_image(open(filename, 'rb'), user, user)
+ with open(filename, 'rb') as f:
+ upload_avatar_image(f, user, user)
do_change_avatar_fields(user, UserProfile.AVATAR_FROM_USER, acting_user=None)
def add_message_formatting_conversation(self) -> None: