diff --git a/analytics/tests/test_fixtures.py b/analytics/tests/test_fixtures.py index cc9da62750..9389553ecc 100644 --- a/analytics/tests/test_fixtures.py +++ b/analytics/tests/test_fixtures.py @@ -22,7 +22,7 @@ class TestFixtures(ZulipTestCase): frequency=CountStat.HOUR, ) # test we get an array of the right length with frequency=CountStat.HOUR - self.assertEqual(len(data), 24) + self.assert_length(data, 24) # test that growth doesn't affect the first data point self.assertEqual(data[0], 2000) # test that the last data point is growth times what it otherwise would be diff --git a/analytics/tests/test_views.py b/analytics/tests/test_views.py index bfa522755e..909d8df310 100644 --- a/analytics/tests/test_views.py +++ b/analytics/tests/test_views.py @@ -978,7 +978,7 @@ class TestSupportEndpoint(ZulipTestCase): self.assertIn( "request for sponsored hosting has been approved", messages[0].message.content ) - self.assertEqual(len(messages), 1) + self.assert_length(messages, 1) def test_activate_or_deactivate_realm(self) -> None: cordelia = self.example_user("cordelia") diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.py index fc51e209e6..59cc05eb39 100644 --- a/corporate/tests/test_stripe.py +++ b/corporate/tests/test_stripe.py @@ -1297,7 +1297,7 @@ class StripeTest(StripeTestCase): m.output[0], f"WARNING:corporate.stripe:Customer id> trying to upgrade, but has an active subscription", ) - self.assertEqual(len(m.output), 1) + self.assert_length(m.output, 1) def test_check_upgrade_parameters(self) -> None: # Tests all the error paths except 'not enough licenses' @@ -1439,10 +1439,10 @@ class StripeTest(StripeTestCase): self.assertEqual(customer.sponsorship_pending, True) from django.core.mail import outbox - self.assertEqual(len(outbox), 1) + self.assert_length(outbox, 1) for message in outbox: - self.assertEqual(len(message.to), 1) + self.assert_length(message.to, 1) self.assertEqual(message.to[0], "desdemona+admin@zulip.com") self.assertEqual(message.subject, "Sponsorship request (Open-source) for zulip") self.assertEqual(message.reply_to, ["hamlet@zulip.com"]) @@ -1953,7 +1953,7 @@ class StripeTest(StripeTestCase): self.assertEqual(annual_plan.next_invoice_date, self.next_month) self.assertEqual(annual_plan.invoiced_through, None) annual_ledger_entries = LicenseLedger.objects.filter(plan=annual_plan).order_by("id") - self.assertEqual(len(annual_ledger_entries), 2) + self.assert_length(annual_ledger_entries, 2) self.assertEqual(annual_ledger_entries[0].is_renewal, True) self.assertEqual( annual_ledger_entries.values_list("licenses", "licenses_at_next_renewal")[0], (20, 20) @@ -1972,7 +1972,7 @@ class StripeTest(StripeTestCase): invoice_plans_as_needed(self.next_month) annual_ledger_entries = LicenseLedger.objects.filter(plan=annual_plan).order_by("id") - self.assertEqual(len(annual_ledger_entries), 2) + self.assert_length(annual_ledger_entries, 2) annual_plan.refresh_from_db() self.assertEqual(annual_plan.invoicing_status, CustomerPlan.DONE) self.assertEqual(annual_plan.invoiced_through, annual_ledger_entries[1]) @@ -2128,7 +2128,7 @@ class StripeTest(StripeTestCase): self.assertEqual(annual_plan.billing_cycle_anchor, self.next_month) self.assertEqual(annual_plan.next_invoice_date, self.next_month) annual_ledger_entries = LicenseLedger.objects.filter(plan=annual_plan).order_by("id") - self.assertEqual(len(annual_ledger_entries), 1) + self.assert_length(annual_ledger_entries, 1) self.assertEqual(annual_ledger_entries[0].is_renewal, True) self.assertEqual( annual_ledger_entries.values_list("licenses", "licenses_at_next_renewal")[0], @@ -2645,7 +2645,7 @@ class StripeTest(StripeTestCase): self.assertEqual(void_all_open_invoices(iago.realm), 1) invoices = stripe.Invoice.list(customer=customer.stripe_customer_id) - self.assertEqual(len(invoices), 1) + self.assert_length(invoices, 1) for invoice in invoices: self.assertEqual(invoice.status, "void") @@ -2780,7 +2780,7 @@ class RequiresBillingAccessTest(ZulipTestCase): json_endpoints = { word.strip("\"'()[],$") for word in string_with_all_endpoints.split() if "json/" in word } - self.assertEqual(len(json_endpoints), 4) + self.assert_length(json_endpoints, 4) class BillingHelpersTest(ZulipTestCase): diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.py index 5f43f25a91..d10155f131 100644 --- a/zerver/lib/test_classes.py +++ b/zerver/lib/test_classes.py @@ -1009,7 +1009,7 @@ Output: streams = sorted(streams, key=lambda x: x.name) subscribed_streams = gather_subscriptions(self.nonreg_user(user_name))[0] - self.assertEqual(len(subscribed_streams), len(streams)) + self.assert_length(subscribed_streams, len(streams)) for x, y in zip(subscribed_streams, streams): self.assertEqual(x["name"], y.name) diff --git a/zerver/tests/test_alert_words.py b/zerver/tests/test_alert_words.py index aff9983d16..c04a7b5316 100644 --- a/zerver/tests/test_alert_words.py +++ b/zerver/tests/test_alert_words.py @@ -106,7 +106,7 @@ class AlertWordTests(ZulipTestCase): do_add_alert_words(user2, ["another"]) realm_words = alert_words_in_realm(user2.realm) - self.assertEqual(len(realm_words), 2) + self.assert_length(realm_words, 2) self.assertEqual(set(realm_words.keys()), {user1.id, user2.id}) self.assertEqual(set(realm_words[user1.id]), set(self.interesting_alert_word_list)) self.assertEqual(set(realm_words[user2.id]), {"another"}) diff --git a/zerver/tests/test_audit_log.py b/zerver/tests/test_audit_log.py index 84b99b6de0..5fa9e4230e 100644 --- a/zerver/tests/test_audit_log.py +++ b/zerver/tests/test_audit_log.py @@ -493,7 +493,7 @@ class TestRealmAuditLog(ZulipTestCase): acting_user=user, event_time__gte=test_start, ) - self.assertEqual(len(audit_entries), 1) + self.assert_length(audit_entries, 1) self.assertEqual(icon_source, realm.icon_source) self.assertEqual( audit_entries.first().extra_data, "{'icon_source': 'G', 'icon_version': 2}" diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.py index c32b80ba12..8635f75099 100644 --- a/zerver/tests/test_auth_backends.py +++ b/zerver/tests/test_auth_backends.py @@ -1138,7 +1138,7 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase): def test_social_auth_mobile_success(self) -> None: mobile_flow_otp = "1234abcd" * 8 account_data_dict = self.get_account_data_dict(email=self.email, name="Full Name") - self.assertEqual(len(mail.outbox), 0) + self.assert_length(mail.outbox, 0) self.user_profile.date_joined = timezone_now() - datetime.timedelta( seconds=JUST_CREATED_THRESHOLD + 1 ) @@ -1172,7 +1172,7 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase): encrypted_api_key = query_params["otp_encrypted_api_key"][0] hamlet_api_keys = get_all_api_keys(self.example_user("hamlet")) self.assertIn(otp_decrypt_api_key(encrypted_api_key, mobile_flow_otp), hamlet_api_keys) - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) self.assertIn("Zulip on Android", mail.outbox[0].body) def test_social_auth_desktop_success(self) -> None: @@ -3401,7 +3401,7 @@ class GoogleAuthBackendTest(SocialAuthBase): def test_social_auth_mobile_success_legacy_url(self) -> None: mobile_flow_otp = "1234abcd" * 8 account_data_dict = self.get_account_data_dict(email=self.email, name="Full Name") - self.assertEqual(len(mail.outbox), 0) + self.assert_length(mail.outbox, 0) self.user_profile.date_joined = timezone_now() - datetime.timedelta( seconds=JUST_CREATED_THRESHOLD + 1 ) @@ -3442,7 +3442,7 @@ class GoogleAuthBackendTest(SocialAuthBase): encrypted_api_key = query_params["otp_encrypted_api_key"][0] hamlet_api_keys = get_all_api_keys(self.example_user("hamlet")) self.assertIn(otp_decrypt_api_key(encrypted_api_key, mobile_flow_otp), hamlet_api_keys) - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) self.assertIn("Zulip on Android", mail.outbox[0].body) def test_google_auth_enabled(self) -> None: @@ -4525,7 +4525,7 @@ class TestZulipRemoteUserBackend(DesktopFlowTestingLib, ZulipTestCase): encrypted_api_key = query_params["otp_encrypted_api_key"][0] hamlet_api_keys = get_all_api_keys(self.example_user("hamlet")) self.assertIn(otp_decrypt_api_key(encrypted_api_key, mobile_flow_otp), hamlet_api_keys) - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) self.assertIn("Zulip on Android", mail.outbox[0].body) @override_settings(SEND_LOGIN_EMAILS=True) @@ -4574,7 +4574,7 @@ class TestZulipRemoteUserBackend(DesktopFlowTestingLib, ZulipTestCase): encrypted_api_key = query_params["otp_encrypted_api_key"][0] hamlet_api_keys = get_all_api_keys(self.example_user("hamlet")) self.assertIn(otp_decrypt_api_key(encrypted_api_key, mobile_flow_otp), hamlet_api_keys) - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) self.assertIn("Zulip on Android", mail.outbox[0].body) @override_settings(SEND_LOGIN_EMAILS=True) @@ -4944,7 +4944,7 @@ class ZulipLDAPTestCase(ZulipTestCase): class TestLDAP(ZulipLDAPTestCase): def test_generate_dev_ldap_dir(self) -> None: ldap_dir = generate_dev_ldap_dir("A", 10) - self.assertEqual(len(ldap_dir), 10) + self.assert_length(ldap_dir, 10) regex = re.compile( r"(uid\=)+[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+(\,ou\=users\,dc\=zulip\,dc\=com)" ) @@ -4956,14 +4956,14 @@ class TestLDAP(ZulipLDAPTestCase): ) ldap_dir = generate_dev_ldap_dir("b", 9) - self.assertEqual(len(ldap_dir), 9) + self.assert_length(ldap_dir, 9) regex = re.compile(r"(uid\=)+[a-zA-Z0-9_.+-]+(\,ou\=users\,dc\=zulip\,dc\=com)") for key, value in ldap_dir.items(): self.assertTrue(regex.match(key)) self.assertCountEqual(list(value.keys()), [*common_attrs, "uid", "jpegPhoto"]) ldap_dir = generate_dev_ldap_dir("c", 8) - self.assertEqual(len(ldap_dir), 8) + self.assert_length(ldap_dir, 8) regex = re.compile(r"(uid\=)+[a-zA-Z0-9_.+-]+(\,ou\=users\,dc\=zulip\,dc\=com)") for key, value in ldap_dir.items(): self.assertTrue(regex.match(key)) @@ -5754,7 +5754,7 @@ class TestQueryLDAP(ZulipLDAPTestCase): } ): values = query_ldap(self.example_email("hamlet")) - self.assertEqual(len(values), 4) + self.assert_length(values, 4) self.assertIn("full_name: King Hamlet", values) self.assertIn("avatar: (An avatar image file)", values) self.assertIn("custom_profile_field__birthday: 1900-09-08", values) @@ -5766,7 +5766,7 @@ class TestQueryLDAP(ZulipLDAPTestCase): # This will look up the user by email in our test dictionary, # should successfully find hamlet's LDAP entry. values = query_ldap(self.example_email("hamlet")) - self.assertEqual(len(values), 2) + self.assert_length(values, 2) self.assertIn("full_name: King Hamlet", values) self.assertIn("email: hamlet@zulip.com", values) diff --git a/zerver/tests/test_bots.py b/zerver/tests/test_bots.py index e65dd9d1a2..3e22265693 100644 --- a/zerver/tests/test_bots.py +++ b/zerver/tests/test_bots.py @@ -415,10 +415,10 @@ class BotTest(ZulipTestCase, UploadSerializeMixin): # No notification message event or invitation email is sent because of bot. msg_event = [e for e in events_bot if e["event"]["type"] == "message"] self.assert_length(msg_event, 0) - self.assertEqual(len(events_bot), len(events) - 1) + self.assert_length(events_bot, len(events) - 1) # Test runner automatically redirects all sent email to a dummy 'outbox'. - self.assertEqual(len(mail.outbox), 0) + self.assert_length(mail.outbox, 0) def test_add_bot_with_default_sending_stream_private_allowed(self) -> None: self.login("hamlet") diff --git a/zerver/tests/test_cache.py b/zerver/tests/test_cache.py index 7b62a059f2..4cee235494 100644 --- a/zerver/tests/test_cache.py +++ b/zerver/tests/test_cache.py @@ -35,7 +35,7 @@ class AppsTest(ZulipTestCase): flush_cache(Mock()) mock.assert_called_once() self.assertEqual(m.output, ["INFO:root:Clearing memcached cache after migrations"]) - self.assertEqual(len(m.output), 1) + self.assert_length(m.output, 1) class CacheKeyValidationTest(ZulipTestCase): @@ -91,7 +91,7 @@ class CacheWithKeyDecoratorTest(ZulipTestCase): with queries_captured() as queries: result = get_user_function_with_bad_cache_keys(hamlet.id) - self.assertEqual(len(m.output), 1) + self.assert_length(m.output, 1) self.assertEqual(result, hamlet) self.assert_length(queries, 1) mock_set.assert_not_called() @@ -110,7 +110,7 @@ class CacheWithKeyDecoratorTest(ZulipTestCase): with queries_captured() as queries: result = get_user_function_with_bad_cache_keys(hamlet.id) - self.assertEqual(len(m.output), 1) + self.assert_length(m.output, 1) self.assertEqual(result, hamlet) self.assert_length(queries, 1) mock_set.assert_not_called() @@ -198,7 +198,7 @@ class GetCacheWithKeyDecoratorTest(ZulipTestCase): with self.assertLogs(level="WARNING") as m: with self.assertRaises(NotFoundInCache): get_user_function_with_bad_cache_keys(hamlet.id) - self.assertEqual(len(m.output), 1) + self.assert_length(m.output, 1) class SafeCacheFunctionsTest(ZulipTestCase): @@ -222,7 +222,7 @@ class SafeCacheFunctionsTest(ZulipTestCase): "WARNING:root:Invalid cache key used: ['SafeFunctionsTest:\\nbadkey1', 'SafeFunctionsTest:\\nbadkey2']", m.output[0], ) - self.assertEqual(len(m.output), 1) + self.assert_length(m.output, 1) with self.assertLogs(level="WARNING") as m: result = safe_cache_get_many(list(items.keys())) @@ -231,7 +231,7 @@ class SafeCacheFunctionsTest(ZulipTestCase): "WARNING:root:Invalid cache key used: ['SafeFunctionsTest:\\nbadkey1', 'SafeFunctionsTest:\\nbadkey2']", m.output[0], ) - self.assertEqual(len(m.output), 1) + self.assert_length(m.output, 1) def test_safe_cache_functions_with_good_and_bad_keys(self) -> None: bad_items = {"SafeFunctionsTest:\nbadkey1": 1, "SafeFunctionsTest:\nbadkey2": 2} @@ -244,7 +244,7 @@ class SafeCacheFunctionsTest(ZulipTestCase): "WARNING:root:Invalid cache key used: ['SafeFunctionsTest:\\nbadkey1', 'SafeFunctionsTest:\\nbadkey2']", m.output[0], ) - self.assertEqual(len(m.output), 1) + self.assert_length(m.output, 1) with self.assertLogs(level="WARNING") as m: result = safe_cache_get_many(list(items.keys())) @@ -253,7 +253,7 @@ class SafeCacheFunctionsTest(ZulipTestCase): "WARNING:root:Invalid cache key used: ['SafeFunctionsTest:\\nbadkey1', 'SafeFunctionsTest:\\nbadkey2']", m.output[0], ) - self.assertEqual(len(m.output), 1) + self.assert_length(m.output, 1) class BotCacheKeyTest(ZulipTestCase): diff --git a/zerver/tests/test_custom_profile_data.py b/zerver/tests/test_custom_profile_data.py index 657a14f3d7..f82fc51ab0 100644 --- a/zerver/tests/test_custom_profile_data.py +++ b/zerver/tests/test_custom_profile_data.py @@ -725,7 +725,7 @@ class ListCustomProfileFieldTest(CustomProfileFieldTestCase): self.assert_json_success(result) self.assertEqual(200, result.status_code) content = result.json() - self.assertEqual(len(content["custom_fields"]), self.original_count) + self.assert_length(content["custom_fields"], self.original_count) def test_list_order(self) -> None: self.login("iago") @@ -753,7 +753,7 @@ class ListCustomProfileFieldTest(CustomProfileFieldTestCase): "/json/users", {"client_gravatar": "false", "include_custom_profile_fields": "true"} ) - self.assertEqual(len(queries), 4) + self.assert_length(queries, 4) self.assertEqual(response.status_code, 200) raw_users_data = response.json()["members"] diff --git a/zerver/tests/test_email_change.py b/zerver/tests/test_email_change.py index 6c5d3fc7d6..c7293b40c0 100644 --- a/zerver/tests/test_email_change.py +++ b/zerver/tests/test_email_change.py @@ -101,9 +101,9 @@ class EmailChangeTestCase(ZulipTestCase): data = {"email": "hamlet-new@zulip.com"} self.login("hamlet") url = "/json/settings" - self.assertEqual(len(mail.outbox), 0) + self.assert_length(mail.outbox, 0) result = self.client_patch(url, data) - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) self.assert_in_success_response(["Check your email for a confirmation link."], result) email_message = mail.outbox[0] self.assertEqual( @@ -141,7 +141,7 @@ class EmailChangeTestCase(ZulipTestCase): ) url = "/json/settings" result = self.client_patch(url, data) - self.assertEqual(len(mail.outbox), 0) + self.assert_length(mail.outbox, 0) self.assertEqual(result.status_code, 400) self.assert_in_response("Email address changes are disabled in this organization.", result) # Realm admins can change their email address even setting is disabled. @@ -158,7 +158,7 @@ class EmailChangeTestCase(ZulipTestCase): url = "/json/settings" result = self.client_patch(url, data) - self.assertEqual(len(mail.outbox), 0) + self.assert_length(mail.outbox, 0) self.assertEqual(result.status_code, 400) self.assert_in_response("Already has an account", result) @@ -167,9 +167,9 @@ class EmailChangeTestCase(ZulipTestCase): user_profile = self.example_user("hamlet") self.login_user(user_profile) url = "/json/settings" - self.assertEqual(len(mail.outbox), 0) + self.assert_length(mail.outbox, 0) result = self.client_patch(url, data) - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) self.assert_in_success_response(["Check your email for a confirmation link."], result) email_message = mail.outbox[0] self.assertEqual( diff --git a/zerver/tests/test_email_mirror.py b/zerver/tests/test_email_mirror.py index e1bfaae0cd..3b10691285 100644 --- a/zerver/tests/test_email_mirror.py +++ b/zerver/tests/test_email_mirror.py @@ -141,7 +141,7 @@ class TestEncodeDecode(ZulipTestCase): parts = msg_string.split("+") # Stream name should be completely stripped to '', so msg_string # should only have the email_token in it. - self.assertEqual(len(parts), 1) + self.assert_length(parts, 1) # Correctly decode the resulting address that doesn't have the stream name: token, show_sender = decode_email_address(email_address) diff --git a/zerver/tests/test_email_notifications.py b/zerver/tests/test_email_notifications.py index 45eeaf9148..83979ee652 100644 --- a/zerver/tests/test_email_notifications.py +++ b/zerver/tests/test_email_notifications.py @@ -41,10 +41,10 @@ class TestCustomEmails(ZulipTestCase): "dry_run": False, }, ) - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) msg = mail.outbox[0] self.assertEqual(msg.subject, email_subject) - self.assertEqual(len(msg.reply_to), 1) + self.assert_length(msg.reply_to, 1) self.assertEqual(msg.reply_to[0], reply_to) self.assertNotIn("{% block content %}", msg.body) @@ -60,7 +60,7 @@ class TestCustomEmails(ZulipTestCase): "dry_run": False, }, ) - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) msg = mail.outbox[0] self.assertEqual(msg.subject, "Test subject") self.assertFalse(msg.reply_to) @@ -145,7 +145,7 @@ class TestCustomEmails(ZulipTestCase): "dry_run": False, }, ) - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) self.assertIn(admin_user.delivery_email, mail.outbox[0].to[0]) def test_send_custom_email_dry_run(self) -> None: @@ -165,7 +165,7 @@ class TestCustomEmails(ZulipTestCase): "dry_run": True, }, ) - self.assertEqual(len(mail.outbox), 0) + self.assert_length(mail.outbox, 0) class TestFollowupEmails(ZulipTestCase): @@ -217,7 +217,7 @@ class TestFollowupEmails(ZulipTestCase): user = UserProfile.objects.get(delivery_email="newuser_email_as_uid@zulip.com") scheduled_emails = ScheduledEmail.objects.filter(users=user) - self.assertEqual(len(scheduled_emails), 2) + self.assert_length(scheduled_emails, 2) email_data = orjson.loads(scheduled_emails[0].data) self.assertEqual(email_data["context"]["ldap"], True) self.assertEqual( @@ -243,7 +243,7 @@ class TestFollowupEmails(ZulipTestCase): user = UserProfile.objects.get(delivery_email="newuser@zulip.com") scheduled_emails = ScheduledEmail.objects.filter(users=user) - self.assertEqual(len(scheduled_emails), 2) + self.assert_length(scheduled_emails, 2) email_data = orjson.loads(scheduled_emails[0].data) self.assertEqual(email_data["context"]["ldap"], True) self.assertEqual(email_data["context"]["ldap_username"], "newuser") @@ -266,7 +266,7 @@ class TestFollowupEmails(ZulipTestCase): user = UserProfile.objects.get(delivery_email="newuser_email@zulip.com") scheduled_emails = ScheduledEmail.objects.filter(users=user) - self.assertEqual(len(scheduled_emails), 2) + self.assert_length(scheduled_emails, 2) email_data = orjson.loads(scheduled_emails[0].data) self.assertEqual(email_data["context"]["ldap"], True) self.assertEqual(email_data["context"]["ldap_username"], "newuser_with_email") @@ -293,7 +293,7 @@ class TestFollowupEmails(ZulipTestCase): enqueue_welcome_emails(cordelia) scheduled_emails = ScheduledEmail.objects.filter(users=cordelia) # Cordelia has account in more than 1 realm so day2 email should not be sent - self.assertEqual(len(scheduled_emails), 1) + self.assert_length(scheduled_emails, 1) email_data = orjson.loads(scheduled_emails[0].data) self.assertEqual(email_data["template_prefix"], "zerver/emails/followup_day1") @@ -332,13 +332,13 @@ class TestMissedMessages(ZulipTestCase): reply_to_emails = ["noreply@testserver"] msg = mail.outbox[0] from_email = str(Address(display_name="Zulip notifications", addr_spec=FromAddress.NOREPLY)) - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) if send_as_user: from_email = f'"{othello.full_name}" <{othello.email}>' self.assertEqual(self.email_envelope_from(msg), settings.NOREPLY_EMAIL_ADDRESS) self.assertEqual(self.email_display_from(msg), from_email) self.assertEqual(msg.subject, email_subject) - self.assertEqual(len(msg.reply_to), 1) + self.assert_length(msg.reply_to, 1) self.assertIn(msg.reply_to[0], reply_to_emails) if verify_html_body: for text in verify_body_include: @@ -642,7 +642,7 @@ class TestMissedMessages(ZulipTestCase): ) self.assert_json_success(result) handle_missedmessage_emails(hamlet.id, [{"message_id": msg_id}]) - self.assertEqual(len(mail.outbox), 0) + self.assert_length(mail.outbox, 0) def _deleted_message_in_personal_missed_stream_messages(self, send_as_user: bool) -> None: msg_id = self.send_personal_message( @@ -658,7 +658,7 @@ class TestMissedMessages(ZulipTestCase): ) self.assert_json_success(result) handle_missedmessage_emails(hamlet.id, [{"message_id": msg_id}]) - self.assertEqual(len(mail.outbox), 0) + self.assert_length(mail.outbox, 0) def _deleted_message_in_huddle_missed_stream_messages(self, send_as_user: bool) -> None: msg_id = self.send_huddle_message( @@ -678,9 +678,9 @@ class TestMissedMessages(ZulipTestCase): ) self.assert_json_success(result) handle_missedmessage_emails(hamlet.id, [{"message_id": msg_id}]) - self.assertEqual(len(mail.outbox), 0) + self.assert_length(mail.outbox, 0) handle_missedmessage_emails(iago.id, [{"message_id": msg_id}]) - self.assertEqual(len(mail.outbox), 0) + self.assert_length(mail.outbox, 0) def test_realm_name_in_notifications(self) -> None: # Test with realm_name_in_notifications for hamlet disabled. @@ -956,7 +956,7 @@ class TestMissedMessages(ZulipTestCase): {"message_id": msg_id_2}, ], ) - self.assertEqual(len(mail.outbox), 2) + self.assert_length(mail.outbox, 2) email_subject = "PMs with Othello, the Moor of Venice" self.assertEqual(mail.outbox[0].subject, email_subject) email_subject = "PMs with Iago" @@ -974,7 +974,7 @@ class TestMissedMessages(ZulipTestCase): {"message_id": msg_id_2, "trigger": "stream_email_notify"}, ], ) - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) email_subject = "#Denmark > test" self.assertEqual(mail.outbox[0].subject, email_subject) @@ -993,7 +993,7 @@ class TestMissedMessages(ZulipTestCase): {"message_id": msg_id_2, "trigger": "mentioned"}, ], ) - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) email_subject = "#Denmark > test" self.assertEqual(mail.outbox[0].subject, email_subject) @@ -1021,7 +1021,7 @@ class TestMissedMessages(ZulipTestCase): ], ) - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) self.assertEqual(mail.outbox[0].subject, "#private_stream > test") # email subject email_text = mail.outbox[0].message().as_string() self.assertNotIn("Before subscribing", email_text) @@ -1049,7 +1049,7 @@ class TestMissedMessages(ZulipTestCase): {"message_id": msg_id_3, "trigger": "stream_email_notify"}, ], ) - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) email_subject = "#Denmark > test" self.assertEqual(mail.outbox[0].subject, email_subject) @@ -1068,7 +1068,7 @@ class TestMissedMessages(ZulipTestCase): {"message_id": msg_id_2, "trigger": "stream_email_notify"}, ], ) - self.assertEqual(len(mail.outbox), 2) + self.assert_length(mail.outbox, 2) email_subjects = {mail.outbox[0].subject, mail.outbox[1].subject} valid_email_subjects = {"#Denmark > test", "#Denmark > test2"} self.assertEqual(email_subjects, valid_email_subjects) diff --git a/zerver/tests/test_event_queue.py b/zerver/tests/test_event_queue.py index ae72ee648a..fa5a2ab1bc 100644 --- a/zerver/tests/test_event_queue.py +++ b/zerver/tests/test_event_queue.py @@ -319,7 +319,7 @@ class MissedMessageNotificationsTest(ZulipTestCase): self.send_stream_message(cordelia, stream_name) - self.assertEqual(len(client.event_queue.contents()), 1) + self.assert_length(client.event_queue.contents(), 1) # This next line of code should silently succeed and basically do # nothing under the covers. This test is here to prevent a bug @@ -826,7 +826,7 @@ class PruneInternalDataTest(ZulipTestCase): self.send_personal_message(self.example_user("iago"), user_profile) events = client.event_queue.contents() - self.assertEqual(len(events), 3) + self.assert_length(events, 3) self.assertFalse("internal_data" in events[0]) self.assertFalse("internal_data" in events[1]) self.assertFalse("internal_data" in events[2]) diff --git a/zerver/tests/test_event_system.py b/zerver/tests/test_event_system.py index 47c6ea208f..d906158e87 100644 --- a/zerver/tests/test_event_system.py +++ b/zerver/tests/test_event_system.py @@ -335,7 +335,7 @@ class GetEventsTest(ZulipTestCase): ) recipient_events = orjson.loads(recipient_result.content)["events"] self.assert_json_success(recipient_result) - self.assertEqual(len(recipient_events), 2) + self.assert_length(recipient_events, 2) self.assertEqual(recipient_events[0]["type"], "message") self.assertEqual(recipient_events[0]["message"]["sender_email"], email) self.assertTrue("local_message_id" not in recipient_events[0]) @@ -574,7 +574,7 @@ class ClientDescriptorsTest(ZulipTestCase): users=[], ) - self.assertEqual(len(client_info), 1) + self.assert_length(client_info, 1) dct = client_info[client.event_queue.id] self.assertEqual(dct["client"].apply_markdown, True) @@ -629,7 +629,7 @@ class ClientDescriptorsTest(ZulipTestCase): ], ) - self.assertEqual(len(client_info), 0) + self.assert_length(client_info, 0) client_info = get_client_info_for_message_event( message_event, @@ -638,7 +638,7 @@ class ClientDescriptorsTest(ZulipTestCase): dict(id=hamlet.id, flags=["mentioned"]), ], ) - self.assertEqual(len(client_info), 1) + self.assert_length(client_info, 1) dct = client_info[client.event_queue.id] self.assertEqual(dct["client"].apply_markdown, apply_markdown) @@ -877,7 +877,7 @@ class RestartEventsTest(ZulipTestCase): # may decide to write a deeper test in the future # that exercises the finish_handler. virtual_events = client.event_queue.virtual_events - self.assertEqual(len(virtual_events), 1) + self.assert_length(virtual_events, 1) restart_event = virtual_events["restart"] check_restart_event("restart_event", restart_event) diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py index 5d1ffdd949..8c0b8ae2c7 100644 --- a/zerver/tests/test_events.py +++ b/zerver/tests/test_events.py @@ -286,7 +286,7 @@ class BaseAction(ZulipTestCase): "result": "success", } validate_against_openapi_schema(content, "/events", "get", "200", display_brief_error=True) - self.assertEqual(len(events), num_events) + self.assert_length(events, num_events) initial_state = copy.deepcopy(hybrid_state) post_process_state(self.user_profile, initial_state, notification_settings_null) before = orjson.dumps(initial_state) @@ -2139,7 +2139,7 @@ class SubscribeActionTest(BaseAction): action, include_subscribers=include_subscribers, include_streams=False, num_events=2 ) check_subscription_remove("events[0]", events[0]) - self.assertEqual(len(events[0]["subscriptions"]), 1) + self.assert_length(events[0]["subscriptions"], 1) self.assertEqual( events[0]["subscriptions"][0]["name"], "test_stream", diff --git a/zerver/tests/test_gitter_importer.py b/zerver/tests/test_gitter_importer.py index ac4045d7b8..9cf9243eb1 100644 --- a/zerver/tests/test_gitter_importer.py +++ b/zerver/tests/test_gitter_importer.py @@ -42,7 +42,7 @@ class GitterImporter(ZulipTestCase): self.assertIn("username2@users.noreply.github.com", exported_user_email) # test stream - self.assertEqual(len(realm["zerver_stream"]), 1) + self.assert_length(realm["zerver_stream"], 1) self.assertEqual(realm["zerver_stream"][0]["name"], "from gitter") self.assertEqual(realm["zerver_stream"][0]["deactivated"], False) self.assertEqual(realm["zerver_stream"][0]["realm"], realm["zerver_realm"][0]["id"]) @@ -62,7 +62,7 @@ class GitterImporter(ZulipTestCase): ) self.assertEqual({0, 1}, exported_subscription_userprofile) exported_subscription_recipient = self.get_set(realm["zerver_subscription"], "recipient") - self.assertEqual(len(exported_subscription_recipient), 3) + self.assert_length(exported_subscription_recipient, 3) self.assertIn(realm["zerver_subscription"][1]["recipient"], exported_recipient_id) messages = read_file("messages-000001.json") diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.py index 70c4b83557..f2c271fbb3 100644 --- a/zerver/tests/test_home.py +++ b/zerver/tests/test_home.py @@ -607,7 +607,7 @@ class HomeTest(ZulipTestCase): self.assertNotIn(defunct_user.id, active_ids) cross_bots = page_params["cross_realm_bots"] - self.assertEqual(len(cross_bots), 3) + self.assert_length(cross_bots, 3) cross_bots.sort(key=lambda d: d["email"]) for cross_bot in cross_bots: # These are either nondeterministic or boring diff --git a/zerver/tests/test_hotspots.py b/zerver/tests/test_hotspots.py index 747bdc12d9..0927a54da7 100644 --- a/zerver/tests/test_hotspots.py +++ b/zerver/tests/test_hotspots.py @@ -15,14 +15,14 @@ class TestGetNextHotspots(ZulipTestCase): def test_first_hotspot(self) -> None: hotspots = get_next_hotspots(self.user) - self.assertEqual(len(hotspots), 1) + self.assert_length(hotspots, 1) self.assertEqual(hotspots[0]["name"], "intro_reply") def test_some_done_some_not(self) -> None: do_mark_hotspot_as_read(self.user, "intro_reply") do_mark_hotspot_as_read(self.user, "intro_compose") hotspots = get_next_hotspots(self.user) - self.assertEqual(len(hotspots), 1) + self.assert_length(hotspots, 1) self.assertEqual(hotspots[0]["name"], "intro_streams") def test_all_intro_hotspots_done(self) -> None: @@ -35,7 +35,7 @@ class TestGetNextHotspots(ZulipTestCase): def test_send_all(self) -> None: with self.settings(DEVELOPMENT=True, ALWAYS_SEND_ALL_HOTSPOTS=True): - self.assertEqual(len(ALL_HOTSPOTS), len(get_next_hotspots(self.user))) + self.assert_length(ALL_HOTSPOTS, len(get_next_hotspots(self.user))) def test_tutorial_disabled(self) -> None: with self.settings(TUTORIAL_ENABLED=False): diff --git a/zerver/tests/test_i18n.py b/zerver/tests/test_i18n.py index dc11eed640..b2e4272967 100644 --- a/zerver/tests/test_i18n.py +++ b/zerver/tests/test_i18n.py @@ -170,5 +170,5 @@ class FrontendRegexTestCase(ZulipTestCase): for input_text, expected in data: result = command.extract_strings(input_text) - self.assertEqual(len(result), 1) + self.assert_length(result, 1) self.assertEqual(result[0], expected) diff --git a/zerver/tests/test_import_export.py b/zerver/tests/test_import_export.py index 2a30abf780..7c22004c4d 100644 --- a/zerver/tests/test_import_export.py +++ b/zerver/tests/test_import_export.py @@ -107,7 +107,7 @@ class QueryUtilTest(ZulipTestCase): all_row_ids.append(row.id) self.assertEqual(all_row_ids, sorted(all_row_ids)) - self.assertEqual(len(all_msg_ids), len(Message.objects.all())) + self.assert_length(all_msg_ids, len(Message.objects.all())) # Now just search for cordelia/hamlet. Note that we don't really # need the order_by here, but it should be harmless. @@ -169,9 +169,9 @@ class QueryUtilTest(ZulipTestCase): id_collector=all_msg_ids, chunk_size=11, # use a different size each time ) - self.assertEqual(len(all_msg_ids), 0) # until we actually use the iterator + self.assert_length(all_msg_ids, 0) # until we actually use the iterator list(chunker) # exhaust the iterator - self.assertEqual(len(all_msg_ids), len(Message.objects.all())) + self.assert_length(all_msg_ids, len(Message.objects.all())) # Verify that we can just get the first chunk with a next() call. queries = [ @@ -184,8 +184,8 @@ class QueryUtilTest(ZulipTestCase): chunk_size=10, # use a different size each time ) first_chunk = next(chunker) - self.assertEqual(len(first_chunk), 10) - self.assertEqual(len(all_msg_ids), 10) + self.assert_length(first_chunk, 10) + self.assert_length(all_msg_ids, 10) expected_msg = Message.objects.all()[0:10][5] actual_msg = first_chunk[5] self.assertEqual(actual_msg.content, expected_msg.content) @@ -314,7 +314,7 @@ class ImportExportTest(ZulipTestCase): full_data = self._export_realm(realm) data = full_data["attachment"] - self.assertEqual(len(data["zerver_attachment"]), 1) + self.assert_length(data["zerver_attachment"], 1) record = data["zerver_attachment"][0] self.assertEqual(record["path_id"], path_id) @@ -385,7 +385,7 @@ class ImportExportTest(ZulipTestCase): full_data = self._export_realm(realm) data = full_data["attachment"] - self.assertEqual(len(data["zerver_attachment"]), 1) + self.assert_length(data["zerver_attachment"], 1) record = data["zerver_attachment"][0] self.assertEqual(record["path_id"], attachment_path_id) @@ -467,8 +467,8 @@ class ImportExportTest(ZulipTestCase): realm_emoji.save() data = full_data["realm"] - self.assertEqual(len(data["zerver_userprofile_crossrealm"]), 3) - self.assertEqual(len(data["zerver_userprofile_mirrordummy"]), 0) + self.assert_length(data["zerver_userprofile_crossrealm"], 3) + self.assert_length(data["zerver_userprofile_mirrordummy"], 0) exported_user_emails = self.get_set(data["zerver_userprofile"], "delivery_email") self.assertIn(self.example_email("cordelia"), exported_user_emails) @@ -485,7 +485,7 @@ class ImportExportTest(ZulipTestCase): # We set up 4 alert words for Hamlet, Cordelia, etc. # when we populate the test database. num_zulip_users = 10 - self.assertEqual(len(exported_alert_words), num_zulip_users * 4) + self.assert_length(exported_alert_words, num_zulip_users * 4) self.assertIn("robotics", {r["word"] for r in exported_alert_words}) @@ -627,8 +627,8 @@ class ImportExportTest(ZulipTestCase): data = full_data["realm"] - self.assertEqual(len(data["zerver_userprofile_crossrealm"]), 3) - self.assertEqual(len(data["zerver_userprofile_mirrordummy"]), 0) + self.assert_length(data["zerver_userprofile_crossrealm"], 3) + self.assert_length(data["zerver_userprofile_mirrordummy"], 0) exported_user_emails = self.get_set(data["zerver_userprofile"], "delivery_email") self.assertIn(self.example_email("cordelia"), exported_user_emails) @@ -657,7 +657,7 @@ class ImportExportTest(ZulipTestCase): user_profile__in=[self.example_user("iago"), self.example_user("hamlet")] ) um = exported_usermessages[0] - self.assertEqual(len(data["zerver_usermessage"]), len(exported_usermessages)) + self.assert_length(data["zerver_usermessage"], len(exported_usermessages)) exported_um = self.find_by_id(data["zerver_usermessage"], um.id) self.assertEqual(exported_um["message"], um.message_id) self.assertEqual(exported_um["user_profile"], um.user_profile_id) @@ -1171,7 +1171,7 @@ class ImportExportTest(ZulipTestCase): # Test attachments uploaded_file = Attachment.objects.get(realm=imported_realm) - self.assertEqual(len(b"zulip!"), uploaded_file.size) + self.assert_length(b"zulip!", uploaded_file.size) attachment_file_path = os.path.join( settings.LOCAL_UPLOADS_DIR, "files", uploaded_file.path_id @@ -1236,7 +1236,7 @@ class ImportExportTest(ZulipTestCase): # Test attachments uploaded_file = Attachment.objects.get(realm=imported_realm) - self.assertEqual(len(b"zulip!"), uploaded_file.size) + self.assert_length(b"zulip!", uploaded_file.size) attachment_content = uploads_bucket.Object(uploaded_file.path_id).get()["Body"].read() self.assertEqual(b"zulip!", attachment_content) diff --git a/zerver/tests/test_markdown.py b/zerver/tests/test_markdown.py index bea8815a41..9a5b58d8f0 100644 --- a/zerver/tests/test_markdown.py +++ b/zerver/tests/test_markdown.py @@ -426,7 +426,7 @@ class MarkdownTest(ZulipTestCase): for name, test in format_tests.items(): with self.subTest(markdown_test_case=name): # Check that there aren't any unexpected keys as those are often typos - self.assertEqual(len(set(test.keys()) - valid_keys), 0) + self.assert_length(set(test.keys()) - valid_keys, 0) # Ignore tests if specified if test.get("ignore", False): continue # nocoverage @@ -1344,14 +1344,14 @@ class MarkdownTest(ZulipTestCase): converted_topic = topic_links(realm.id, content) if should_have_converted: self.assertTrue("https://trac.example.com" in converted) - self.assertEqual(len(converted_topic), 1) + self.assert_length(converted_topic, 1) self.assertEqual( converted_topic[0], {"url": "https://trac.example.com/ticket/123", "text": "#123"}, ) else: self.assertTrue("https://trac.example.com" not in converted) - self.assertEqual(len(converted_topic), 0) + self.assert_length(converted_topic, 0) assert_conversion("Hello #123 World") assert_conversion("Hello #123World", False) diff --git a/zerver/tests/test_mattermost_importer.py b/zerver/tests/test_mattermost_importer.py index ef8e9cd658..8bb25ad20f 100644 --- a/zerver/tests/test_mattermost_importer.py +++ b/zerver/tests/test_mattermost_importer.py @@ -34,28 +34,28 @@ class MatterMostImporter(ZulipTestCase): def test_mattermost_data_file_to_dict(self) -> None: fixture_file_name = self.fixture_file_name("export.json", "mattermost_fixtures") mattermost_data = mattermost_data_file_to_dict(fixture_file_name) - self.assertEqual(len(mattermost_data), 7) + self.assert_length(mattermost_data, 7) self.assertEqual(mattermost_data["version"], [1]) - self.assertEqual(len(mattermost_data["team"]), 2) + self.assert_length(mattermost_data["team"], 2) self.assertEqual(mattermost_data["team"][0]["name"], "gryffindor") - self.assertEqual(len(mattermost_data["channel"]), 5) + self.assert_length(mattermost_data["channel"], 5) self.assertEqual(mattermost_data["channel"][0]["name"], "gryffindor-common-room") self.assertEqual(mattermost_data["channel"][0]["team"], "gryffindor") - self.assertEqual(len(mattermost_data["user"]), 5) + self.assert_length(mattermost_data["user"], 5) self.assertEqual(mattermost_data["user"][1]["username"], "harry") - self.assertEqual(len(mattermost_data["user"][1]["teams"]), 1) + self.assert_length(mattermost_data["user"][1]["teams"], 1) - self.assertEqual(len(mattermost_data["post"]["channel_post"]), 20) + self.assert_length(mattermost_data["post"]["channel_post"], 20) self.assertEqual(mattermost_data["post"]["channel_post"][0]["team"], "gryffindor") self.assertEqual(mattermost_data["post"]["channel_post"][0]["channel"], "dumbledores-army") self.assertEqual(mattermost_data["post"]["channel_post"][0]["user"], "harry") - self.assertEqual(len(mattermost_data["post"]["channel_post"][0]["replies"]), 1) + self.assert_length(mattermost_data["post"]["channel_post"][0]["replies"], 1) - self.assertEqual(len(mattermost_data["emoji"]), 2) + self.assert_length(mattermost_data["emoji"], 2) self.assertEqual(mattermost_data["emoji"][0]["name"], "peerdium") fixture_file_name = self.fixture_file_name( @@ -63,7 +63,7 @@ class MatterMostImporter(ZulipTestCase): ) mattermost_data = mattermost_data_file_to_dict(fixture_file_name) - self.assertEqual(len(mattermost_data["post"]["channel_post"]), 4) + self.assert_length(mattermost_data["post"]["channel_post"], 4) self.assertEqual(mattermost_data["post"]["channel_post"][0]["team"], "gryffindor") self.assertEqual( mattermost_data["post"]["channel_post"][0]["channel"], "gryffindor-common-room" @@ -71,7 +71,7 @@ class MatterMostImporter(ZulipTestCase): self.assertEqual(mattermost_data["post"]["channel_post"][0]["user"], "ron") self.assertEqual(mattermost_data["post"]["channel_post"][0]["replies"], None) - self.assertEqual(len(mattermost_data["post"]["direct_post"]), 7) + self.assert_length(mattermost_data["post"]["direct_post"], 7) self.assertEqual(mattermost_data["post"]["direct_post"][0]["user"], "ron") self.assertEqual(mattermost_data["post"]["direct_post"][0]["replies"], None) self.assertEqual(mattermost_data["post"]["direct_post"][0]["message"], "hey harry") @@ -137,7 +137,7 @@ class MatterMostImporter(ZulipTestCase): team_name = "gryffindor" user_handler = UserHandler() convert_user_data(user_handler, user_id_mapper, username_to_user, realm_id, team_name) - self.assertEqual(len(user_handler.get_all_users()), 2) + self.assert_length(user_handler.get_all_users(), 2) self.assertTrue(user_id_mapper.has("harry")) self.assertTrue(user_id_mapper.has("ron")) self.assertEqual( @@ -150,7 +150,7 @@ class MatterMostImporter(ZulipTestCase): team_name = "slytherin" user_handler = UserHandler() convert_user_data(user_handler, user_id_mapper, username_to_user, realm_id, team_name) - self.assertEqual(len(user_handler.get_all_users()), 3) + self.assert_length(user_handler.get_all_users(), 3) self.assertTrue(user_id_mapper.has("malfoy")) self.assertTrue(user_id_mapper.has("pansy")) self.assertTrue(user_id_mapper.has("snape")) @@ -160,13 +160,13 @@ class MatterMostImporter(ZulipTestCase): label_mirror_dummy_users(2, team_name, mattermost_data, username_to_user) user_handler = UserHandler() convert_user_data(user_handler, user_id_mapper, username_to_user, realm_id, team_name) - self.assertEqual(len(user_handler.get_all_users()), 3) + self.assert_length(user_handler.get_all_users(), 3) self.assertTrue(user_id_mapper.has("snape")) team_name = "slytherin" user_handler = UserHandler() convert_user_data(user_handler, user_id_mapper, username_to_user, realm_id, team_name) - self.assertEqual(len(user_handler.get_all_users()), 3) + self.assert_length(user_handler.get_all_users(), 3) def test_convert_channel_data(self) -> None: fixture_file_name = self.fixture_file_name("export.json", "mattermost_fixtures") @@ -198,7 +198,7 @@ class MatterMostImporter(ZulipTestCase): team_name=team_name, ) - self.assertEqual(len(zerver_stream), 3) + self.assert_length(zerver_stream, 3) self.assertEqual(zerver_stream[0]["name"], "Gryffindor common room") self.assertEqual(zerver_stream[0]["invite_only"], False) @@ -333,7 +333,7 @@ class MatterMostImporter(ZulipTestCase): team_name=team_name, ) - self.assertEqual(len(zerver_huddle), 1) + self.assert_length(zerver_huddle, 1) huddle_members = mattermost_data["direct_channel"][1]["members"] huddle_name = generate_huddle_name(huddle_members) @@ -355,7 +355,7 @@ class MatterMostImporter(ZulipTestCase): output_dir=output_dir, ) - self.assertEqual(len(zerver_realm_emoji), 2) + self.assert_length(zerver_realm_emoji, 2) self.assertEqual(zerver_realm_emoji[0]["file_name"], "peerdium") self.assertEqual(zerver_realm_emoji[0]["realm"], 3) self.assertEqual(zerver_realm_emoji[0]["deactivated"], False) @@ -535,7 +535,7 @@ class MatterMostImporter(ZulipTestCase): smile_emoji_code = name_to_codepoint["smile"] world_map_emoji_code = name_to_codepoint["world_map"] - self.assertEqual(len(total_reactions), 4) + self.assert_length(total_reactions, 4) self.assertEqual( self.get_set(total_reactions, "reaction_type"), {Reaction.REALM_EMOJI, Reaction.UNICODE_EMOJI}, @@ -548,8 +548,8 @@ class MatterMostImporter(ZulipTestCase): {tick_emoji_code, smile_emoji_code, world_map_emoji_code}, ) self.assertEqual(self.get_set(total_reactions, "user_profile"), {harry_id, ron_id}) - self.assertEqual(len(self.get_set(total_reactions, "id")), 4) - self.assertEqual(len(self.get_set(total_reactions, "message")), 1) + self.assert_length(self.get_set(total_reactions, "id"), 4) + self.assert_length(self.get_set(total_reactions, "message"), 1) def team_output_dir(self, output_dir: str, team_name: str) -> str: return os.path.join(output_dir, team_name) @@ -603,7 +603,7 @@ class MatterMostImporter(ZulipTestCase): {"harry@zulip.com", "ron@zulip.com", "snape@zulip.com"}, exported_user_emails ) - self.assertEqual(len(realm["zerver_stream"]), 3) + self.assert_length(realm["zerver_stream"], 3) exported_stream_names = self.get_set(realm["zerver_stream"], "name") self.assertEqual( exported_stream_names, @@ -614,21 +614,21 @@ class MatterMostImporter(ZulipTestCase): ) self.assertEqual(self.get_set(realm["zerver_stream"], "deactivated"), {False}) - self.assertEqual(len(realm["zerver_defaultstream"]), 0) + self.assert_length(realm["zerver_defaultstream"], 0) exported_recipient_ids = self.get_set(realm["zerver_recipient"], "id") - self.assertEqual(len(exported_recipient_ids), 6) + self.assert_length(exported_recipient_ids, 6) exported_recipient_types = self.get_set(realm["zerver_recipient"], "type") self.assertEqual(exported_recipient_types, {1, 2}) exported_recipient_type_ids = self.get_set(realm["zerver_recipient"], "type_id") - self.assertEqual(len(exported_recipient_type_ids), 3) + self.assert_length(exported_recipient_type_ids, 3) exported_subscription_userprofile = self.get_set( realm["zerver_subscription"], "user_profile" ) - self.assertEqual(len(exported_subscription_userprofile), 3) + self.assert_length(exported_subscription_userprofile, 3) exported_subscription_recipients = self.get_set(realm["zerver_subscription"], "recipient") - self.assertEqual(len(exported_subscription_recipients), 6) + self.assert_length(exported_subscription_recipients, 6) messages = self.read_file(harry_team_output_dir, "messages-000001.json") @@ -640,7 +640,7 @@ class MatterMostImporter(ZulipTestCase): exported_usermessage_userprofiles = self.get_set( messages["zerver_usermessage"], "user_profile" ) - self.assertEqual(len(exported_usermessage_userprofiles), 3) + self.assert_length(exported_usermessage_userprofiles, 3) exported_usermessage_messages = self.get_set(messages["zerver_usermessage"], "message") self.assertEqual(exported_usermessage_messages, exported_messages_id) @@ -702,7 +702,7 @@ class MatterMostImporter(ZulipTestCase): exported_user_emails, ) - self.assertEqual(len(realm["zerver_stream"]), 3) + self.assert_length(realm["zerver_stream"], 3) exported_stream_names = self.get_set(realm["zerver_stream"], "name") self.assertEqual( exported_stream_names, @@ -713,21 +713,21 @@ class MatterMostImporter(ZulipTestCase): ) self.assertEqual(self.get_set(realm["zerver_stream"], "deactivated"), {False}) - self.assertEqual(len(realm["zerver_defaultstream"]), 0) + self.assert_length(realm["zerver_defaultstream"], 0) exported_recipient_ids = self.get_set(realm["zerver_recipient"], "id") - self.assertEqual(len(exported_recipient_ids), 8) + self.assert_length(exported_recipient_ids, 8) exported_recipient_types = self.get_set(realm["zerver_recipient"], "type") self.assertEqual(exported_recipient_types, {1, 2, 3}) exported_recipient_type_ids = self.get_set(realm["zerver_recipient"], "type_id") - self.assertEqual(len(exported_recipient_type_ids), 4) + self.assert_length(exported_recipient_type_ids, 4) exported_subscription_userprofile = self.get_set( realm["zerver_subscription"], "user_profile" ) - self.assertEqual(len(exported_subscription_userprofile), 4) + self.assert_length(exported_subscription_userprofile, 4) exported_subscription_recipients = self.get_set(realm["zerver_subscription"], "recipient") - self.assertEqual(len(exported_subscription_recipients), 8) + self.assert_length(exported_subscription_recipients, 8) messages = self.read_file(harry_team_output_dir, "messages-000001.json") @@ -739,7 +739,7 @@ class MatterMostImporter(ZulipTestCase): exported_usermessage_userprofiles = self.get_set( messages["zerver_usermessage"], "user_profile" ) - self.assertEqual(len(exported_usermessage_userprofiles), 3) + self.assert_length(exported_usermessage_userprofiles, 3) exported_usermessage_messages = self.get_set(messages["zerver_usermessage"], "message") self.assertEqual(exported_usermessage_messages, exported_messages_id) @@ -754,19 +754,19 @@ class MatterMostImporter(ZulipTestCase): messages = Message.objects.filter(sender__realm=realm) for message in messages: self.assertIsNotNone(message.rendered_content) - self.assertEqual(len(messages), 11) + self.assert_length(messages, 11) stream_messages = messages.filter(recipient__type=Recipient.STREAM).order_by("date_sent") stream_recipients = stream_messages.values_list("recipient", flat=True) - self.assertEqual(len(stream_messages), 4) - self.assertEqual(len(set(stream_recipients)), 2) + self.assert_length(stream_messages, 4) + self.assert_length(set(stream_recipients), 2) self.assertEqual(stream_messages[0].sender.email, "ron@zulip.com") self.assertEqual(stream_messages[0].content, "ron joined the channel.\n\n") huddle_messages = messages.filter(recipient__type=Recipient.HUDDLE).order_by("date_sent") huddle_recipients = huddle_messages.values_list("recipient", flat=True) - self.assertEqual(len(huddle_messages), 3) - self.assertEqual(len(set(huddle_recipients)), 1) + self.assert_length(huddle_messages, 3) + self.assert_length(set(huddle_recipients), 1) self.assertEqual(huddle_messages[0].sender.email, "ginny@zulip.com") self.assertEqual(huddle_messages[0].content, "Who is going to Hogsmeade this weekend?\n\n") @@ -774,8 +774,8 @@ class MatterMostImporter(ZulipTestCase): "date_sent" ) personal_recipients = personal_messages.values_list("recipient", flat=True) - self.assertEqual(len(personal_messages), 4) - self.assertEqual(len(set(personal_recipients)), 3) + self.assert_length(personal_messages, 4) + self.assert_length(set(personal_recipients), 3) self.assertEqual(personal_messages[0].sender.email, "ron@zulip.com") self.assertEqual(personal_messages[0].content, "hey harry\n\n") diff --git a/zerver/tests/test_message_dict.py b/zerver/tests/test_message_dict.py index 054f721115..e1d1604b9a 100644 --- a/zerver/tests/test_message_dict.py +++ b/zerver/tests/test_message_dict.py @@ -182,7 +182,7 @@ class MessageDictTest(ZulipTestCase): MessageDict.post_process_dicts(objs, apply_markdown=False, client_gravatar=False) self.assert_length(queries, 7) - self.assertEqual(len(rows), num_ids) + self.assert_length(rows, num_ids) def test_applying_markdown(self) -> None: sender = self.example_user("othello") @@ -420,7 +420,7 @@ class MessageHydrationTest(ZulipTestCase): allow_edit_history=False, ) - self.assertEqual(len(messages), 2) + self.assert_length(messages, 2) for message in messages: if message["id"] == old_message_id: @@ -640,7 +640,7 @@ class SewMessageAndReactionTest(ZulipTestCase): reactions = Reaction.get_raw_db_rows(needed_ids) tied_data = sew_messages_and_reactions(messages, reactions) for data in tied_data: - self.assertEqual(len(data["reactions"]), 1) + self.assert_length(data["reactions"], 1) self.assertEqual(data["reactions"][0]["emoji_name"], "simple_smile") self.assertTrue(data["id"]) self.assertTrue(data["content"]) diff --git a/zerver/tests/test_message_edit.py b/zerver/tests/test_message_edit.py index 65e7cca43a..a8487a8ac3 100644 --- a/zerver/tests/test_message_edit.py +++ b/zerver/tests/test_message_edit.py @@ -100,14 +100,14 @@ class EditMessageTest(ZulipTestCase): MessageDict.to_dict_uncached(messages) # 1 query for realm_id per message = 3 # 1 query each for reactions & submessage for all messages = 2 - self.assertEqual(len(queries), 5) + self.assert_length(queries, 5) realm_id = 2 # Fetched from stream object # Check number of queries performed with realm_id with queries_captured() as queries: MessageDict.to_dict_uncached(messages, realm_id) # 1 query each for reactions & submessage for all messages = 2 - self.assertEqual(len(queries), 2) + self.assert_length(queries, 2) def test_save_message(self) -> None: """This is also tested by a client test, but here we can verify @@ -591,7 +591,7 @@ class EditMessageTest(ZulipTestCase): expected_entries.add("content_html_diff") i += 1 self.assertEqual(expected_entries, set(entry.keys())) - self.assertEqual(len(message_history), 6) + self.assert_length(message_history, 6) self.assertEqual(message_history[0]["prev_topic"], "topic 3") self.assertEqual(message_history[0]["topic"], "topic 4") self.assertEqual(message_history[1]["topic"], "topic 3") @@ -926,7 +926,7 @@ class EditMessageTest(ZulipTestCase): # Since edit history is being generated by do_update_message, # it's contents can vary over time; So, to keep this test # future proof, we only verify it's length. - self.assertEqual(len(orjson.loads(msg.edit_history)), len_edit_history) + self.assert_length(orjson.loads(msg.edit_history), len_edit_history) for msg_id in [id3, id4]: msg = Message.objects.get(id=msg_id) @@ -998,7 +998,7 @@ class EditMessageTest(ZulipTestCase): new_topic, msg.topic_name(), ) - self.assertEqual(len(orjson.loads(msg.edit_history)), 1) + self.assert_length(orjson.loads(msg.edit_history), 1) def test_propagate_topic_forward(self) -> None: self.login("hamlet") @@ -1133,14 +1133,14 @@ class EditMessageTest(ZulipTestCase): self.assert_json_success(result) messages = get_topic_messages(user_profile, old_stream, "test") - self.assertEqual(len(messages), 1) + self.assert_length(messages, 1) self.assertEqual( messages[0].content, f"This topic was moved by @_**Iago|{user_profile.id}** to #**new stream>test**", ) messages = get_topic_messages(user_profile, new_stream, "test") - self.assertEqual(len(messages), 4) + self.assert_length(messages, 4) self.assertEqual( messages[3].content, f"This topic was moved here from #**test move stream>test** by @_**Iago|{user_profile.id}**", @@ -1307,7 +1307,7 @@ class EditMessageTest(ZulipTestCase): self.assert_json_success(result) messages = get_topic_messages(user_profile, old_stream, "test") - self.assertEqual(len(messages), 2) + self.assert_length(messages, 2) self.assertEqual(messages[0].id, msg_id) self.assertEqual( messages[1].content, @@ -1315,7 +1315,7 @@ class EditMessageTest(ZulipTestCase): ) messages = get_topic_messages(user_profile, new_stream, "test") - self.assertEqual(len(messages), 3) + self.assert_length(messages, 3) self.assertEqual(messages[0].id, msg_id_later) self.assertEqual( messages[2].content, @@ -1342,15 +1342,15 @@ class EditMessageTest(ZulipTestCase): if expect_fail: self.assert_json_error(result, "You don't have permission to move this message") messages = get_topic_messages(user_profile, old_stream, "test") - self.assertEqual(len(messages), 3) + self.assert_length(messages, 3) messages = get_topic_messages(user_profile, new_stream, "test") - self.assertEqual(len(messages), 0) + self.assert_length(messages, 0) else: self.assert_json_success(result) messages = get_topic_messages(user_profile, old_stream, "test") - self.assertEqual(len(messages), 1) + self.assert_length(messages, 1) messages = get_topic_messages(user_profile, new_stream, "test") - self.assertEqual(len(messages), 4) + self.assert_length(messages, 4) # Check sending messages when policy is Realm.POLICY_ADMINS_ONLY. do_set_realm_property( @@ -1432,15 +1432,15 @@ class EditMessageTest(ZulipTestCase): if error_msg is not None: self.assert_json_error(result, error_msg) messages = get_topic_messages(user_profile, old_stream, "test") - self.assertEqual(len(messages), 3) + self.assert_length(messages, 3) messages = get_topic_messages(user_profile, new_stream, "test") - self.assertEqual(len(messages), 0) + self.assert_length(messages, 0) else: self.assert_json_success(result) messages = get_topic_messages(user_profile, old_stream, "test") - self.assertEqual(len(messages), 1) + self.assert_length(messages, 1) messages = get_topic_messages(user_profile, new_stream, "test") - self.assertEqual(len(messages), 4) + self.assert_length(messages, 4) # Check when stream_post_policy is STREAM_POST_POLICY_ADMINS. do_change_stream_post_policy(new_stream, Stream.STREAM_POST_POLICY_ADMINS) @@ -1508,10 +1508,10 @@ class EditMessageTest(ZulipTestCase): self.assert_json_error(result, "Cannot change message content while changing stream") messages = get_topic_messages(user_profile, old_stream, "test") - self.assertEqual(len(messages), 3) + self.assert_length(messages, 3) messages = get_topic_messages(user_profile, new_stream, "test") - self.assertEqual(len(messages), 0) + self.assert_length(messages, 0) def test_move_message_to_stream_and_topic(self) -> None: (user_profile, old_stream, new_stream, msg_id, msg_id_later) = self.prepare_move_topics( @@ -1528,18 +1528,18 @@ class EditMessageTest(ZulipTestCase): "topic": "new topic", }, ) - self.assertEqual(len(queries), 52) - self.assertEqual(len(cache_tries), 13) + self.assert_length(queries, 52) + self.assert_length(cache_tries, 13) messages = get_topic_messages(user_profile, old_stream, "test") - self.assertEqual(len(messages), 1) + self.assert_length(messages, 1) self.assertEqual( messages[0].content, f"This topic was moved by @_**Iago|{user_profile.id}** to #**new stream>new topic**", ) messages = get_topic_messages(user_profile, new_stream, "new topic") - self.assertEqual(len(messages), 4) + self.assert_length(messages, 4) self.assertEqual( messages[3].content, f"This topic was moved here from #**test move stream>test** by @_**Iago|{user_profile.id}**", @@ -1679,10 +1679,10 @@ class EditMessageTest(ZulipTestCase): self.assert_json_success(result) messages = get_topic_messages(user_profile, old_stream, "test") - self.assertEqual(len(messages), 0) + self.assert_length(messages, 0) messages = get_topic_messages(user_profile, new_stream, "test") - self.assertEqual(len(messages), 3) + self.assert_length(messages, 3) def test_notify_new_thread_move_message_to_stream(self) -> None: (user_profile, old_stream, new_stream, msg_id, msg_id_lt) = self.prepare_move_topics( @@ -1703,10 +1703,10 @@ class EditMessageTest(ZulipTestCase): self.assert_json_success(result) messages = get_topic_messages(user_profile, old_stream, "test") - self.assertEqual(len(messages), 0) + self.assert_length(messages, 0) messages = get_topic_messages(user_profile, new_stream, "test") - self.assertEqual(len(messages), 4) + self.assert_length(messages, 4) self.assertEqual( messages[3].content, f"This topic was moved here from #**test move stream>test** by @_**Iago|{user_profile.id}**", @@ -1731,14 +1731,14 @@ class EditMessageTest(ZulipTestCase): self.assert_json_success(result) messages = get_topic_messages(user_profile, old_stream, "test") - self.assertEqual(len(messages), 1) + self.assert_length(messages, 1) self.assertEqual( messages[0].content, f"This topic was moved by @_**Iago|{user_profile.id}** to #**new stream>test**", ) messages = get_topic_messages(user_profile, new_stream, "test") - self.assertEqual(len(messages), 3) + self.assert_length(messages, 3) def parameterized_test_move_message_involving_private_stream( self, @@ -1796,14 +1796,14 @@ class EditMessageTest(ZulipTestCase): self.assert_json_success(result) messages = get_topic_messages(admin_user, old_stream, "test") - self.assertEqual(len(messages), 1) + self.assert_length(messages, 1) self.assertEqual( messages[0].content, f"This topic was moved by @_**Iago|{admin_user.id}** to #**new stream>test**", ) messages = get_topic_messages(admin_user, new_stream, "test") - self.assertEqual(len(messages), 3) + self.assert_length(messages, 3) self.assertEqual( UserMessage.objects.filter( diff --git a/zerver/tests/test_message_edit_notifications.py b/zerver/tests/test_message_edit_notifications.py index 665c2fe930..694fb04e82 100644 --- a/zerver/tests/test_message_edit_notifications.py +++ b/zerver/tests/test_message_edit_notifications.py @@ -109,12 +109,12 @@ class EditMessageSideEffectsTest(ZulipTestCase): ] if expect_short_circuit: - self.assertEqual(len(cordelia_calls), 0) + self.assert_length(cordelia_calls, 0) return {} # Normally we expect maybe_enqueue_notifications to be # called for Cordelia, so continue on. - self.assertEqual(len(cordelia_calls), 1) + self.assert_length(cordelia_calls, 1) enqueue_kwargs = cordelia_calls[0][1] queue_messages = [] @@ -202,7 +202,7 @@ class EditMessageSideEffectsTest(ZulipTestCase): queue_messages = info["queue_messages"] - self.assertEqual(len(queue_messages), 2) + self.assert_length(queue_messages, 2) self.assertEqual(queue_messages[0]["queue_name"], "missedmessage_mobile_notifications") mobile_event = queue_messages[0]["event"] @@ -335,7 +335,7 @@ class EditMessageSideEffectsTest(ZulipTestCase): queue_messages = info["queue_messages"] - self.assertEqual(len(queue_messages), 1) + self.assert_length(queue_messages, 1) def test_always_push_notify_for_fully_present_boring_user(self) -> None: cordelia = self.example_user("cordelia") @@ -376,7 +376,7 @@ class EditMessageSideEffectsTest(ZulipTestCase): # Even though Cordelia has enable_online_push_notifications set # to True, we don't send her any offline notifications, since she # was not mentioned. - self.assertEqual(len(queue_messages), 0) + self.assert_length(queue_messages, 0) def test_updates_with_stream_mention_of_sorta_present_user(self) -> None: cordelia = self.example_user("cordelia") @@ -412,7 +412,7 @@ class EditMessageSideEffectsTest(ZulipTestCase): # She will get messages enqueued. (Other tests drill down on the # actual content of these messages.) - self.assertEqual(len(info["queue_messages"]), 2) + self.assert_length(info["queue_messages"], 2) def test_updates_with_wildcard_mention(self) -> None: cordelia = self.example_user("cordelia") @@ -447,7 +447,7 @@ class EditMessageSideEffectsTest(ZulipTestCase): self.assertEqual(info["enqueue_kwargs"], expected_enqueue_kwargs) # She will get messages enqueued. - self.assertEqual(len(info["queue_messages"]), 2) + self.assert_length(info["queue_messages"], 2) def test_updates_with_upgrade_wildcard_mention(self) -> None: # If there was a previous wildcard mention delivered to the @@ -509,7 +509,7 @@ class EditMessageSideEffectsTest(ZulipTestCase): # Because Cordelia is FULLY present, we don't need to send any offline # push notifications or message notification emails. - self.assertEqual(len(info["queue_messages"]), 0) + self.assert_length(info["queue_messages"], 0) def test_clear_notification_when_mention_removed(self) -> None: mentioned_user = self.example_user("iago") diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.py index 84a6a2345f..770b2731f8 100644 --- a/zerver/tests/test_message_fetch.py +++ b/zerver/tests/test_message_fetch.py @@ -159,8 +159,8 @@ class NarrowBuilderTest(ZulipTestCase): ] realm = get_realm("zulip") created, existing = create_streams_if_needed(realm, stream_dicts) - self.assertEqual(len(created), 3) - self.assertEqual(len(existing), 0) + self.assert_length(created, 3) + self.assert_length(existing, 0) # Number of recipient ids will increase by 1 and not 3 self._do_add_term_test( @@ -195,8 +195,8 @@ class NarrowBuilderTest(ZulipTestCase): ] realm = get_realm("zulip") created, existing = create_streams_if_needed(realm, stream_dicts) - self.assertEqual(len(created), 3) - self.assertEqual(len(existing), 0) + self.assert_length(created, 3) + self.assert_length(existing, 0) # Number of recipient ids will increase by 1 and not 3 self._do_add_term_test( @@ -1342,7 +1342,7 @@ class GetOldMessagesTest(ZulipTestCase): self.assert_json_success(payload) result = orjson.loads(payload.content) - self.assertEqual(len(result["messages"]), len(message_ids)) + self.assert_length(result["messages"], len(message_ids)) for message in result["messages"]: assert message["id"] in message_ids @@ -1354,7 +1354,7 @@ class GetOldMessagesTest(ZulipTestCase): self.assert_json_success(payload) result = orjson.loads(payload.content) - self.assertEqual(len(result["messages"]), len(message_ids[pivot_index:])) + self.assert_length(result["messages"], len(message_ids[pivot_index:])) for message in result["messages"]: assert message["id"] in message_ids @@ -1428,7 +1428,7 @@ class GetOldMessagesTest(ZulipTestCase): message_to_assert = message break assert message_to_assert is not None - self.assertEqual(len(message_to_assert["reactions"]), 1) + self.assert_length(message_to_assert["reactions"], 1) self.assertEqual(message_to_assert["reactions"][0]["emoji_name"], reaction_name) def test_successful_get_messages(self) -> None: @@ -1849,7 +1849,7 @@ class GetOldMessagesTest(ZulipTestCase): self.assert_json_success(payload) result = orjson.loads(payload.content) messages = result["messages"] - self.assertEqual(len(messages), 2) + self.assert_length(messages, 2) for message in messages: if message["id"] == old_message_id: @@ -1925,7 +1925,7 @@ class GetOldMessagesTest(ZulipTestCase): messages = get_user_messages(self.mit_user("starnine")) stream_messages = [msg for msg in messages if msg.is_stream_message()] - self.assertEqual(len(result["messages"]), 2) + self.assert_length(result["messages"], 2) for i, message in enumerate(result["messages"]): self.assertEqual(message["type"], "stream") stream_id = stream_messages[i].recipient.id @@ -1955,7 +1955,7 @@ class GetOldMessagesTest(ZulipTestCase): messages = get_user_messages(mit_user_profile) stream_messages = [msg for msg in messages if msg.is_stream_message()] - self.assertEqual(len(result["messages"]), 5) + self.assert_length(result["messages"], 5) for i, message in enumerate(result["messages"]): self.assertEqual(message["type"], "stream") stream_id = stream_messages[i].recipient.id @@ -1989,7 +1989,7 @@ class GetOldMessagesTest(ZulipTestCase): messages = get_user_messages(mit_user_profile) stream_messages = [msg for msg in messages if msg.is_stream_message()] - self.assertEqual(len(result["messages"]), 7) + self.assert_length(result["messages"], 7) for i, message in enumerate(result["messages"]): self.assertEqual(message["type"], "stream") stream_id = stream_messages[i].recipient.id @@ -2064,7 +2064,7 @@ class GetOldMessagesTest(ZulipTestCase): result = self.client_get("/json/messages/matches_narrow", params) self.assert_json_success(result) messages = result.json()["messages"] - self.assertEqual(len(list(messages.keys())), 1) + self.assert_length(list(messages.keys()), 1) message = messages[str(good_id)] self.assertEqual( message["match_content"], @@ -2114,7 +2114,7 @@ class GetOldMessagesTest(ZulipTestCase): num_after=10, ) ) - self.assertEqual(len(result["messages"]), 2) + self.assert_length(result["messages"], 2) messages = result["messages"] narrow = [dict(operator="search", operand="https://google.com")] @@ -2126,7 +2126,7 @@ class GetOldMessagesTest(ZulipTestCase): num_after=10, ) ) - self.assertEqual(len(link_search_result["messages"]), 1) + self.assert_length(link_search_result["messages"], 1) self.assertEqual( link_search_result["messages"][0]["match_content"], '

https://google.com

', @@ -2157,7 +2157,7 @@ class GetOldMessagesTest(ZulipTestCase): num_before=0, ) ) - self.assertEqual(len(multi_search_result["messages"]), 1) + self.assert_length(multi_search_result["messages"], 1) self.assertEqual( multi_search_result["messages"][0]["match_content"], '

discuss lunch after lunch

', @@ -2175,7 +2175,7 @@ class GetOldMessagesTest(ZulipTestCase): num_before=0, ) ) - self.assertEqual(len(result["messages"]), 4) + self.assert_length(result["messages"], 4) messages = result["messages"] japanese_message = [m for m in messages if m[TOPIC_NAME] == "日本"][-1] @@ -2205,7 +2205,7 @@ class GetOldMessagesTest(ZulipTestCase): num_before=0, ) ) - self.assertEqual(len(multi_search_result["messages"]), 1) + self.assert_length(multi_search_result["messages"], 1) self.assertEqual( multi_search_result["messages"][0]["match_content"], '

こんに ちは今日は いい 天気ですね。

', @@ -2269,7 +2269,7 @@ class GetOldMessagesTest(ZulipTestCase): num_before=10, ) ) - self.assertEqual(len(stream_search_result["messages"]), 1) + self.assert_length(stream_search_result["messages"], 1) self.assertEqual( stream_search_result["messages"][0]["match_content"], '

Public special content!

', @@ -2322,7 +2322,7 @@ class GetOldMessagesTest(ZulipTestCase): num_before=0, ) ) - self.assertEqual(len(result["messages"]), 4) + self.assert_length(result["messages"], 4) messages = result["messages"] japanese_message = [m for m in messages if m[TOPIC_NAME] == "日本語"][-1] @@ -2353,7 +2353,7 @@ class GetOldMessagesTest(ZulipTestCase): num_before=0, ) ) - self.assertEqual(len(multi_search_result["messages"]), 1) + self.assert_length(multi_search_result["messages"], 1) self.assertEqual( multi_search_result["messages"][0]["match_content"], '

Can you speak https://en.wikipedia.org/wiki/Japanese?

', @@ -2372,7 +2372,7 @@ class GetOldMessagesTest(ZulipTestCase): num_before=0, ) ) - self.assertEqual(len(multi_search_result["messages"]), 1) + self.assert_length(multi_search_result["messages"], 1) self.assertEqual( multi_search_result["messages"][0]["match_content"], '

朝はごはんを食べました

', @@ -2387,7 +2387,7 @@ class GetOldMessagesTest(ZulipTestCase): num_before=0, ) ) - self.assertEqual(len(link_search_result["messages"]), 1) + self.assert_length(link_search_result["messages"], 1) self.assertEqual( link_search_result["messages"][0]["match_content"], '

https://google.com

', @@ -2405,7 +2405,7 @@ class GetOldMessagesTest(ZulipTestCase): num_before=0, ) ) - self.assertEqual(len(special_search_result["messages"]), 1) + self.assert_length(special_search_result["messages"], 1) self.assertEqual( special_search_result["messages"][0][MATCH_TOPIC], 'bread & butter', @@ -2422,7 +2422,7 @@ class GetOldMessagesTest(ZulipTestCase): num_before=0, ) ) - self.assertEqual(len(special_search_result["messages"]), 1) + self.assert_length(special_search_result["messages"], 1) self.assertEqual( special_search_result["messages"][0][MATCH_TOPIC], 'bread & butter', @@ -2459,7 +2459,7 @@ class GetOldMessagesTest(ZulipTestCase): result = self.client_get("/json/messages/matches_narrow", params) self.assert_json_success(result) messages = result.json()["messages"] - self.assertEqual(len(list(messages.keys())), 1) + self.assert_length(list(messages.keys()), 1) message = messages[str(good_id)] self.assertIn("a href=", message["match_content"]) self.assertIn("http://foo.com", message["match_content"]) @@ -2485,17 +2485,17 @@ class GetOldMessagesTest(ZulipTestCase): num_after=0, ) ) - self.assertEqual(len(result["messages"]), 1) + self.assert_length(result["messages"], 1) narrow = [dict(operator="is", operand="mentioned")] result = self.get_and_check_messages( dict(narrow=orjson.dumps(narrow).decode(), anchor=anchor, num_before=0, num_after=0) ) - self.assertEqual(len(result["messages"]), 0) + self.assert_length(result["messages"], 0) def test_get_visible_messages_with_anchor(self) -> None: def messages_matches_ids(messages: List[Dict[str, Any]], message_ids: List[int]) -> None: - self.assertEqual(len(messages), len(message_ids)) + self.assert_length(messages, len(message_ids)) for message in messages: assert message["id"] in message_ids @@ -3119,7 +3119,7 @@ class GetOldMessagesTest(ZulipTestCase): # Verify the query for old messages looks correct. queries = [q for q in all_queries if "/* get_messages */" in q["sql"]] - self.assertEqual(len(queries), 1) + self.assert_length(queries, 1) sql = queries[0]["sql"] self.assertNotIn(f"AND message_id = {LARGER_THAN_MAX_MESSAGE_ID}", sql) self.assertIn("ORDER BY message_id ASC", sql) @@ -3165,7 +3165,7 @@ class GetOldMessagesTest(ZulipTestCase): get_messages_backend(request, user_profile) queries = [q for q in all_queries if "/* get_messages */" in q["sql"]] - self.assertEqual(len(queries), 1) + self.assert_length(queries, 1) sql = queries[0]["sql"] self.assertNotIn(f"AND message_id = {LARGER_THAN_MAX_MESSAGE_ID}", sql) self.assertIn("ORDER BY message_id ASC", sql) @@ -3189,7 +3189,7 @@ class GetOldMessagesTest(ZulipTestCase): get_messages_backend(request, user_profile) queries = [q for q in all_queries if "/* get_messages */" in q["sql"]] - self.assertEqual(len(queries), 1) + self.assert_length(queries, 1) sql = queries[0]["sql"] @@ -3243,7 +3243,7 @@ class GetOldMessagesTest(ZulipTestCase): # Do some tests on the main query, to verify the muting logic # runs on this code path. queries = [q for q in all_queries if str(q["sql"]).startswith("SELECT message_id, flags")] - self.assertEqual(len(queries), 1) + self.assert_length(queries, 1) stream = get_stream("Scotland", realm) recipient_id = stream.recipient.id @@ -3253,7 +3253,7 @@ class GetOldMessagesTest(ZulipTestCase): # Next, verify the use_first_unread_anchor setting invokes # the `message_id = LARGER_THAN_MAX_MESSAGE_ID` hack. queries = [q for q in all_queries if "/* get_messages */" in q["sql"]] - self.assertEqual(len(queries), 1) + self.assert_length(queries, 1) self.assertIn(f"AND zerver_message.id = {LARGER_THAN_MAX_MESSAGE_ID}", queries[0]["sql"]) def test_exclude_muting_conditions(self) -> None: @@ -3601,7 +3601,7 @@ WHERE user_profile_id = {hamlet_id} AND (content ILIKE '%jumping%' OR subject IL num_after=10, ) ) - self.assertEqual(len(result["messages"]), 0) + self.assert_length(result["messages"], 0) narrow = [ dict(operator="sender", operand=cordelia.email), @@ -3614,7 +3614,7 @@ WHERE user_profile_id = {hamlet_id} AND (content ILIKE '%jumping%' OR subject IL num_after=10, ) ) - self.assertEqual(len(result["messages"]), 1) + self.assert_length(result["messages"], 1) messages = result["messages"] (hello_message,) = [m for m in messages if m[TOPIC_NAME] == "say hello"] diff --git a/zerver/tests/test_message_flags.py b/zerver/tests/test_message_flags.py index 6d141dfc57..93caa0deda 100644 --- a/zerver/tests/test_message_flags.py +++ b/zerver/tests/test_message_flags.py @@ -613,7 +613,7 @@ class GetUnreadMsgsTest(ZulipTestCase): ] all_message_ids |= set(message_ids[topic_name]) - self.assertEqual(len(all_message_ids), 12) # sanity check on test setup + self.assert_length(all_message_ids, 12) # sanity check on test setup self.mute_stream( user_profile=hamlet, @@ -1311,7 +1311,7 @@ class MessageAccessTests(ZulipTestCase): # Message sent before subscribing wouldn't be accessible by later # subscribed user as stream has protected history - self.assertEqual(len(filtered_messages), 1) + self.assert_length(filtered_messages, 1) self.assertEqual(filtered_messages[0].id, message_two_id) do_change_stream_invite_only(stream, True, history_public_to_subscribers=True) @@ -1322,7 +1322,7 @@ class MessageAccessTests(ZulipTestCase): # Message sent before subscribing are accessible by 8user as stream # don't have protected history - self.assertEqual(len(filtered_messages), 2) + self.assert_length(filtered_messages, 2) # Testing messages accessiblity for an unsubscribed user unsubscribed_user = self.example_user("ZOE") @@ -1331,7 +1331,7 @@ class MessageAccessTests(ZulipTestCase): filtered_messages = bulk_access_messages(unsubscribed_user, messages, stream=stream) self.assert_length(queries, 2) - self.assertEqual(len(filtered_messages), 0) + self.assert_length(filtered_messages, 0) # Verify an exception is thrown if called where the passed # stream not matching the messages. @@ -1363,14 +1363,14 @@ class MessageAccessTests(ZulipTestCase): # All public stream messages are always accessible with queries_captured() as queries: filtered_messages = bulk_access_messages(later_subscribed_user, messages, stream=stream) - self.assertEqual(len(filtered_messages), 2) + self.assert_length(filtered_messages, 2) self.assert_length(queries, 2) unsubscribed_user = self.example_user("ZOE") with queries_captured() as queries: filtered_messages = bulk_access_messages(unsubscribed_user, messages, stream=stream) - self.assertEqual(len(filtered_messages), 2) + self.assert_length(filtered_messages, 2) self.assert_length(queries, 2) diff --git a/zerver/tests/test_message_send.py b/zerver/tests/test_message_send.py index 08dab9adba..c6f2888e5c 100644 --- a/zerver/tests/test_message_send.py +++ b/zerver/tests/test_message_send.py @@ -522,7 +522,7 @@ class MessagePOSTTest(ZulipTestCase): message_id = orjson.loads(result.content)["id"] recent_conversations = get_recent_private_conversations(user_profile) - self.assertEqual(len(recent_conversations), 1) + self.assert_length(recent_conversations, 1) recent_conversation = list(recent_conversations.values())[0] recipient_id = list(recent_conversations.keys())[0] self.assertEqual(set(recent_conversation["user_ids"]), {othello.id}) @@ -542,7 +542,7 @@ class MessagePOSTTest(ZulipTestCase): self_message_id = orjson.loads(result.content)["id"] recent_conversations = get_recent_private_conversations(user_profile) - self.assertEqual(len(recent_conversations), 2) + self.assert_length(recent_conversations, 2) recent_conversation = recent_conversations[recipient_id] self.assertEqual(set(recent_conversation["user_ids"]), {othello.id}) self.assertEqual(recent_conversation["max_message_id"], message_id) @@ -1946,10 +1946,10 @@ class StreamMessagesTest(ZulipTestCase): self.assertIn(message2_id, msg_data["huddle_dict"].keys()) # only these two messages are present in msg_data - self.assertEqual(len(msg_data["huddle_dict"].keys()), 2) + self.assert_length(msg_data["huddle_dict"].keys(), 2) recent_conversations = get_recent_private_conversations(users[1]) - self.assertEqual(len(recent_conversations), 1) + self.assert_length(recent_conversations, 1) recent_conversation = list(recent_conversations.values())[0] self.assertEqual( set(recent_conversation["user_ids"]), {user.id for user in users if user != users[1]} diff --git a/zerver/tests/test_muting_users.py b/zerver/tests/test_muting_users.py index 963aab6a0e..81ff6ae390 100644 --- a/zerver/tests/test_muting_users.py +++ b/zerver/tests/test_muting_users.py @@ -26,7 +26,7 @@ class MutedUsersTests(ZulipTestCase): self.assert_json_success(result) muted_users = get_user_mutes(hamlet) - self.assertEqual(len(muted_users), 1) + self.assert_length(muted_users, 1) self.assertDictEqual( muted_users[0], @@ -101,7 +101,7 @@ class MutedUsersTests(ZulipTestCase): "event_type", "event_time", "extra_data" ) ) - self.assertEqual(len(audit_log_entries), 1) + self.assert_length(audit_log_entries, 1) audit_log_entry = audit_log_entries[0] self.assertEqual( audit_log_entry, @@ -152,7 +152,7 @@ class MutedUsersTests(ZulipTestCase): .values_list("event_type", "event_time", "extra_data") .order_by("id") ) - self.assertEqual(len(audit_log_entries), 2) + self.assert_length(audit_log_entries, 2) audit_log_entry = audit_log_entries[1] self.assertEqual( audit_log_entry, diff --git a/zerver/tests/test_new_users.py b/zerver/tests/test_new_users.py index 43d1483ab5..6b6d6f474b 100644 --- a/zerver/tests/test_new_users.py +++ b/zerver/tests/test_new_users.py @@ -52,7 +52,7 @@ class SendLoginEmailTest(ZulipTestCase): ) # email is sent and correct subject - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) subject = "New login from Firefox on Windows" self.assertEqual(mail.outbox[0].subject, subject) # local time is correct and in email's body @@ -75,7 +75,7 @@ class SendLoginEmailTest(ZulipTestCase): user = self.example_user("hamlet") self.login_user(user) - self.assertEqual(len(mail.outbox), 0) + self.assert_length(mail.outbox, 0) def test_dont_send_login_emails_for_new_user_registration_logins(self) -> None: with self.settings(SEND_LOGIN_EMAILS=True): @@ -83,7 +83,7 @@ class SendLoginEmailTest(ZulipTestCase): # Verify that there's just 1 email for new user registration. self.assertEqual(mail.outbox[0].subject, "Activate your Zulip account") - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) def test_without_path_info_dont_send_login_emails_for_new_user_registration_logins( self, @@ -109,13 +109,13 @@ class SendLoginEmailTest(ZulipTestCase): self.assertFalse(user.enable_login_emails) with mock.patch("zerver.signals.timezone_now", return_value=mock_time): self.login_user(user) - self.assertEqual(len(mail.outbox), 0) + self.assert_length(mail.outbox, 0) do_change_notification_settings(user, "enable_login_emails", True, acting_user=None) self.assertTrue(user.enable_login_emails) with mock.patch("zerver.signals.timezone_now", return_value=mock_time): self.login_user(user) - self.assertEqual(len(mail.outbox), 1) + self.assert_length(mail.outbox, 1) class TestBrowserAndOsUserAgentStrings(ZulipTestCase): diff --git a/zerver/tests/test_openapi.py b/zerver/tests/test_openapi.py index fe7acf7656..7f06ba83a9 100644 --- a/zerver/tests/test_openapi.py +++ b/zerver/tests/test_openapi.py @@ -337,7 +337,7 @@ so maybe we shouldn't mark it as intentionally undocumented in the URLs. undocumented_paths -= self.buggy_documentation_endpoints undocumented_paths -= self.pending_endpoints try: - self.assertEqual(len(undocumented_paths), 0) + self.assert_length(undocumented_paths, 0) except AssertionError: # nocoverage msg = "The following endpoints have been documented but can't be found in urls.py:" for undocumented_path in undocumented_paths: diff --git a/zerver/tests/test_outgoing_http.py b/zerver/tests/test_outgoing_http.py index aec23f880c..6a5cd84073 100644 --- a/zerver/tests/test_outgoing_http.py +++ b/zerver/tests/test_outgoing_http.py @@ -54,7 +54,7 @@ class TestOutgoingHttp(ZulipTestCase): OutgoingSession(role="testing", timeout=1, headers={"X-Foo": "bar"}).get( "http://example.com/" ) - self.assertEqual(len(mock_requests.calls), 1) + self.assert_length(mock_requests.calls, 1) headers = mock_requests.calls[0].request.headers # We don't see a proxy header with no proxy set self.assertFalse("X-Smokescreen-Role" in headers) @@ -67,7 +67,7 @@ class TestOutgoingHttp(ZulipTestCase): OutgoingSession(role="testing", timeout=1, headers={"X-Foo": "bar"}).get( "http://example.com/" ) - self.assertEqual(len(mock_requests.calls), 1) + self.assert_length(mock_requests.calls, 1) headers = mock_requests.calls[0].request.headers self.assertEqual(headers["X-Smokescreen-Role"], "testing") @@ -81,11 +81,11 @@ class TestOutgoingHttp(ZulipTestCase): with RequestMockWithTimeoutAsHeader() as mock_requests: mock_requests.add(responses.GET, "http://example.com/") OutgoingSession(role="testing", timeout=17).get("http://example.com/") - self.assertEqual(len(mock_requests.calls), 1) + self.assert_length(mock_requests.calls, 1) self.assertEqual(mock_requests.calls[0].request.headers["X-Timeout"], 17) with RequestMockWithTimeoutAsHeader() as mock_requests: mock_requests.add(responses.GET, "http://example.com/") OutgoingSession(role="testing", timeout=17).get("http://example.com/", timeout=42) - self.assertEqual(len(mock_requests.calls), 1) + self.assert_length(mock_requests.calls, 1) self.assertEqual(mock_requests.calls[0].request.headers["X-Timeout"], 42) diff --git a/zerver/tests/test_outgoing_webhook_system.py b/zerver/tests/test_outgoing_webhook_system.py index d68a36c489..ffb33058fe 100644 --- a/zerver/tests/test_outgoing_webhook_system.py +++ b/zerver/tests/test_outgoing_webhook_system.py @@ -82,7 +82,7 @@ class DoRestCallTests(ZulipTestCase): session.post.return_value = ResponseMock(200, orjson.dumps(dict(content="whatever"))) with self.assertLogs(level="INFO") as logs: do_rest_call("", mock_event, service_handler) - self.assertEqual(len(logs.output), 1) + self.assert_length(logs.output, 1) self.assertIn( f"Outgoing webhook request from {bot_user.id}@zulip took ", logs.output[0] ) @@ -95,7 +95,7 @@ class DoRestCallTests(ZulipTestCase): session.post.return_value = ResponseMock(200, b"{}") with self.assertLogs(level="INFO") as logs: do_rest_call("", mock_event, handler) - self.assertEqual(len(logs.output), 1) + self.assert_length(logs.output, 1) self.assertIn( f"Outgoing webhook request from {bot_user.id}@zulip took ", logs.output[0] ) @@ -174,7 +174,7 @@ The webhook got a response with status code *400*.""", final_response = do_rest_call("https://example.com/", mock_event, service_handler) assert final_response is not None - self.assertEqual(len(logs.output), 1) + self.assert_length(logs.output, 1) self.assertIn( f"Outgoing webhook request from {bot_user.id}@zulip took ", logs.output[0] ) @@ -393,11 +393,11 @@ class TestOutgoingWebhookMessaging(ZulipTestCase): bot, content="some content", ) - self.assertEqual(len(logs.output), 2) + self.assert_length(logs.output, 2) self.assertIn(f"Outgoing webhook request from {bot.id}@zulip took ", logs.output[0]) self.assertIn(f"Outgoing webhook request from {bot.id}@zulip took ", logs.output[1]) - self.assertEqual(len(responses.calls), 2) + self.assert_length(responses.calls, 2) calls_by_url = { call.request.url: orjson.loads(call.request.body or b"") for call in responses.calls @@ -425,10 +425,10 @@ class TestOutgoingWebhookMessaging(ZulipTestCase): ) with self.assertLogs(level="INFO") as logs: self.send_personal_message(sender, bot, content="foo") - self.assertEqual(len(logs.output), 1) + self.assert_length(logs.output, 1) self.assertIn(f"Outgoing webhook request from {bot.id}@zulip took ", logs.output[0]) - self.assertEqual(len(responses.calls), 1) + self.assert_length(responses.calls, 1) last_message = self.get_last_message() self.assertEqual(last_message.content, "Hidley ho, I'm a webhook responding!") @@ -454,7 +454,7 @@ class TestOutgoingWebhookMessaging(ZulipTestCase): with expect_fail as mock_fail, self.assertLogs(level="WARNING"): message_id = self.send_personal_message(sender, bot, content="foo") - self.assertEqual(len(responses.calls), 1) + self.assert_length(responses.calls, 1) # create message dict to get the message url message = { @@ -499,9 +499,9 @@ class TestOutgoingWebhookMessaging(ZulipTestCase): bot_owner, "Denmark", content=f"@**{bot.full_name}** foo", topic_name="bar" ) - self.assertEqual(len(responses.calls), 1) + self.assert_length(responses.calls, 1) - self.assertEqual(len(logs.output), 1) + self.assert_length(logs.output, 1) self.assertIn(f"Outgoing webhook request from {bot.id}@zulip took ", logs.output[0]) last_message = self.get_last_message() @@ -533,9 +533,9 @@ class TestOutgoingWebhookMessaging(ZulipTestCase): bot_owner, "Denmark", content=f"@**{bot.full_name}** foo", topic_name="bar" ) - self.assertEqual(len(responses.calls), 1) + self.assert_length(responses.calls, 1) - self.assertEqual(len(logs.output), 1) + self.assert_length(logs.output, 1) self.assertIn(f"Outgoing webhook request from {bot.id}@zulip took ", logs.output[0]) # We verify that no new message was sent, since that's the behavior implied diff --git a/zerver/tests/test_presence.py b/zerver/tests/test_presence.py index a1fa6c57fa..99277e2dea 100644 --- a/zerver/tests/test_presence.py +++ b/zerver/tests/test_presence.py @@ -85,7 +85,7 @@ class UserPresenceModelTests(ZulipTestCase): user_profile = self.example_user("hamlet") email = user_profile.email presence_dct = get_status_dict_by_realm(user_profile.realm_id) - self.assertEqual(len(presence_dct), 0) + self.assert_length(presence_dct, 0) self.login_user(user_profile) result = self.client_post("/json/users/me/presence", {"status": "active"}) @@ -93,12 +93,12 @@ class UserPresenceModelTests(ZulipTestCase): slim_presence = False presence_dct = get_status_dict_by_realm(user_profile.realm_id, slim_presence) - self.assertEqual(len(presence_dct), 1) + self.assert_length(presence_dct, 1) self.assertEqual(presence_dct[email]["website"]["status"], "active") slim_presence = True presence_dct = get_status_dict_by_realm(user_profile.realm_id, slim_presence) - self.assertEqual(len(presence_dct), 1) + self.assert_length(presence_dct, 1) info = presence_dct[str(user_profile.id)] self.assertEqual(set(info.keys()), {"active_timestamp"}) @@ -110,12 +110,12 @@ class UserPresenceModelTests(ZulipTestCase): # Simulate the presence being a week old first. Nothing should change. back_date(num_weeks=1) presence_dct = get_status_dict_by_realm(user_profile.realm_id) - self.assertEqual(len(presence_dct), 1) + self.assert_length(presence_dct, 1) # If the UserPresence row is three weeks old, we ignore it. back_date(num_weeks=3) presence_dct = get_status_dict_by_realm(user_profile.realm_id) - self.assertEqual(len(presence_dct), 0) + self.assert_length(presence_dct, 0) def test_push_tokens(self) -> None: UserPresence.objects.all().delete() @@ -129,7 +129,7 @@ class UserPresenceModelTests(ZulipTestCase): def pushable() -> bool: presence_dct = get_status_dict_by_realm(user_profile.realm_id) - self.assertEqual(len(presence_dct), 1) + self.assert_length(presence_dct, 1) return presence_dct[email]["website"]["pushable"] self.assertFalse(pushable()) diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py index 09680dfba6..d75c9bf0ad 100644 --- a/zerver/tests/test_push_notifications.py +++ b/zerver/tests/test_push_notifications.py @@ -257,7 +257,7 @@ class PushBouncerNotificationTest(BouncerTestCase): remote_tokens = RemotePushDeviceToken.objects.filter(token=payload["token"]) token_count = 1 if method == "register" else 0 - self.assertEqual(len(remote_tokens), token_count) + self.assert_length(remote_tokens, token_count) # Try adding/removing tokens that are too big... broken_token = "x" * 5000 # too big @@ -273,14 +273,14 @@ class PushBouncerNotificationTest(BouncerTestCase): self.assert_json_success(result) remote_tokens = RemotePushDeviceToken.objects.filter(token=payload["token"]) - self.assertEqual(len(remote_tokens), 1) + self.assert_length(remote_tokens, 1) result = self.uuid_post( self.server_uuid, "/api/v1/remotes/push/unregister/all", dict(user_id=10) ) self.assert_json_success(result) remote_tokens = RemotePushDeviceToken.objects.filter(token=payload["token"]) - self.assertEqual(len(remote_tokens), 0) + self.assert_length(remote_tokens, 0) def test_invalid_apns_token(self) -> None: endpoints = [ @@ -373,12 +373,12 @@ class PushBouncerNotificationTest(BouncerTestCase): tokens = list( RemotePushDeviceToken.objects.filter(user_id=user.id, token=token, server=server) ) - self.assertEqual(len(tokens), 1) + self.assert_length(tokens, 1) self.assertEqual(tokens[0].token, token) # User should have tokens for both devices now. tokens = list(RemotePushDeviceToken.objects.filter(user_id=user.id, server=server)) - self.assertEqual(len(tokens), 2) + self.assert_length(tokens, 2) # Remove tokens for endpoint, token, kind in endpoints: @@ -389,14 +389,14 @@ class PushBouncerNotificationTest(BouncerTestCase): tokens = list( RemotePushDeviceToken.objects.filter(user_id=user.id, token=token, server=server) ) - self.assertEqual(len(tokens), 0) + self.assert_length(tokens, 0) # Re-add copies of those tokens for endpoint, token, kind in endpoints: result = self.client_post(endpoint, {"token": token}, subdomain="zulip") self.assert_json_success(result) tokens = list(RemotePushDeviceToken.objects.filter(user_id=user.id, server=server)) - self.assertEqual(len(tokens), 2) + self.assert_length(tokens, 2) # Now we want to remove them using the bouncer after an API key change. # First we test error handling in case of issues with the bouncer: @@ -409,12 +409,12 @@ class PushBouncerNotificationTest(BouncerTestCase): # We didn't manage to communicate with the bouncer, to the tokens are still there: tokens = list(RemotePushDeviceToken.objects.filter(user_id=user.id, server=server)) - self.assertEqual(len(tokens), 2) + self.assert_length(tokens, 2) # Now we successfully remove them: do_regenerate_api_key(user, user) tokens = list(RemotePushDeviceToken.objects.filter(user_id=user.id, server=server)) - self.assertEqual(len(tokens), 0) + self.assert_length(tokens, 0) class AnalyticsBouncerTest(BouncerTestCase): @@ -1935,7 +1935,7 @@ class TestPushApi(BouncerTestCase): self.assert_json_success(result) tokens = list(PushDeviceToken.objects.filter(user=user, token=token)) - self.assertEqual(len(tokens), 1) + self.assert_length(tokens, 1) self.assertEqual(tokens[0].token, token) with self.settings( @@ -1951,11 +1951,11 @@ class TestPushApi(BouncerTestCase): self.assert_json_success(result) tokens = list(PushDeviceToken.objects.filter(user=user, token=token)) - self.assertEqual(len(tokens), 1) + self.assert_length(tokens, 1) self.assertEqual(tokens[0].token, token) tokens = list(RemotePushDeviceToken.objects.filter(user_id=user.id, token=token)) - self.assertEqual(len(tokens), 1) + self.assert_length(tokens, 1) self.assertEqual(tokens[0].token, token) # PushDeviceToken will include all the device tokens. @@ -1974,7 +1974,7 @@ class TestPushApi(BouncerTestCase): result = self.client_delete(endpoint, {"token": token}) self.assert_json_success(result) tokens = list(PushDeviceToken.objects.filter(user=user, token=token)) - self.assertEqual(len(tokens), 0) + self.assert_length(tokens, 0) # Use push notification bouncer and test removing device tokens. # Tokens will be removed both locally and remotely. @@ -1988,8 +1988,8 @@ class TestPushApi(BouncerTestCase): remote_tokens = list( RemotePushDeviceToken.objects.filter(user_id=user.id, token=token) ) - self.assertEqual(len(tokens), 0) - self.assertEqual(len(remote_tokens), 0) + self.assert_length(tokens, 0) + self.assert_length(remote_tokens, 0) # Verify that the above process indeed removed all the tokens we created. self.assertEqual(RemotePushDeviceToken.objects.all().count(), 0) diff --git a/zerver/tests/test_queue.py b/zerver/tests/test_queue.py index 4cfee026f2..d41ea684d1 100644 --- a/zerver/tests/test_queue.py +++ b/zerver/tests/test_queue.py @@ -40,7 +40,7 @@ class TestQueueImplementation(ZulipTestCase): queue_client.start_json_consumer("test_suite", collect) - self.assertEqual(len(output), 1) + self.assert_length(output, 1) self.assertEqual(output[0]["event"], "my_event") @override_settings(USING_RABBITMQ=True) @@ -68,7 +68,7 @@ class TestQueueImplementation(ZulipTestCase): # Confirm that we processed the event fully once self.assertEqual(count, 2) - self.assertEqual(len(output), 1) + self.assert_length(output, 1) self.assertEqual(output[0]["event"], "my_event") @override_settings(USING_RABBITMQ=True) diff --git a/zerver/tests/test_queue_worker.py b/zerver/tests/test_queue_worker.py index a213ec12a0..3d6a1ffcc6 100644 --- a/zerver/tests/test_queue_worker.py +++ b/zerver/tests/test_queue_worker.py @@ -95,7 +95,7 @@ class WorkerTest(ZulipTestCase): user_profile=user.id, client=get_client("ios"), ) - self.assertEqual(len(activity_records), 1) + self.assert_length(activity_records, 1) self.assertEqual(activity_records[0].count, 2) # Now process the event a second time and confirm count goes @@ -110,7 +110,7 @@ class WorkerTest(ZulipTestCase): user_profile=user.id, client=get_client("ios"), ) - self.assertEqual(len(activity_records), 1) + self.assert_length(activity_records, 1) self.assertEqual(activity_records[0].count, 3) def test_missed_message_worker(self) -> None: diff --git a/zerver/tests/test_reactions.py b/zerver/tests/test_reactions.py index 2efd00cf77..777af3ef88 100644 --- a/zerver/tests/test_reactions.py +++ b/zerver/tests/test_reactions.py @@ -423,7 +423,7 @@ class ReactionEventTest(ZulipTestCase): reaction_sender, f"/api/v1/messages/{pm_id}/reactions", reaction_info ) self.assert_json_success(result) - self.assertEqual(len(events), 1) + self.assert_length(events, 1) event = events[0]["event"] event_user_ids = set(events[0]["users"]) @@ -468,7 +468,7 @@ class ReactionEventTest(ZulipTestCase): reaction_sender, f"/api/v1/messages/{pm_id}/reactions", reaction_info ) self.assert_json_success(result) - self.assertEqual(len(events), 1) + self.assert_length(events, 1) event = events[0]["event"] event_user_ids = set(events[0]["users"]) @@ -977,7 +977,7 @@ class RealmEmojiReactionTests(EmojiReactionBase): reactions = self.get_message_reactions( 1, self.default_reaction_info["emoji_code"], "realm_emoji" ) - self.assertEqual(len(reactions), 2) + self.assert_length(reactions, 2) def test_remove_realm_emoji_reaction(self) -> None: result = self.post_reaction(self.default_reaction_info) @@ -1038,7 +1038,7 @@ class ReactionAPIEventTest(EmojiReactionBase): with tornado_redirected_to_list(events): self.api_post(reaction_sender, f"/api/v1/messages/{pm_id}/reactions", reaction_info) - self.assertEqual(len(events), 1) + self.assert_length(events, 1) event = events[0]["event"] event_user_ids = set(events[0]["users"]) @@ -1085,7 +1085,7 @@ class ReactionAPIEventTest(EmojiReactionBase): ) self.assert_json_success(result) - self.assertEqual(len(events), 1) + self.assert_length(events, 1) event = events[0]["event"] event_user_ids = set(events[0]["users"]) diff --git a/zerver/tests/test_realm.py b/zerver/tests/test_realm.py index 1c40419f0b..05c2ec3657 100644 --- a/zerver/tests/test_realm.py +++ b/zerver/tests/test_realm.py @@ -291,7 +291,7 @@ class RealmTest(ZulipTestCase): do_send_realm_reactivation_email(realm, acting_user=iago) from django.core.mail import outbox - self.assertEqual(len(outbox), 1) + self.assert_length(outbox, 1) self.assertEqual(self.email_envelope_from(outbox[0]), settings.NOREPLY_EMAIL_ADDRESS) self.assertRegex( self.email_display_from(outbox[0]), diff --git a/zerver/tests/test_realm_emoji.py b/zerver/tests/test_realm_emoji.py index 94d910fa07..7a3e6d7491 100644 --- a/zerver/tests/test_realm_emoji.py +++ b/zerver/tests/test_realm_emoji.py @@ -28,7 +28,7 @@ class RealmEmojiTest(ZulipTestCase): result = self.client_get("/json/realm/emoji") self.assert_json_success(result) self.assertEqual(200, result.status_code) - self.assertEqual(len(result.json()["emoji"]), 2) + self.assert_length(result.json()["emoji"], 2) def test_list_no_author(self) -> None: self.login("iago") @@ -38,7 +38,7 @@ class RealmEmojiTest(ZulipTestCase): result = self.client_get("/json/realm/emoji") self.assert_json_success(result) content = result.json() - self.assertEqual(len(content["emoji"]), 2) + self.assert_length(content["emoji"], 2) test_emoji = content["emoji"][str(realm_emoji.id)] self.assertIsNone(test_emoji["author_id"]) @@ -54,7 +54,7 @@ class RealmEmojiTest(ZulipTestCase): result = self.client_get("/json/realm/emoji") self.assert_json_success(result) content = result.json() - self.assertEqual(len(content["emoji"]), 2) + self.assert_length(content["emoji"], 2) test_emoji = content["emoji"][str(realm_emoji.id)] self.assertIsNone(test_emoji["author_id"]) @@ -73,7 +73,7 @@ class RealmEmojiTest(ZulipTestCase): result = self.client_get("/json/realm/emoji") content = result.json() self.assert_json_success(result) - self.assertEqual(len(content["emoji"]), 2) + self.assert_length(content["emoji"], 2) test_emoji = content["emoji"][str(realm_emoji.id)] self.assertIn("author_id", test_emoji) author = UserProfile.objects.get(id=test_emoji["author_id"]) @@ -147,7 +147,7 @@ class RealmEmojiTest(ZulipTestCase): self.assert_json_success(result) # We only mark an emoji as deactivated instead of # removing it from the database. - self.assertEqual(len(emojis), 2) + self.assert_length(emojis, 2) test_emoji = emojis[str(realm_emoji.id)] self.assertEqual(test_emoji["deactivated"], True) @@ -237,7 +237,7 @@ class RealmEmojiTest(ZulipTestCase): result = self.client_get("/json/realm/emoji") emojis = result.json()["emoji"] self.assert_json_success(result) - self.assertEqual(len(emojis), 3) + self.assert_length(emojis, 3) def test_failed_file_upload(self) -> None: self.login("iago") diff --git a/zerver/tests/test_realm_export.py b/zerver/tests/test_realm_export.py index 61a35af3e1..06cca60b89 100644 --- a/zerver/tests/test_realm_export.py +++ b/zerver/tests/test_realm_export.py @@ -171,7 +171,7 @@ class RealmExportTest(ZulipTestCase): self.login_user(admin) current_log = RealmAuditLog.objects.filter(event_type=RealmAuditLog.REALM_EXPORTED) - self.assertEqual(len(current_log), 0) + self.assert_length(current_log, 0) exports = [] for i in range(0, 5): diff --git a/zerver/tests/test_realm_linkifiers.py b/zerver/tests/test_realm_linkifiers.py index 2b0874f321..4291a5402d 100644 --- a/zerver/tests/test_realm_linkifiers.py +++ b/zerver/tests/test_realm_linkifiers.py @@ -17,7 +17,7 @@ class RealmFilterTest(ZulipTestCase): result = self.client_get("/json/realm/linkifiers") self.assert_json_success(result) linkifiers = result.json()["linkifiers"] - self.assertEqual(len(linkifiers), 1) + self.assert_length(linkifiers, 1) self.assertEqual(linkifiers[0]["pattern"], "#(?P[123])") self.assertEqual(linkifiers[0]["url_format"], "https://realm.com/my_realm_filter/%(id)s") @@ -147,7 +147,7 @@ class RealmFilterTest(ZulipTestCase): result = self.client_get("/json/realm/linkifiers") self.assert_json_success(result) linkifier = result.json()["linkifiers"] - self.assertEqual(len(linkifier), 1) + self.assert_length(linkifier, 1) self.assertEqual(linkifier[0]["pattern"], "#(?P[0-9]+)") self.assertEqual( linkifier[0]["url_format"], "https://realm.com/my_realm_filter/issues/%(id)s" diff --git a/zerver/tests/test_retention.py b/zerver/tests/test_retention.py index 17e3ee0484..177064af83 100644 --- a/zerver/tests/test_retention.py +++ b/zerver/tests/test_retention.py @@ -439,7 +439,7 @@ class TestArchiveMessagesGeneral(ArchiveMessagesTestingBase): self._verify_archive_data(expired_msg_ids, expired_usermsg_ids) transactions = ArchiveTransaction.objects.all() - self.assertEqual(len(transactions), 2) # With chunk_size 4, there should be 2 transactions + self.assert_length(transactions, 2) # With chunk_size 4, there should be 2 transactions restore_all_data_from_archive() transactions[0].refresh_from_db() @@ -451,7 +451,7 @@ class TestArchiveMessagesGeneral(ArchiveMessagesTestingBase): self._verify_archive_data(expired_msg_ids, expired_usermsg_ids) transactions = ArchiveTransaction.objects.order_by("id") - self.assertEqual(len(transactions), 3) + self.assert_length(transactions, 3) archived_messages = ArchivedMessage.objects.filter(id__in=expired_msg_ids) # Check that the re-archived messages are correctly assigned to the new transaction: @@ -492,7 +492,7 @@ class TestArchivingSubMessages(ArchiveMessagesTestingBase): SubMessage.objects.filter(message_id__in=expired_msg_ids).values_list("id", flat=True), ) - self.assertEqual(len(submessage_ids), 3) + self.assert_length(submessage_ids, 3) self.assertEqual(SubMessage.objects.filter(id__in=submessage_ids).count(), 3) archive_messages() self.assertEqual(SubMessage.objects.filter(id__in=submessage_ids).count(), 0) @@ -537,7 +537,7 @@ class TestArchivingReactions(ArchiveMessagesTestingBase): Reaction.objects.filter(message_id__in=expired_msg_ids).values_list("id", flat=True), ) - self.assertEqual(len(reaction_ids), 3) + self.assert_length(reaction_ids, 3) self.assertEqual(Reaction.objects.filter(id__in=reaction_ids).count(), 3) archive_messages() self.assertEqual(Reaction.objects.filter(id__in=reaction_ids).count(), 0) @@ -878,7 +878,7 @@ class TestCleaningArchive(ArchiveMessagesTestingBase): clean_archived_data() remaining_transactions = list(ArchiveTransaction.objects.all()) - self.assertEqual(len(remaining_transactions), 1) + self.assert_length(remaining_transactions, 1) # All transactions except the last one were deleted: self.assertEqual(remaining_transactions[0].id, transactions[-1].id) # And corresponding ArchivedMessages should have been deleted: @@ -1060,7 +1060,7 @@ class TestDoDeleteMessages(ZulipTestCase): archived_messages = ArchivedMessage.objects.filter(id__in=message_ids) self.assertEqual(archived_messages.count(), len(message_ids)) - self.assertEqual(len({message.archive_transaction_id for message in archived_messages}), 1) + self.assert_length({message.archive_transaction_id for message in archived_messages}, 1) def test_old_event_format_processed_correctly(self) -> None: """ diff --git a/zerver/tests/test_send_email.py b/zerver/tests/test_send_email.py index c581db1885..5c347ac30f 100644 --- a/zerver/tests/test_send_email.py +++ b/zerver/tests/test_send_email.py @@ -58,7 +58,7 @@ class TestBuildEmail(ZulipTestCase): from_address=overly_long_address, language="en", ) - self.assertEqual(len(info_log.records), 2) + self.assert_length(info_log.records, 2) self.assertEqual( info_log.output[0], f"INFO:{logger.name}:Sending password_reset email to {mail.to}" ) @@ -85,7 +85,7 @@ class TestBuildEmail(ZulipTestCase): from_address=address, language="en", ) - self.assertEqual(len(info_log.records), 2) + self.assert_length(info_log.records, 2) self.assertEqual( info_log.output[0], f"INFO:{logger.name}:Sending password_reset email to {[hamlet]}" ) @@ -163,7 +163,7 @@ class TestSendEmail(ZulipTestCase): from_address=FromAddress.NOREPLY, language="en", ) - self.assertEqual(len(info_log.records), 2) + self.assert_length(info_log.records, 2) self.assertEqual( info_log.output[0], f"INFO:{logger.name}:Sending password_reset email to {mail.to}", diff --git a/zerver/tests/test_service_bot_system.py b/zerver/tests/test_service_bot_system.py index 775f80318a..3a364a8342 100644 --- a/zerver/tests/test_service_bot_system.py +++ b/zerver/tests/test_service_bot_system.py @@ -82,7 +82,7 @@ class TestServiceBotBasics(ZulipTestCase): recipient_type=Recipient.STREAM, ) - self.assertEqual(len(event_dict), 0) + self.assert_length(event_dict, 0) def test_service_events_for_stream_mentions(self) -> None: sender = self.example_user("hamlet") @@ -136,7 +136,7 @@ class TestServiceBotBasics(ZulipTestCase): recipient_type=Recipient.PERSONAL, ) - self.assertEqual(len(event_dict), 0) + self.assert_length(event_dict, 0) def test_service_events_with_unexpected_bot_type(self) -> None: hamlet = self.example_user("hamlet") @@ -161,7 +161,7 @@ class TestServiceBotBasics(ZulipTestCase): recipient_type=Recipient.PERSONAL, ) - self.assertEqual(len(event_dict), 0) + self.assert_length(event_dict, 0) self.assertEqual( m.output, [f"ERROR:root:Unexpected bot_type for Service bot id={bot.id}: {wrong_bot_type}"], @@ -398,12 +398,12 @@ class TestServiceBotConfigHandler(ZulipTestCase): def test_load_bot_config_template(self) -> None: bot_config = load_bot_config_template("giphy") self.assertTrue(isinstance(bot_config, dict)) - self.assertEqual(len(bot_config), 1) + self.assert_length(bot_config, 1) def test_load_bot_config_template_for_bot_without_config_data(self) -> None: bot_config = load_bot_config_template("converter") self.assertTrue(isinstance(bot_config, dict)) - self.assertEqual(len(bot_config), 0) + self.assert_length(bot_config, 0) def test_bot_send_pm_with_empty_recipients_list(self) -> None: with self.assertRaisesRegex( diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.py index 2747b3bd2e..9948da3a4a 100644 --- a/zerver/tests/test_signup.py +++ b/zerver/tests/test_signup.py @@ -292,7 +292,7 @@ class AddNewUserHistoryTest(ZulipTestCase): .exclude(message_id=race_message_id) .order_by("-message_id")[0:ONBOARDING_UNREAD_MESSAGES] ) - self.assertEqual(len(latest_messages), 2) + self.assert_length(latest_messages, 2) for msg in latest_messages: self.assertFalse(msg.flags.read.is_set) @@ -489,7 +489,7 @@ class PasswordResetTest(ZulipTestCase): # Check that the password reset email is from a noreply address. from django.core.mail import outbox - self.assertEqual(len(outbox), 0) + self.assert_length(outbox, 0) @override_settings(RATE_LIMITING=True) def test_rate_limiting(self) -> None: @@ -564,7 +564,7 @@ class PasswordResetTest(ZulipTestCase): from django.core.mail import outbox - self.assertEqual(len(outbox), 0) + self.assert_length(outbox, 0) @override_settings( AUTHENTICATION_BACKENDS=( @@ -593,7 +593,7 @@ class PasswordResetTest(ZulipTestCase): from django.core.mail import outbox - self.assertEqual(len(outbox), 0) + self.assert_length(outbox, 0) @override_settings( AUTHENTICATION_BACKENDS=( @@ -615,7 +615,7 @@ class PasswordResetTest(ZulipTestCase): ) from django.core.mail import outbox - self.assertEqual(len(outbox), 0) + self.assert_length(outbox, 0) # If the domain doesn't match, we do generate an email with self.settings(LDAP_APPEND_DOMAIN="example.com"): @@ -773,13 +773,13 @@ class LoginTest(ZulipTestCase): with queries_captured() as queries, cache_tries_captured() as cache_tries: self.register(self.nonreg_email("test"), "test") # Ensure the number of queries we make is not O(streams) - self.assertEqual(len(queries), 70) + self.assert_length(queries, 70) # We can probably avoid a couple cache hits here, but there doesn't # seem to be any O(N) behavior. Some of the cache hits are related # to sending messages, such as getting the welcome bot, looking up # the alert words for a realm, etc. - self.assertEqual(len(cache_tries), 16) + self.assert_length(cache_tries, 16) user_profile = self.nonreg_user("test") self.assert_logged_in_user_id(user_profile.id) @@ -933,7 +933,7 @@ class InviteUserBase(ZulipTestCase): ) -> None: from django.core.mail import outbox - self.assertEqual(len(outbox), len(correct_recipients)) + self.assert_length(outbox, len(correct_recipients)) email_recipients = [email.recipients()[0] for email in outbox] self.assertEqual(sorted(email_recipients), sorted(correct_recipients)) if len(outbox) == 0: @@ -1811,11 +1811,11 @@ so we didn't send them an invitation. We did send invitations to everyone else!" email_jobs_to_deliver = ScheduledEmail.objects.filter( scheduled_timestamp__lte=timezone_now() ) - self.assertEqual(len(email_jobs_to_deliver), 1) + self.assert_length(email_jobs_to_deliver, 1) email_count = len(outbox) for job in email_jobs_to_deliver: deliver_scheduled_emails(job) - self.assertEqual(len(outbox), email_count + 1) + self.assert_length(outbox, email_count + 1) self.assertEqual(self.email_envelope_from(outbox[-1]), settings.NOREPLY_EMAIL_ADDRESS) self.assertIn(FromAddress.NOREPLY, self.email_display_from(outbox[-1])) @@ -1833,13 +1833,13 @@ so we didn't send them an invitation. We did send invitations to everyone else!" email_jobs_to_deliver = ScheduledEmail.objects.filter( scheduled_timestamp__lte=timezone_now(), type=ScheduledEmail.INVITATION_REMINDER ) - self.assertEqual(len(email_jobs_to_deliver), 1) + self.assert_length(email_jobs_to_deliver, 1) self.register(invitee_email, "test") email_jobs_to_deliver = ScheduledEmail.objects.filter( scheduled_timestamp__lte=timezone_now(), type=ScheduledEmail.INVITATION_REMINDER ) - self.assertEqual(len(email_jobs_to_deliver), 0) + self.assert_length(email_jobs_to_deliver, 0) def test_no_invitation_reminder_when_link_expires_quickly(self) -> None: self.login("hamlet") @@ -1919,7 +1919,7 @@ so we didn't send them an invitation. We did send invitations to everyone else!" do_invite_users(lear_user, ["foo@zulip.com"], [], False) invites = PreregistrationUser.objects.filter(email__iexact="foo@zulip.com") - self.assertEqual(len(invites), 4) + self.assert_length(invites, 4) do_create_user( "foo@zulip.com", @@ -1938,7 +1938,7 @@ so we didn't send them an invitation. We did send invitations to everyone else!" ) # If a user was invited more than once, when it accepts one invite and register # the others must be canceled. - self.assertEqual(len(accepted_invite), 1) + self.assert_length(accepted_invite, 1) self.assertEqual(accepted_invite[0].id, prereg_user.id) expected_revoked_invites = set(invites.exclude(id=prereg_user.id).exclude(realm=lear)) @@ -2032,9 +2032,9 @@ class InvitationsTestCase(InviteUserBase): referred_by=user_profile, realm=user_profile.realm ) create_confirmation_link(multiuse_invite, Confirmation.MULTIUSE_INVITE) - self.assertEqual(len(do_get_user_invites(user_profile)), 5) - self.assertEqual(len(do_get_user_invites(hamlet)), 1) - self.assertEqual(len(do_get_user_invites(othello)), 1) + self.assert_length(do_get_user_invites(user_profile), 5) + self.assert_length(do_get_user_invites(hamlet), 1) + self.assert_length(do_get_user_invites(othello), 1) def test_successful_get_open_invitations(self) -> None: """ @@ -2077,7 +2077,7 @@ class InvitationsTestCase(InviteUserBase): result = self.client_get("/json/invites") self.assertEqual(result.status_code, 200) invites = orjson.loads(result.content)["invites"] - self.assertEqual(len(invites), 2) + self.assert_length(invites, 2) self.assertFalse(invites[0]["is_multiuse"]) self.assertEqual(invites[0]["email"], "TestOne@zulip.com") @@ -2276,7 +2276,7 @@ class InvitationsTestCase(InviteUserBase): self.assert_json_success(self.invite(invitee, ["Denmark"])) # Verify hamlet has only one invitation (Member can resend invitations only sent by him). invitation = PreregistrationUser.objects.filter(referred_by=user_profile) - self.assertEqual(len(invitation), 1) + self.assert_length(invitation, 1) prereg_user = PreregistrationUser.objects.get(email=invitee) # Verify and then clear from the outbox the original invite email @@ -2807,13 +2807,13 @@ class RealmCreationTest(ZulipTestCase): stream = get_stream(stream_name, realm) recipient = stream.recipient messages = Message.objects.filter(recipient=recipient).order_by("date_sent") - self.assertEqual(len(messages), message_count) + self.assert_length(messages, message_count) self.assertIn(text, messages[0].content) # Check signup messages recipient = signups_stream.recipient messages = Message.objects.filter(recipient=recipient).order_by("id") - self.assertEqual(len(messages), 2) + self.assert_length(messages, 2) self.assertIn("Signups enabled", messages[0].content) self.assertIn("signed up", messages[1].content) self.assertEqual("zuliptest", messages[1].topic_name()) @@ -4578,7 +4578,7 @@ class UserSignUpTest(InviteUserBase): user_profile = UserProfile.objects.get(delivery_email=self.nonreg_email("newuser")) self.assertTrue(user_profile.is_realm_admin) sub = get_stream_subscriptions_for_user(user_profile).filter(recipient__type_id=stream.id) - self.assertEqual(len(sub), 1) + self.assert_length(sub, 1) def test_registration_when_name_changes_are_disabled(self) -> None: """ @@ -4937,7 +4937,7 @@ class TestFindMyTeam(ZulipTestCase): from django.core.mail import outbox # 3 = 1 + 2 -- Cordelia gets an email each for the "zulip" and "lear" realms. - self.assertEqual(len(outbox), 3) + self.assert_length(outbox, 3) def test_find_team_ignore_invalid_email(self) -> None: result = self.client_post( @@ -4954,7 +4954,7 @@ class TestFindMyTeam(ZulipTestCase): self.assertIn("invalid_email@", content) from django.core.mail import outbox - self.assertEqual(len(outbox), 1) + self.assert_length(outbox, 1) def test_find_team_reject_invalid_email(self) -> None: result = self.client_post("/accounts/find/", dict(emails="invalid_string")) @@ -4962,7 +4962,7 @@ class TestFindMyTeam(ZulipTestCase): self.assertIn(b"Enter a valid email", result.content) from django.core.mail import outbox - self.assertEqual(len(outbox), 0) + self.assert_length(outbox, 0) # Just for coverage on perhaps-unnecessary validation code. result = self.client_get("/accounts/find/", {"emails": "invalid"}) @@ -4975,7 +4975,7 @@ class TestFindMyTeam(ZulipTestCase): self.assertEqual(result.status_code, 200) from django.core.mail import outbox - self.assertEqual(len(outbox), 0) + self.assert_length(outbox, 0) def test_find_team_one_email(self) -> None: data = {"emails": self.example_email("hamlet")} @@ -4984,7 +4984,7 @@ class TestFindMyTeam(ZulipTestCase): self.assertEqual(result.url, "/accounts/find/?emails=hamlet%40zulip.com") from django.core.mail import outbox - self.assertEqual(len(outbox), 1) + self.assert_length(outbox, 1) def test_find_team_deactivated_user(self) -> None: do_deactivate_user(self.example_user("hamlet"), acting_user=None) @@ -4994,7 +4994,7 @@ class TestFindMyTeam(ZulipTestCase): self.assertEqual(result.url, "/accounts/find/?emails=hamlet%40zulip.com") from django.core.mail import outbox - self.assertEqual(len(outbox), 0) + self.assert_length(outbox, 0) def test_find_team_deactivated_realm(self) -> None: do_deactivate_realm(get_realm("zulip"), acting_user=None) @@ -5004,7 +5004,7 @@ class TestFindMyTeam(ZulipTestCase): self.assertEqual(result.url, "/accounts/find/?emails=hamlet%40zulip.com") from django.core.mail import outbox - self.assertEqual(len(outbox), 0) + self.assert_length(outbox, 0) def test_find_team_bot_email(self) -> None: data = {"emails": self.example_email("webhook_bot")} @@ -5013,7 +5013,7 @@ class TestFindMyTeam(ZulipTestCase): self.assertEqual(result.url, "/accounts/find/?emails=webhook-bot%40zulip.com") from django.core.mail import outbox - self.assertEqual(len(outbox), 0) + self.assert_length(outbox, 0) def test_find_team_more_than_ten_emails(self) -> None: data = {"emails": ",".join(f"hamlet-{i}@zulip.com" for i in range(11))} @@ -5022,7 +5022,7 @@ class TestFindMyTeam(ZulipTestCase): self.assertIn("Please enter at most 10", result.content.decode("utf8")) from django.core.mail import outbox - self.assertEqual(len(outbox), 0) + self.assert_length(outbox, 0) class ConfirmationKeyTest(ZulipTestCase): diff --git a/zerver/tests/test_slack_importer.py b/zerver/tests/test_slack_importer.py index bce668aee8..7da2060813 100644 --- a/zerver/tests/test_slack_importer.py +++ b/zerver/tests/test_slack_importer.py @@ -174,7 +174,7 @@ class SlackImporter(ZulipTestCase): fetch_shared_channel_users(users, slack_data_dir, "token") # Normal users - self.assertEqual(len(users), 5) + self.assert_length(users, 5) self.assertEqual(users[0]["id"], "U061A1R2R") self.assertEqual(users[0]["is_mirror_dummy"], False) self.assertFalse("team_domain" in users[0]) @@ -386,7 +386,7 @@ class SlackImporter(ZulipTestCase): for name in cpf_name: self.assertTrue(name.startswith("Slack custom field ")) - self.assertEqual(len(customprofilefield_value), 6) + self.assert_length(customprofilefield_value, 6) self.assertEqual(customprofilefield_value[0]["field"], 0) self.assertEqual(customprofilefield_value[0]["user_profile"], 1) self.assertEqual(customprofilefield_value[3]["user_profile"], 0) @@ -394,9 +394,9 @@ class SlackImporter(ZulipTestCase): # test that the primary owner should always be imported first self.assertDictEqual(slack_user_id_to_zulip_user_id, test_slack_user_id_to_zulip_user_id) - self.assertEqual(len(avatar_list), 8) + self.assert_length(avatar_list, 8) - self.assertEqual(len(zerver_userprofile), 8) + self.assert_length(zerver_userprofile, 8) self.assertEqual(zerver_userprofile[0]["is_staff"], False) self.assertEqual(zerver_userprofile[0]["is_bot"], False) @@ -664,14 +664,14 @@ class SlackImporter(ZulipTestCase): passed_realm["zerver_realm"][0]["description"], "Organization imported from Slack!" ) self.assertEqual(passed_realm["zerver_userpresence"], []) - self.assertEqual(len(passed_realm.keys()), 15) + self.assert_length(passed_realm.keys(), 15) self.assertEqual(realm["zerver_stream"], []) self.assertEqual(realm["zerver_userprofile"], []) self.assertEqual(realm["zerver_realmemoji"], []) self.assertEqual(realm["zerver_customprofilefield"], []) self.assertEqual(realm["zerver_customprofilefieldvalue"], []) - self.assertEqual(len(realm.keys()), 5) + self.assert_length(realm.keys(), 5) def test_get_message_sending_user(self) -> None: message_with_file = {"subtype": "file", "type": "message", "file": {"user": "U064KUGRJ"}} @@ -865,7 +865,7 @@ class SlackImporter(ZulipTestCase): # functioning already tested in helper function self.assertEqual(zerver_usermessage, []) # subtype: channel_join is filtered - self.assertEqual(len(zerver_message), 9) + self.assert_length(zerver_message, 9) self.assertEqual(uploads, []) self.assertEqual(attachment, []) @@ -1050,7 +1050,7 @@ class SlackImporter(ZulipTestCase): self.assertTrue(os.path.exists(realm_icon_records_path)) with open(realm_icon_records_path, "rb") as f: records = orjson.loads(f.read()) - self.assertEqual(len(records), 2) + self.assert_length(records, 2) self.assertEqual(records[0]["path"], "0/icon.original") self.assertTrue(os.path.exists(os.path.join(realm_icons_path, records[0]["path"]))) @@ -1133,8 +1133,8 @@ class SlackImporter(ZulipTestCase): zerver_attachment=zerver_attachment, uploads_list=uploads_list, ) - self.assertEqual(len(zerver_attachment), 1) - self.assertEqual(len(uploads_list), 1) + self.assert_length(zerver_attachment, 1) + self.assert_length(uploads_list, 1) image_path = zerver_attachment[0]["path_id"] self.assertIn("/SlackImportAttachment/", image_path) diff --git a/zerver/tests/test_slack_message_conversion.py b/zerver/tests/test_slack_message_conversion.py index 7978058c49..081809dd7f 100644 --- a/zerver/tests/test_slack_message_conversion.py +++ b/zerver/tests/test_slack_message_conversion.py @@ -40,7 +40,7 @@ class SlackMessageConversion(ZulipTestCase): for name, test in format_tests.items(): # Check that there aren't any unexpected keys as those are often typos - self.assertEqual(len(set(test.keys()) - valid_keys), 0) + self.assert_length(set(test.keys()) - valid_keys, 0) slack_user_map: Dict[str, int] = {} users: List[Dict[str, Any]] = [{}] channel_map: Dict[str, Tuple[str, int]] = {} diff --git a/zerver/tests/test_soft_deactivation.py b/zerver/tests/test_soft_deactivation.py index b721aafb91..aee0008032 100644 --- a/zerver/tests/test_soft_deactivation.py +++ b/zerver/tests/test_soft_deactivation.py @@ -280,7 +280,7 @@ class UserSoftDeactivationTests(ZulipTestCase): received_count = UserMessage.objects.filter( user_profile__in=users, message_id=message_id ).count() - self.assertEqual(len(users), received_count) + self.assert_length(users, received_count) # Verify that deactivated users are NOT caught up if # AUTO_CATCH_UP_SOFT_DEACTIVATED_USERS is off @@ -349,7 +349,7 @@ class SoftDeactivationMessageTest(ZulipTestCase): long_term_idle_user, ) idle_user_msg_list = get_user_messages(long_term_idle_user) - self.assertEqual(len(idle_user_msg_list), idle_user_msg_count + 1) + self.assert_length(idle_user_msg_list, idle_user_msg_count + 1) self.assertEqual(idle_user_msg_list[-1].content, message) long_term_idle_user.refresh_from_db() self.assertEqual(long_term_idle_user.last_active_message_id, message_id) @@ -401,7 +401,7 @@ class SoftDeactivationMessageTest(ZulipTestCase): add_missing_messages(long_term_idle_user) self.assert_length(queries, 6) idle_user_msg_list = get_user_messages(long_term_idle_user) - self.assertEqual(len(idle_user_msg_list), idle_user_msg_count + 1) + self.assert_length(idle_user_msg_list, idle_user_msg_count + 1) self.assertEqual(idle_user_msg_list[-1], sent_message) long_term_idle_user.refresh_from_db() self.assertEqual(long_term_idle_user.last_active_message_id, sent_message.id) @@ -418,7 +418,7 @@ class SoftDeactivationMessageTest(ZulipTestCase): add_missing_messages(long_term_idle_user) self.assert_length(queries, 7) idle_user_msg_list = get_user_messages(long_term_idle_user) - self.assertEqual(len(idle_user_msg_list), idle_user_msg_count + 1) + self.assert_length(idle_user_msg_list, idle_user_msg_count + 1) self.assertEqual(idle_user_msg_list[-1], sent_message) long_term_idle_user.refresh_from_db() self.assertEqual(long_term_idle_user.last_active_message_id, sent_message.id) @@ -443,7 +443,7 @@ class SoftDeactivationMessageTest(ZulipTestCase): add_missing_messages(long_term_idle_user) self.assert_length(queries, 6) idle_user_msg_list = get_user_messages(long_term_idle_user) - self.assertEqual(len(idle_user_msg_list), idle_user_msg_count + 2) + self.assert_length(idle_user_msg_list, idle_user_msg_count + 2) for sent_message in sent_message_list: self.assertEqual(idle_user_msg_list.pop(), sent_message) long_term_idle_user.refresh_from_db() @@ -475,7 +475,7 @@ class SoftDeactivationMessageTest(ZulipTestCase): add_missing_messages(long_term_idle_user) self.assert_length(queries, 6) idle_user_msg_list = get_user_messages(long_term_idle_user) - self.assertEqual(len(idle_user_msg_list), idle_user_msg_count + 2) + self.assert_length(idle_user_msg_list, idle_user_msg_count + 2) for sent_message in sent_message_list: self.assertEqual(idle_user_msg_list.pop(), sent_message) long_term_idle_user.refresh_from_db() @@ -511,7 +511,7 @@ class SoftDeactivationMessageTest(ZulipTestCase): self.assert_length(queries, 4) idle_user_msg_list = get_user_messages(long_term_idle_user) # No new UserMessage rows should have been created. - self.assertEqual(len(idle_user_msg_list), idle_user_msg_count) + self.assert_length(idle_user_msg_list, idle_user_msg_count) # Note: At this point in this test we have long_term_idle_user # unsubscribed from the 'Denmark' stream. @@ -537,7 +537,7 @@ class SoftDeactivationMessageTest(ZulipTestCase): add_missing_messages(long_term_idle_user) self.assert_length(queries, 6) idle_user_msg_list = get_user_messages(long_term_idle_user) - self.assertEqual(len(idle_user_msg_list), idle_user_msg_count + 2) + self.assert_length(idle_user_msg_list, idle_user_msg_count + 2) for sent_message in sent_message_list: self.assertEqual(idle_user_msg_list.pop(), sent_message) long_term_idle_user.refresh_from_db() @@ -575,7 +575,7 @@ class SoftDeactivationMessageTest(ZulipTestCase): add_missing_messages(long_term_idle_user) self.assert_length(queries, 10) idle_user_msg_list = get_user_messages(long_term_idle_user) - self.assertEqual(len(idle_user_msg_list), idle_user_msg_count + num_new_messages) + self.assert_length(idle_user_msg_list, idle_user_msg_count + num_new_messages) long_term_idle_user.refresh_from_db() self.assertEqual(long_term_idle_user.last_active_message_id, message_ids[-1]) @@ -619,7 +619,7 @@ class SoftDeactivationMessageTest(ZulipTestCase): def assert_um_count(user: UserProfile, count: int) -> None: user_messages = get_user_messages(user) - self.assertEqual(len(user_messages), count) + self.assert_length(user_messages, count) def assert_last_um_content(user: UserProfile, content: str, negate: bool = False) -> None: user_messages = get_user_messages(user) diff --git a/zerver/tests/test_submessage.py b/zerver/tests/test_submessage.py index b269020511..edd4bfe96b 100644 --- a/zerver/tests/test_submessage.py +++ b/zerver/tests/test_submessage.py @@ -137,7 +137,7 @@ class TestBasics(ZulipTestCase): self.assertIn(hamlet.id, users) rows = SubMessage.get_raw_db_rows([message_id]) - self.assertEqual(len(rows), 1) + self.assert_length(rows, 1) row = rows[0] expected_data = dict( diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.py index 5848e2a639..d909cf8922 100644 --- a/zerver/tests/test_subs.py +++ b/zerver/tests/test_subs.py @@ -141,7 +141,7 @@ class TestCreateStreams(ZulipTestCase): self.assertEqual(events[0]["event"]["type"], "stream") self.assertEqual(events[0]["event"]["op"], "create") # Send private stream creation event to only realm admins. - self.assertEqual(len(events[0]["users"]), 2) + self.assert_length(events[0]["users"], 2) self.assertTrue(self.example_user("iago").id in events[0]["users"]) self.assertTrue(self.example_user("desdemona").id in events[0]["users"]) self.assertEqual(events[0]["event"]["streams"][0]["name"], "Private stream") @@ -160,8 +160,8 @@ class TestCreateStreams(ZulipTestCase): ], ) - self.assertEqual(len(new_streams), 3) - self.assertEqual(len(existing_streams), 0) + self.assert_length(new_streams, 3) + self.assert_length(existing_streams, 0) actual_stream_names = {stream.name for stream in new_streams} self.assertEqual(actual_stream_names, set(stream_names)) @@ -180,8 +180,8 @@ class TestCreateStreams(ZulipTestCase): ], ) - self.assertEqual(len(new_streams), 0) - self.assertEqual(len(existing_streams), 3) + self.assert_length(new_streams, 0) + self.assert_length(existing_streams, 3) actual_stream_names = {stream.name for stream in existing_streams} self.assertEqual(actual_stream_names, set(stream_names)) @@ -234,8 +234,8 @@ class TestCreateStreams(ZulipTestCase): created, existing = create_streams_if_needed(realm, stream_dicts) - self.assertEqual(len(created), 5) - self.assertEqual(len(existing), 0) + self.assert_length(created, 5) + self.assert_length(existing, 0) for stream in created: if stream.name == "publicstream": self.assertTrue(stream.history_public_to_subscribers) @@ -335,7 +335,7 @@ class TestCreateStreams(ZulipTestCase): hamlet_unread_messages = get_unread_stream_data(hamlet) # The stream creation messages should be unread for Hamlet - self.assertEqual(len(hamlet_unread_messages), 2) + self.assert_length(hamlet_unread_messages, 2) # According to the code in zerver/views/streams/add_subscriptions_backend # the notification stream message is sent first, then the new stream's message. @@ -343,7 +343,7 @@ class TestCreateStreams(ZulipTestCase): self.assertEqual(hamlet_unread_messages[1]["stream_id"], stream_id) # But it should be marked as read for Iago, the stream creator. - self.assertEqual(len(iago_unread_messages), 0) + self.assert_length(iago_unread_messages, 0) class RecipientTest(ZulipTestCase): @@ -881,7 +881,7 @@ class StreamAdminTest(ZulipTestCase): {"new_name": "stream_rename"}, ) self.assert_json_success(result) - self.assertEqual(len(events), 3) + self.assert_length(events, 3) stream_rename_exists = get_stream("stream_rename", realm) self.assertTrue(stream_rename_exists) @@ -1396,7 +1396,7 @@ class StreamAdminTest(ZulipTestCase): self.assertEqual(sub_events, []) stream_events = [e for e in events if e["event"]["type"] == "stream"] - self.assertEqual(len(stream_events), 1) + self.assert_length(stream_events, 1) event = stream_events[0]["event"] self.assertEqual(event["op"], "delete") self.assertEqual(event["streams"][0]["stream_id"], stream.id) @@ -1578,8 +1578,8 @@ class StreamAdminTest(ZulipTestCase): target_users_subbed=True, ) json = self.assert_json_success(result) - self.assertEqual(len(json["removed"]), 1) - self.assertEqual(len(json["not_removed"]), 0) + self.assert_length(json["removed"], 1) + self.assert_length(json["not_removed"], 0) def test_realm_admin_remove_multiple_users_from_stream(self) -> None: """ @@ -1605,8 +1605,8 @@ class StreamAdminTest(ZulipTestCase): target_users_subbed=True, ) json = self.assert_json_success(result) - self.assertEqual(len(json["removed"]), 5) - self.assertEqual(len(json["not_removed"]), 0) + self.assert_length(json["removed"], 5) + self.assert_length(json["not_removed"], 0) def test_realm_admin_remove_others_from_subbed_private_stream(self) -> None: """ @@ -1622,8 +1622,8 @@ class StreamAdminTest(ZulipTestCase): target_users_subbed=True, ) json = self.assert_json_success(result) - self.assertEqual(len(json["removed"]), 1) - self.assertEqual(len(json["not_removed"]), 0) + self.assert_length(json["removed"], 1) + self.assert_length(json["not_removed"], 0) def test_realm_admin_remove_others_from_unsubbed_private_stream(self) -> None: """ @@ -1640,8 +1640,8 @@ class StreamAdminTest(ZulipTestCase): other_sub_users=[self.example_user("othello")], ) json = self.assert_json_success(result) - self.assertEqual(len(json["removed"]), 1) - self.assertEqual(len(json["not_removed"]), 0) + self.assert_length(json["removed"], 1) + self.assert_length(json["not_removed"], 0) def test_stream_admin_remove_others_from_public_stream(self) -> None: """ @@ -1657,8 +1657,8 @@ class StreamAdminTest(ZulipTestCase): target_users_subbed=True, ) json = self.assert_json_success(result) - self.assertEqual(len(json["removed"]), 1) - self.assertEqual(len(json["not_removed"]), 0) + self.assert_length(json["removed"], 1) + self.assert_length(json["not_removed"], 0) def test_stream_admin_remove_multiple_users_from_stream(self) -> None: """ @@ -1678,8 +1678,8 @@ class StreamAdminTest(ZulipTestCase): target_users_subbed=True, ) json = self.assert_json_success(result) - self.assertEqual(len(json["removed"]), 5) - self.assertEqual(len(json["not_removed"]), 0) + self.assert_length(json["removed"], 5) + self.assert_length(json["not_removed"], 0) def test_stream_admin_remove_others_from_private_stream(self) -> None: """ @@ -1695,8 +1695,8 @@ class StreamAdminTest(ZulipTestCase): target_users_subbed=True, ) json = self.assert_json_success(result) - self.assertEqual(len(json["removed"]), 1) - self.assertEqual(len(json["not_removed"]), 0) + self.assert_length(json["removed"], 1) + self.assert_length(json["not_removed"], 0) def test_cant_remove_others_from_stream_legacy_emails(self) -> None: result = self.attempt_unsubscribe_of_principal( @@ -1722,8 +1722,8 @@ class StreamAdminTest(ZulipTestCase): using_legacy_emails=True, ) json = self.assert_json_success(result) - self.assertEqual(len(json["removed"]), 1) - self.assertEqual(len(json["not_removed"]), 0) + self.assert_length(json["removed"], 1) + self.assert_length(json["not_removed"], 0) def test_admin_remove_multiple_users_from_stream_legacy_emails(self) -> None: result = self.attempt_unsubscribe_of_principal( @@ -1736,8 +1736,8 @@ class StreamAdminTest(ZulipTestCase): using_legacy_emails=True, ) json = self.assert_json_success(result) - self.assertEqual(len(json["removed"]), 2) - self.assertEqual(len(json["not_removed"]), 0) + self.assert_length(json["removed"], 2) + self.assert_length(json["not_removed"], 0) def test_create_stream_policy_setting(self) -> None: """ @@ -1897,8 +1897,8 @@ class StreamAdminTest(ZulipTestCase): target_users_subbed=False, ) json = self.assert_json_success(result) - self.assertEqual(len(json["removed"]), 0) - self.assertEqual(len(json["not_removed"]), 1) + self.assert_length(json["removed"], 0) + self.assert_length(json["not_removed"], 1) def test_remove_invalid_user(self) -> None: """ @@ -2005,7 +2005,7 @@ class DefaultStreamTest(ZulipTestCase): unsubscribed = sub_info.unsubscribed never_subscribed = sub_info.never_subscribed - self.assertEqual(len(streams), len(subscribed) + len(unsubscribed) + len(never_subscribed)) + self.assert_length(streams, len(subscribed) + len(unsubscribed) + len(never_subscribed)) expected_streams = subscribed + unsubscribed + never_subscribed stream_names = [stream["name"] for stream in streams] expected_stream_names = [stream["name"] for stream in expected_streams] @@ -3097,7 +3097,7 @@ class SubscriptionAPITest(ZulipTestCase): self.streams + add_streams, self.test_realm, ) - self.assertEqual(len(events), 7) + self.assert_length(events, 7) expected_stream_ids = {get_stream(stream, self.test_realm).id for stream in add_streams} @@ -3553,7 +3553,7 @@ class SubscriptionAPITest(ZulipTestCase): ) self.assertNotIn(self.example_user("polonius").id, add_peer_event["users"]) - self.assertEqual(len(add_peer_event["users"]), 12) + self.assert_length(add_peer_event["users"], 12) self.assertEqual(add_peer_event["event"]["type"], "subscription") self.assertEqual(add_peer_event["event"]["op"], "peer_add") self.assertEqual(add_peer_event["event"]["user_ids"], [self.user_profile.id]) @@ -3585,7 +3585,7 @@ class SubscriptionAPITest(ZulipTestCase): # We don't send a peer_add event to othello self.assertNotIn(user_profile.id, add_peer_event["users"]) self.assertNotIn(self.example_user("polonius").id, add_peer_event["users"]) - self.assertEqual(len(add_peer_event["users"]), 12) + self.assert_length(add_peer_event["users"], 12) self.assertEqual(add_peer_event["event"]["type"], "subscription") self.assertEqual(add_peer_event["event"]["op"], "peer_add") self.assertEqual(add_peer_event["event"]["user_ids"], [user_profile.id]) @@ -3626,7 +3626,7 @@ class SubscriptionAPITest(ZulipTestCase): # We don't send a peer_add event to othello, but we do send peer_add event to # all realm admins. self.assertNotIn(user_profile.id, add_peer_event["users"]) - self.assertEqual(len(add_peer_event["users"]), 3) + self.assert_length(add_peer_event["users"], 3) self.assertEqual(add_peer_event["event"]["type"], "subscription") self.assertEqual(add_peer_event["event"]["op"], "peer_add") self.assertEqual(add_peer_event["event"]["user_ids"], [user_profile.id]) @@ -3650,7 +3650,7 @@ class SubscriptionAPITest(ZulipTestCase): self.assertEqual(add_event["event"]["op"], "add") self.assertEqual(add_event["users"], [self.example_user("iago").id]) - self.assertEqual(len(add_peer_event["users"]), 1) + self.assert_length(add_peer_event["users"], 1) self.assertEqual(add_peer_event["event"]["type"], "subscription") self.assertEqual(add_peer_event["event"]["op"], "peer_add") self.assertEqual(add_peer_event["event"]["user_ids"], [self.example_user("iago").id]) @@ -4907,7 +4907,7 @@ class GetSubscribersTest(ZulipTestCase): never_subscribed = get_never_subscribed() # Invite only stream should not be there in never_subscribed streams - self.assertEqual(len(never_subscribed), len(public_streams) + len(web_public_streams)) + self.assert_length(never_subscribed, len(public_streams) + len(web_public_streams)) for stream_dict in never_subscribed: name = stream_dict["name"] self.assertFalse("invite_only" in name) @@ -4936,7 +4936,7 @@ class GetSubscribersTest(ZulipTestCase): never_sub = helper_result.never_subscribed # It's +1 because of the stream Rome. - self.assertEqual(len(never_sub), len(web_public_streams) + 1) + self.assert_length(never_sub, len(web_public_streams) + 1) sub_ids = list(map(lambda stream: stream["stream_id"], sub)) unsub_ids = list(map(lambda stream: stream["stream_id"], unsub)) @@ -4949,7 +4949,7 @@ class GetSubscribersTest(ZulipTestCase): # subscribers not set up by this test, so we do the # following check only for the streams we created. if stream_dict["name"] in web_public_streams: - self.assertEqual(len(stream_dict["subscribers"]), len(users_to_subscribe)) + self.assert_length(stream_dict["subscribers"], len(users_to_subscribe)) test_guest_user_case() @@ -4982,7 +4982,7 @@ class GetSubscribersTest(ZulipTestCase): for sub in subs: if sub["name"] == stream_name_sub: expected_stream_exists = True - self.assertEqual(len(sub["subscribers"]), 2) + self.assert_length(sub["subscribers"], 2) self.assertTrue(expected_stream_exists) # Guest user only get data about never subscribed streams if they're @@ -4991,7 +4991,7 @@ class GetSubscribersTest(ZulipTestCase): self.assertTrue(stream["is_web_public"]) # Guest user only get data about never subscribed web-public streams - self.assertEqual(len(neversubs), 1) + self.assert_length(neversubs, 1) def test_previously_subscribed_private_streams(self) -> None: admin_user = self.example_user("iago") @@ -5012,18 +5012,18 @@ class GetSubscribersTest(ZulipTestCase): # Test admin user gets previously subscribed private stream's subscribers. sub_data = gather_subscriptions_helper(admin_user) unsubscribed_streams = sub_data.unsubscribed - self.assertEqual(len(unsubscribed_streams), 1) - self.assertEqual(len(unsubscribed_streams[0]["subscribers"]), 1) + self.assert_length(unsubscribed_streams, 1) + self.assert_length(unsubscribed_streams[0]["subscribers"], 1) # Test non admin users cannot get previously subscribed private stream's subscribers. sub_data = gather_subscriptions_helper(non_admin_user) unsubscribed_streams = sub_data.unsubscribed - self.assertEqual(len(unsubscribed_streams), 1) + self.assert_length(unsubscribed_streams, 1) self.assertEqual(unsubscribed_streams[0]["subscribers"], []) sub_data = gather_subscriptions_helper(guest_user) unsubscribed_streams = sub_data.unsubscribed - self.assertEqual(len(unsubscribed_streams), 1) + self.assert_length(unsubscribed_streams, 1) self.assertEqual(unsubscribed_streams[0]["subscribers"], []) def test_gather_subscriptions_mit(self) -> None: @@ -5324,4 +5324,4 @@ class NoRecipientIDsTest(ZulipTestCase): # since there will not be any recipients, without crashing. # # This covers a rare corner case. - self.assertEqual(len(subs), 0) + self.assert_length(subs, 0) diff --git a/zerver/tests/test_transfer.py b/zerver/tests/test_transfer.py index af20d0e7fa..cbd2bd9c31 100644 --- a/zerver/tests/test_transfer.py +++ b/zerver/tests/test_transfer.py @@ -46,7 +46,7 @@ class TransferUploadsToS3Test(ZulipTestCase): original_image_key = bucket.Object(path_id + ".original") medium_image_key = bucket.Object(path_id + "-medium.png") - self.assertEqual(len(list(bucket.objects.all())), 3) + self.assert_length(list(bucket.objects.all()), 3) 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: @@ -68,7 +68,7 @@ class TransferUploadsToS3Test(ZulipTestCase): attachments = Attachment.objects.all().order_by("id") - self.assertEqual(len(list(bucket.objects.all())), 2) + self.assert_length(list(bucket.objects.all()), 2) self.assertEqual(bucket.Object(attachments[0].path_id).get()["Body"].read(), b"zulip1!") self.assertEqual(bucket.Object(attachments[1].path_id).get()["Body"].read(), b"zulip2!") @@ -93,7 +93,7 @@ class TransferUploadsToS3Test(ZulipTestCase): with self.assertLogs(level="INFO"): transfer_emoji_to_s3(1) - self.assertEqual(len(list(bucket.objects.all())), 2) + self.assert_length(list(bucket.objects.all()), 2) original_key = bucket.Object(emoji_path + ".original") resized_key = bucket.Object(emoji_path) diff --git a/zerver/tests/test_typing.py b/zerver/tests/test_typing.py index 45ab835f80..4c17a65c54 100644 --- a/zerver/tests/test_typing.py +++ b/zerver/tests/test_typing.py @@ -153,8 +153,8 @@ class TypingHappyPathTestPMs(ZulipTestCase): result = self.api_post(sender, "/api/v1/typing", params) self.assert_json_success(result) - self.assertEqual(len(events), 1) - self.assertEqual(len(queries), 4) + self.assert_length(events, 1) + self.assert_length(queries, 4) event = events[0]["event"] event_recipient_emails = {user["email"] for user in event["recipients"]} @@ -189,8 +189,8 @@ class TypingHappyPathTestPMs(ZulipTestCase): with tornado_redirected_to_list(events): result = self.api_post(sender, "/api/v1/typing", params) self.assert_json_success(result) - self.assertEqual(len(events), 1) - self.assertEqual(len(queries), 5) + self.assert_length(events, 1) + self.assert_length(queries, 5) # We should not be adding new Huddles just because # a user started typing in the compose box. Let's @@ -229,7 +229,7 @@ class TypingHappyPathTestPMs(ZulipTestCase): }, ) self.assert_json_success(result) - self.assertEqual(len(events), 1) + self.assert_length(events, 1) event = events[0]["event"] event_recipient_emails = {user["email"] for user in event["recipients"]} @@ -264,7 +264,7 @@ class TypingHappyPathTestPMs(ZulipTestCase): result = self.api_post(sender, "/api/v1/typing", params) self.assert_json_success(result) - self.assertEqual(len(events), 1) + self.assert_length(events, 1) event = events[0]["event"] event_recipient_emails = {user["email"] for user in event["recipients"]} @@ -297,7 +297,7 @@ class TypingHappyPathTestPMs(ZulipTestCase): result = self.api_post(user, "/api/v1/typing", params) self.assert_json_success(result) - self.assertEqual(len(events), 1) + self.assert_length(events, 1) event = events[0]["event"] event_recipient_emails = {user["email"] for user in event["recipients"]} @@ -331,7 +331,7 @@ class TypingHappyPathTestPMs(ZulipTestCase): result = self.api_post(sender, "/api/v1/typing", params) self.assert_json_success(result) - self.assertEqual(len(events), 1) + self.assert_length(events, 1) event = events[0]["event"] event_recipient_emails = {user["email"] for user in event["recipients"]} @@ -370,8 +370,8 @@ class TypingHappyPathTestStreams(ZulipTestCase): with tornado_redirected_to_list(events): result = self.api_post(sender, "/api/v1/typing", params) self.assert_json_success(result) - self.assertEqual(len(events), 1) - self.assertEqual(len(queries), 5) + self.assert_length(events, 1) + self.assert_length(queries, 5) event = events[0]["event"] event_user_ids = set(events[0]["users"]) @@ -406,8 +406,8 @@ class TypingHappyPathTestStreams(ZulipTestCase): with tornado_redirected_to_list(events): result = self.api_post(sender, "/api/v1/typing", params) self.assert_json_success(result) - self.assertEqual(len(events), 1) - self.assertEqual(len(queries), 5) + self.assert_length(events, 1) + self.assert_length(queries, 5) event = events[0]["event"] event_user_ids = set(events[0]["users"]) diff --git a/zerver/tests/test_upload.py b/zerver/tests/test_upload.py index e16e8a6c79..0718268a06 100644 --- a/zerver/tests/test_upload.py +++ b/zerver/tests/test_upload.py @@ -637,7 +637,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase): data = b"".join(response.streaming_content) self.assertEqual(b"zulip!", data) self.logout() - self.assertEqual(len(queries), 5) + self.assert_length(queries, 5) # Subscribed user who received the message should be able to view file self.login_user(cordelia) @@ -647,7 +647,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase): data = b"".join(response.streaming_content) self.assertEqual(b"zulip!", data) self.logout() - self.assertEqual(len(queries), 6) + self.assert_length(queries, 6) def assert_cannot_access_file(user: UserProfile) -> None: response = self.api_get(user, uri) @@ -702,7 +702,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase): data = b"".join(response.streaming_content) self.assertEqual(b"zulip!", data) self.logout() - self.assertEqual(len(queries), 5) + self.assert_length(queries, 5) # Originally subscribed user should be able to view file self.login_user(polonius) @@ -712,7 +712,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase): data = b"".join(response.streaming_content) self.assertEqual(b"zulip!", data) self.logout() - self.assertEqual(len(queries), 6) + self.assert_length(queries, 6) # Subscribed user who did not receive the message should also be able to view file self.login_user(late_subscribed_user) @@ -723,7 +723,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase): self.assertEqual(b"zulip!", data) self.logout() # It takes a few extra queries to verify access because of shared history. - self.assertEqual(len(queries), 9) + self.assert_length(queries, 9) def assert_cannot_access_file(user: UserProfile) -> None: self.login_user(user) @@ -731,7 +731,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase): response = self.client_get(uri) self.assertEqual(response.status_code, 403) # It takes a few extra queries to verify lack of access with shared history. - self.assertEqual(len(queries), 8) + self.assert_length(queries, 8) self.assert_in_response("You are not authorized to view this file.", response) self.logout() @@ -774,7 +774,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase): response = self.client_get(uri) self.assertEqual(response.status_code, 403) self.assert_in_response("You are not authorized to view this file.", response) - self.assertEqual(len(queries), 8) + self.assert_length(queries, 8) self.subscribe(user, "test-subscribe 1") self.subscribe(user, "test-subscribe 2") @@ -785,11 +785,11 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase): data = b"".join(response.streaming_content) self.assertEqual(b"zulip!", data) # If we were accidentally one query per message, this would be 20+ - self.assertEqual(len(queries), 9) + self.assert_length(queries, 9) with queries_captured() as queries: self.assertTrue(validate_attachment_request(user, fp_path_id)) - self.assertEqual(len(queries), 6) + self.assert_length(queries, 6) self.logout() @@ -1631,7 +1631,7 @@ class LocalStorageTest(UploadSerializeMixin, ZulipTestCase): self.assertTrue(os.path.isfile(file_path)) uploaded_file = Attachment.objects.get(owner=user_profile, path_id=path_id) - self.assertEqual(len(b"zulip!"), uploaded_file.size) + self.assert_length(b"zulip!", uploaded_file.size) def test_delete_message_image_local(self) -> None: self.login("hamlet") @@ -1753,7 +1753,7 @@ class S3Test(ZulipTestCase): self.assertEqual(b"zulip!", content) uploaded_file = Attachment.objects.get(owner=user_profile, path_id=path_id) - self.assertEqual(len(b"zulip!"), uploaded_file.size) + self.assert_length(b"zulip!", uploaded_file.size) self.subscribe(self.example_user("hamlet"), "Denmark") body = "First message ...[zulip.txt](http://localhost:9991" + uri + ")" @@ -1769,7 +1769,7 @@ class S3Test(ZulipTestCase): path_id = re.sub("/user_uploads/", "", uri) self.assertEqual(b"zulip!", bucket.Object(path_id).get()["Body"].read()) uploaded_file = Attachment.objects.get(owner=user_profile, path_id=path_id) - self.assertEqual(len(b"zulip!"), uploaded_file.size) + self.assert_length(b"zulip!", uploaded_file.size) @use_s3_backend def test_message_image_delete_s3(self) -> None: @@ -2127,8 +2127,8 @@ class UploadSpaceTests(UploadSerializeMixin, ZulipTestCase): upload_message_file("dummy.txt", len(data), "text/plain", data, self.user_profile) # notify_attachment_update function calls currently_used_upload_space_bytes which # updates the cache. - self.assertEqual(len(data), cache_get(get_realm_used_upload_space_cache_key(self.realm))[0]) - self.assertEqual(len(data), self.realm.currently_used_upload_space_bytes()) + self.assert_length(data, cache_get(get_realm_used_upload_space_cache_key(self.realm))[0]) + self.assert_length(data, self.realm.currently_used_upload_space_bytes()) data2 = b"more-data!" upload_message_file("dummy2.txt", len(data2), "text/plain", data2, self.user_profile) @@ -2147,7 +2147,7 @@ class UploadSpaceTests(UploadSerializeMixin, ZulipTestCase): attachment.delete() self.assertEqual(None, cache_get(get_realm_used_upload_space_cache_key(self.realm))) - self.assertEqual(len(data2), self.realm.currently_used_upload_space_bytes()) + self.assert_length(data2, self.realm.currently_used_upload_space_bytes()) class ExifRotateTests(ZulipTestCase): diff --git a/zerver/tests/test_user_groups.py b/zerver/tests/test_user_groups.py index 6024e0ff8f..16dff42e9e 100644 --- a/zerver/tests/test_user_groups.py +++ b/zerver/tests/test_user_groups.py @@ -26,10 +26,10 @@ class UserGroupTestCase(ZulipTestCase): def test_user_groups_in_realm(self) -> None: realm = get_realm("zulip") - self.assertEqual(len(user_groups_in_realm(realm)), 1) + self.assert_length(user_groups_in_realm(realm), 1) self.create_user_group_for_test("support") user_groups = user_groups_in_realm(realm) - self.assertEqual(len(user_groups), 2) + self.assert_length(user_groups, 2) names = {ug.name for ug in user_groups} self.assertEqual(names, {"hamletcharacters", "support"}) @@ -41,7 +41,7 @@ class UserGroupTestCase(ZulipTestCase): empty_user_group = create_user_group("newgroup", [], realm) user_groups = user_groups_in_realm_serialized(realm) - self.assertEqual(len(user_groups), 2) + self.assert_length(user_groups, 2) self.assertEqual(user_groups[0]["id"], user_group.id) self.assertEqual(user_groups[0]["name"], "hamletcharacters") self.assertEqual(user_groups[0]["description"], "Characters of Hamlet") @@ -56,7 +56,7 @@ class UserGroupTestCase(ZulipTestCase): othello = self.example_user("othello") self.create_user_group_for_test("support") user_groups = get_user_groups(othello) - self.assertEqual(len(user_groups), 1) + self.assert_length(user_groups, 1) self.assertEqual(user_groups[0].name, "support") def test_check_add_user_to_user_group(self) -> None: @@ -310,14 +310,14 @@ class UserGroupAPITestCase(ZulipTestCase): self.assert_json_success(result) self.assertEqual(UserGroupMembership.objects.count(), 4) members = get_memberships_of_users(user_group, [hamlet, othello]) - self.assertEqual(len(members), 2) + self.assert_length(members, 2) # Test adding a member already there. result = self.client_post(f"/json/user_groups/{user_group.id}/members", info=params) self.assert_json_error(result, f"User {othello.id} is already a member of this group") self.assertEqual(UserGroupMembership.objects.count(), 4) members = get_memberships_of_users(user_group, [hamlet, othello]) - self.assertEqual(len(members), 2) + self.assert_length(members, 2) self.logout() # Test when user not a member of user group tries to add members to it @@ -342,7 +342,7 @@ class UserGroupAPITestCase(ZulipTestCase): self.assert_json_success(result) self.assertEqual(UserGroupMembership.objects.count(), 5) members = get_memberships_of_users(user_group, [hamlet, othello, aaron]) - self.assertEqual(len(members), 3) + self.assert_length(members, 3) # For normal testing we again log in with hamlet self.logout() @@ -353,7 +353,7 @@ class UserGroupAPITestCase(ZulipTestCase): self.assert_json_success(result) self.assertEqual(UserGroupMembership.objects.count(), 4) members = get_memberships_of_users(user_group, [hamlet, othello, aaron]) - self.assertEqual(len(members), 2) + self.assert_length(members, 2) # Test remove a member that's already removed params = {"delete": orjson.dumps([othello.id]).decode()} @@ -361,7 +361,7 @@ class UserGroupAPITestCase(ZulipTestCase): self.assert_json_error(result, f"There is no member '{othello.id}' in this user group") self.assertEqual(UserGroupMembership.objects.count(), 4) members = get_memberships_of_users(user_group, [hamlet, othello, aaron]) - self.assertEqual(len(members), 2) + self.assert_length(members, 2) # Test when nothing is provided result = self.client_post(f"/json/user_groups/{user_group.id}/members", info={}) @@ -386,7 +386,7 @@ class UserGroupAPITestCase(ZulipTestCase): self.assert_json_success(result) self.assertEqual(UserGroupMembership.objects.count(), 3) members = get_memberships_of_users(user_group, [hamlet, othello, aaron]) - self.assertEqual(len(members), 1) + self.assert_length(members, 1) def test_mentions(self) -> None: cordelia = self.example_user("cordelia") diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py index 9973824aaa..41d9995473 100644 --- a/zerver/tests/test_users.py +++ b/zerver/tests/test_users.py @@ -1173,7 +1173,7 @@ class UserProfileTest(ZulipTestCase): # users; this work is happening before the user account is # created, so any changes will be reflected in the "add" event # introducing the user to clients. - self.assertEqual(len(events), 0) + self.assert_length(events, 0) # We verify that cordelia and iago match, but hamlet has the defaults. self.assertEqual(iago.full_name, "Cordelia, Lear's daughter") @@ -1438,7 +1438,7 @@ class ActivateTest(ZulipTestCase): deliver_scheduled_emails(email) from django.core.mail import outbox - self.assertEqual(len(outbox), 1) + self.assert_length(outbox, 1) for message in outbox: self.assertEqual( set(message.to), @@ -1467,7 +1467,7 @@ class ActivateTest(ZulipTestCase): deliver_scheduled_emails(email) from django.core.mail import outbox - self.assertEqual(len(outbox), 0) + self.assert_length(outbox, 0) self.assertEqual(ScheduledEmail.objects.count(), 1) self.assertEqual( info_log.output,