Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
direct_messages: Always use DM groups if they exist.
Alex Vandiverb071d91ce0f0
diff --git a/analytics/tests/test_counts.py b/analytics/tests/test_counts.pyindex deb3032bac7..b47c19f5e13 100644--- a/analytics/tests/test_counts.py+++ b/analytics/tests/test_counts.py@@ -567,16 +567,18 @@ class TestCountStats(AnalyticsTestCase):bot = self.create_user(is_bot=True)human1 = self.create_user()human2 = self.create_user()- recipient_human1 = Recipient.objects.get(type_id=human1.id, type=Recipient.PERSONAL)+ recipient_bot_and_human1 = self.get_dm_group_recipient(bot, human1)+ recipient_human1_and_2 = self.get_dm_group_recipient(human1, human2)+ recipient_human1 = self.get_dm_group_recipient(human1)recipient_stream = self.create_stream_with_recipient()[1]recipient_direct_message_group = self.create_direct_message_group_with_recipient()[1]- self.create_message(bot, recipient_human1)+ self.create_message(bot, recipient_bot_and_human1)self.create_message(bot, recipient_stream)self.create_message(bot, recipient_direct_message_group)self.create_message(human1, recipient_human1)- self.create_message(human2, recipient_human1)+ self.create_message(human2, recipient_human1_and_2)do_fill_count_stat_at_hour(stat, self.TIME_ZERO)@@ -608,20 +610,23 @@ class TestCountStats(AnalyticsTestCase):bot = self.create_user(is_bot=True)human1 = self.create_user()human2 = self.create_user()- recipient_human1 = Recipient.objects.get(type_id=human1.id, type=Recipient.PERSONAL)+ recipient_bot_and_human1 = self.get_dm_group_recipient(bot, human1)+ recipient_human1_and_2 = self.get_dm_group_recipient(human1, human2)+ recipient_human1 = self.get_dm_group_recipient(human1)+ recipient_hourly_user_and_human1 = self.get_dm_group_recipient(self.hourly_user, human1)recipient_stream = self.create_stream_with_recipient()[1]recipient_direct_message_group = self.create_direct_message_group_with_recipient()[1]# To be included- self.create_message(bot, recipient_human1)+ self.create_message(bot, recipient_bot_and_human1)self.create_message(bot, recipient_stream)self.create_message(bot, recipient_direct_message_group)self.create_message(human1, recipient_human1)- self.create_message(human2, recipient_human1)+ self.create_message(human2, recipient_human1_and_2)# To be excluded- self.create_message(self.hourly_user, recipient_human1)+ self.create_message(self.hourly_user, recipient_hourly_user_and_human1)self.create_message(self.hourly_user, recipient_stream)self.create_message(self.hourly_user, recipient_direct_message_group)@@ -674,11 +679,10 @@ class TestCountStats(AnalyticsTestCase):self.create_message(user2, recipient_direct_message_group2)# direct messages- recipient_user1 = Recipient.objects.get(type_id=user1.id, type=Recipient.PERSONAL)- recipient_user2 = Recipient.objects.get(type_id=user2.id, type=Recipient.PERSONAL)- recipient_user3 = Recipient.objects.get(type_id=user3.id, type=Recipient.PERSONAL)- self.create_message(user1, recipient_user2)- self.create_message(user2, recipient_user1)+ recipient_user1_and_2 = self.get_dm_group_recipient(user1, user2)+ recipient_user3 = self.get_dm_group_recipient(user3)+ self.create_message(user1, recipient_user1_and_2)+ self.create_message(user2, recipient_user1_and_2)self.create_message(user3, recipient_user3)do_fill_count_stat_at_hour(stat, self.TIME_ZERO)@@ -782,7 +786,8 @@ class TestCountStats(AnalyticsTestCase):self.current_property = stat.propertyuser = self.create_user()- user_recipient = Recipient.objects.get(type_id=user.id, type=Recipient.PERSONAL)+ user_recipient = self.get_dm_group_recipient(user)+ hourly_user_and_user_recipient = self.get_dm_group_recipient(self.hourly_user, user)private_stream_recipient = self.create_stream_with_recipient(invite_only=True)[1]stream_recipient = self.create_stream_with_recipient()[1]direct_message_group_recipient = self.create_direct_message_group_with_recipient()[1]@@ -796,7 +801,7 @@ class TestCountStats(AnalyticsTestCase):do_fill_count_stat_at_hour(stat, self.TIME_ZERO, self.default_realm)# To be excluded- self.create_message(self.hourly_user, user_recipient)+ self.create_message(self.hourly_user, hourly_user_and_user_recipient)self.create_message(self.hourly_user, private_stream_recipient)self.create_message(self.hourly_user, stream_recipient)self.create_message(self.hourly_user, direct_message_group_recipient)@@ -830,7 +835,7 @@ class TestCountStats(AnalyticsTestCase):self.current_property = stat.propertyuser = self.create_user(id=1000)- user_recipient = Recipient.objects.get(type_id=user.id, type=Recipient.PERSONAL)+ user_recipient = self.get_dm_group_recipient(user)stream_recipient = self.create_stream_with_recipient(id=1000)[1]direct_message_group_recipient = self.create_direct_message_group_with_recipient(id=1000)[1]@@ -858,14 +863,15 @@ class TestCountStats(AnalyticsTestCase):user1 = self.create_user(is_bot=True)user2 = self.create_user()- recipient_user2 = Recipient.objects.get(type_id=user2.id, type=Recipient.PERSONAL)+ recipient_user1_and_2 = self.get_dm_group_recipient(user1, user2)+ recipient_user2 = self.get_dm_group_recipient(user2)recipient_stream = self.create_stream_with_recipient()[1]recipient_direct_message_group = self.create_direct_message_group_with_recipient()[1]client2 = Client.objects.create(name="client2")- self.create_message(user1, recipient_user2, sending_client=client2)+ self.create_message(user1, recipient_user1_and_2, sending_client=client2)self.create_message(user1, recipient_stream)self.create_message(user1, recipient_direct_message_group)self.create_message(user2, recipient_user2, sending_client=client2)@@ -905,19 +911,26 @@ class TestCountStats(AnalyticsTestCase):user1 = self.create_user(is_bot=True)user2 = self.create_user()- recipient_user2 = Recipient.objects.get(type_id=user2.id, type=Recipient.PERSONAL)++ recipient_user1_and_2 = self.get_dm_group_recipient(user1, user2)+ recipient_user2 = self.get_dm_group_recipient(user2)+ recipient_hourly_user_and_user2 = self.get_dm_group_recipient(self.hourly_user, user2)client2 = Client.objects.create(name="client2")# TO be included- self.create_message(user1, recipient_user2, sending_client=client2)+ self.create_message(user1, recipient_user1_and_2, sending_client=client2)self.create_message(user2, recipient_user2, sending_client=client2)self.create_message(user2, recipient_user2)# To be excluded- self.create_message(self.hourly_user, recipient_user2, sending_client=client2)- self.create_message(self.hourly_user, recipient_user2, sending_client=client2)- self.create_message(self.hourly_user, recipient_user2)+ self.create_message(+ self.hourly_user, recipient_hourly_user_and_user2, sending_client=client2+ )+ self.create_message(+ self.hourly_user, recipient_hourly_user_and_user2, sending_client=client2+ )+ self.create_message(self.hourly_user, recipient_hourly_user_and_user2)do_fill_count_stat_at_hour(stat, self.TIME_ZERO, self.default_realm)@@ -942,7 +955,8 @@ class TestCountStats(AnalyticsTestCase):bot = self.create_user(is_bot=True)human1 = self.create_user()human2 = self.create_user()- recipient_human1 = Recipient.objects.get(type_id=human1.id, type=Recipient.PERSONAL)+ recipient_human1_and_2 = self.get_dm_group_recipient(human1, human2)+ recipient_bot_and_human1 = self.get_dm_group_recipient(bot, human1)stream1, recipient_stream1 = self.create_stream_with_recipient()stream2, recipient_stream2 = self.create_stream_with_recipient()@@ -955,8 +969,8 @@ class TestCountStats(AnalyticsTestCase):self.create_message(bot, recipient_stream2)# To be excluded- self.create_message(human2, recipient_human1)- self.create_message(bot, recipient_human1)+ self.create_message(human2, recipient_human1_and_2)+ self.create_message(bot, recipient_bot_and_human1)recipient_direct_message_group = self.create_direct_message_group_with_recipient()[1]self.create_message(human1, recipient_direct_message_group)@@ -1441,7 +1455,7 @@ class TestLoggingCountStats(AnalyticsTestCase):message = Message(sender=hamlet,- recipient=self.example_user("othello").recipient,+ recipient=self.get_dm_group_recipient(hamlet, self.example_user("othello")),realm_id=hamlet.realm_id,content="This is test content",rendered_content="This is test content",diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.pyindex 9b1ed117461..33c57e33339 100644--- a/corporate/tests/test_stripe.py+++ b/corporate/tests/test_stripe.py@@ -7457,22 +7457,24 @@ class TestSupportBillingHelpers(StripeTestCase):sender = get_system_bot(settings.NOTIFICATION_BOT, realm.id)# Organization owners get the notification bot message- desdemona_recipient = self.example_user("desdemona").recipient+ bot_and_desdemona_recipient = self.get_dm_group_recipient(+ sender, self.example_user("desdemona")+ )message_to_owner = Message.objects.filter(- realm_id=realm.id, sender=sender.id, recipient=desdemona_recipient+ realm_id=realm.id, sender=sender.id, recipient=bot_and_desdemona_recipient).first()assert message_to_owner is not Noneself.assertEqual(message_to_owner.content, expected_message)- self.assertEqual(message_to_owner.recipient.type, Recipient.PERSONAL)+ self.assertEqual(message_to_owner.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)# Hamlet is in `can_manage_billing_group` so should get the notification bot message- hamlet_recipient = self.example_user("hamlet").recipient+ bot_and_hamlet_recipient = self.get_dm_group_recipient(sender, self.example_user("hamlet"))message_to_hamlet = Message.objects.filter(- realm_id=realm.id, sender=sender.id, recipient=hamlet_recipient+ realm_id=realm.id, sender=sender.id, recipient=bot_and_hamlet_recipient).last()assert message_to_hamlet is not Noneself.assertEqual(message_to_hamlet.content, expected_message)- self.assertEqual(message_to_hamlet.recipient.type, Recipient.PERSONAL)+ self.assertEqual(message_to_hamlet.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)def test_update_realm_sponsorship_status(self) -> None:lear = get_realm("lear")diff --git a/zerver/lib/message.py b/zerver/lib/message.pyindex e823a7c09d7..0976eb11b3b 100644--- a/zerver/lib/message.py+++ b/zerver/lib/message.py@@ -16,7 +16,7 @@ from psycopg2.sql import SQLfrom analytics.lib.counts import COUNT_STATSfrom analytics.models import RealmCountfrom zerver.lib.cache import generic_bulk_cached_fetch, to_dict_cache_key_id-from zerver.lib.display_recipient import get_display_recipient, get_display_recipient_by_id+from zerver.lib.display_recipient import get_display_recipient_by_idfrom zerver.lib.exceptions import JsonableError, MissingAuthenticationErrorfrom zerver.lib.markdown import MessageRenderingResultfrom zerver.lib.mention import MentionData, sender_can_mention_group, silent_mention_syntax_for_user@@ -1824,9 +1824,10 @@ def is_1_to_1_message(message: Message) -> bool:def is_message_to_self(message: Message) -> bool:+ """Using the same approach as is_1_to_1_message"""if message.recipient.type == Recipient.DIRECT_MESSAGE_GROUP:- group_members = get_display_recipient(message.recipient)- return len(group_members) == 1 and group_members[0]["id"] == message.sender.id+ direct_message_group = DirectMessageGroup.objects.get(id=message.recipient.type_id)+ return direct_message_group.group_size == 1if message.recipient.type == Recipient.PERSONAL:return message.recipient == message.sender.recipientdiff --git a/zerver/lib/message_report.py b/zerver/lib/message_report.pyindex 3baf56c8a25..7bda86c08e7 100644--- a/zerver/lib/message_report.py+++ b/zerver/lib/message_report.py@@ -5,7 +5,12 @@ from zerver.actions.message_send import internal_send_stream_messagefrom zerver.lib.display_recipient import get_display_recipientfrom zerver.lib.markdown.fenced_code import get_unused_fencefrom zerver.lib.mention import silent_mention_syntax_for_user-from zerver.lib.message import get_user_mentions_for_display, is_1_to_1_message, truncate_content+from zerver.lib.message import (+ get_user_mentions_for_display,+ is_1_to_1_message,+ is_message_to_self,+ truncate_content,+)from zerver.lib.timestamp import datetime_to_global_timefrom zerver.lib.topic_link_util import get_message_link_syntaxfrom zerver.lib.url_encoding import pm_message_url@@ -52,7 +57,7 @@ def send_message_report(else:# Clearly mention the direct message recipient if someone is# reporting their own message in a 1-on-1 direct message.- if reported_message.recipient.type_id != reporting_user.id:+ if not is_message_to_self(reported_message):recipient_user = next(silent_mention_syntax_for_user(user)for user in get_display_recipient(reported_message.recipient)diff --git a/zerver/lib/narrow.py b/zerver/lib/narrow.pyindex 765349a9393..bc2df32811c 100644--- a/zerver/lib/narrow.py+++ b/zerver/lib/narrow.py@@ -557,6 +557,8 @@ class NarrowBuilder:if user_profiles == []:return query.where(maybe_negate(false()))+ all_user_ids = {u.id for u in user_profiles} | {self.user_profile.id}+recipient = recipient_for_user_profiles(user_profiles=user_profiles,forwarded_mirror_message=False,@@ -568,11 +570,19 @@ class NarrowBuilder:except (JsonableError, ValidationError):raise BadNarrowOperatorError("unknown user in " + str(operand))except DirectMessageGroup.DoesNotExist:- # Group DM where direct message group doesn't exist- return query.where(maybe_negate(false()))-- # Group direct message- if recipient.type == Recipient.DIRECT_MESSAGE_GROUP:+ # Group DM where direct message group doesn't exist.+ # For 3+ person groups, no messages can exist.+ if len(all_user_ids) > 2:+ return query.where(maybe_negate(false()))+ # For 1:1 DMs, fall through to query PERSONAL recipients only+ recipient = None++ # Group direct message (3+ participants)+ if (+ recipient is not None+ and recipient.type == Recipient.DIRECT_MESSAGE_GROUP+ and len(all_user_ids) > 2+ ):cond = column("recipient_id", Integer) == recipient.idreturn query.where(maybe_negate(cond))@@ -593,6 +603,14 @@ class NarrowBuilder:# complex query to get messages between these two users# with either of them as the sender.self_recipient_id = self.user_profile.recipient_id+ other_recipient_id = other_participant.recipient_id++ # Include messages from both PERSONAL and DM group recipients.+ # This handles the migration period where messages may exist+ # with either recipient type.+ group_recipient: Iterable[ClauseElement] = tuple()+ if recipient and recipient.type == Recipient.DIRECT_MESSAGE_GROUP:+ group_recipient = (column("recipient_id", Integer) == recipient.id,)cond = and_(column("flags", Integer).op("&")(UserMessage.flags.is_private.mask) != 0,column("realm_id", Integer) == self.realm.id,@@ -603,18 +621,28 @@ class NarrowBuilder:),and_(column("sender_id", Integer) == self.user_profile.id,- column("recipient_id", Integer) == recipient.id,+ column("recipient_id", Integer) == other_recipient_id,),+ *group_recipient,),)+return query.where(maybe_negate(cond))# Direct message with self+ # Build condition for PERSONAL recipients (bidirectional)+ # Include messages from both PERSONAL and DM group recipients+ personal_cond = column("recipient_id", Integer) == self.user_profile.recipient_id+ if recipient is not None and recipient.type == Recipient.DIRECT_MESSAGE_GROUP:+ personal_cond = or_(+ personal_cond,+ column("recipient_id", Integer) == recipient.id,+ )cond = and_(column("flags", Integer).op("&")(UserMessage.flags.is_private.mask) != 0,column("realm_id", Integer) == self.realm.id,column("sender_id", Integer) == self.user_profile.id,- column("recipient_id", Integer) == recipient.id,+ personal_cond,)return query.where(maybe_negate(cond))diff --git a/zerver/lib/recipient_users.py b/zerver/lib/recipient_users.pyindex 5b5ec70cd1f..c46943212f4 100644--- a/zerver/lib/recipient_users.py+++ b/zerver/lib/recipient_users.py@@ -40,31 +40,27 @@ def get_recipient_from_user_profiles(recipient_profiles_map[sender.id] = senderuser_ids = list(recipient_profiles_map)- # Important note: We are transitioning 1:1 DMs and self DMs to use- # DirectMessageGroup as the Recipient type. If PREFER_DIRECT_MESSAGE_GROUP- # is enabled and a DirectMessageGroup exists for the collection of user IDs,- # it is guaranteed to contain that entire DM conversation. If none- # exists, we use the legacy personal recipient (which may or may- # not exist). Once the migration completes, this code path should- # just call get_or_create_direct_message_group.if len(recipient_profiles_map) <= 2:- if settings.PREFER_DIRECT_MESSAGE_GROUP:- direct_message_group = get_direct_message_group(user_ids)- if direct_message_group:- # Use the existing direct message group as the preferred recipient.- return Recipient(- id=direct_message_group.recipient_id,- type=Recipient.DIRECT_MESSAGE_GROUP,- type_id=direct_message_group.id,- )-- # Making sure we have personal recipients for all users,- # otherwise, fall back to the direct message group.+ # Try the DirectMessageGroup for the 1-to-1 and+ # message-to-self case. If it exists, we will ratchet forward+ # and use it (for both sending and receiving).+ direct_message_group = get_direct_message_group(user_ids)+ if direct_message_group:+ # Use the existing direct message group as the preferred recipient.+ return Recipient(+ id=direct_message_group.recipient_id,+ type=Recipient.DIRECT_MESSAGE_GROUP,+ type_id=direct_message_group.id,+ )++ # We don't have a DirectMessageGroup; if we have personal+ # recipients and we're in PREFER_DIRECT_MESSAGE_GROUP=False,+ # then we use them.has_personal_recipient = all(user_profile.recipient_id is not Nonefor user_profile in recipient_profiles_map.values())- if has_personal_recipient:+ if has_personal_recipient and not settings.PREFER_DIRECT_MESSAGE_GROUP:del recipient_profiles_map[sender.id]if len(recipient_profiles_map) == 1:[recipient_user_profile] = recipient_profiles_map.values()@@ -75,6 +71,11 @@ def get_recipient_from_user_profiles(type=Recipient.PERSONAL,type_id=recipient_user_profile.id,)++ # We're a <= 2 person DM, didn't have a DirectMessageGroup, and+ # PREFER_DIRECT_MESSAGE_GROUP=True; fall through to the below,+ # where we create if asked for, or raise an error.+if create:direct_message_group = get_or_create_direct_message_group(user_ids)else:diff --git a/zerver/lib/users.py b/zerver/lib/users.pyindex 297f1bac861..2e54e19d254 100644--- a/zerver/lib/users.py+++ b/zerver/lib/users.py@@ -28,6 +28,7 @@ from zerver.lib.user_groups import user_has_permission_for_group_settingfrom zerver.models import (CustomProfileField,CustomProfileFieldValue,+ DirectMessageGroup,Message,Realm,Recipient,@@ -993,6 +994,36 @@ def get_users_involved_in_dms_with_target_users(sender_ids = {row["sender_id"] for row in message_rows}direct_message_participants_dict[recipient_user_id] |= sender_ids+ # Find DM partners via 1:1 DM groups with message history.+ # Push the message-existence check into the subscription query+ # as a subquery, so we only fetch DMGs that actually have messages.+ target_dmg_subs = Subscription.objects.filter(+ user_profile_id__in=target_user_ids,+ recipient__type=Recipient.DIRECT_MESSAGE_GROUP,+ recipient__type_id__in=DirectMessageGroup.objects.filter(+ group_size__lte=2,+ ),+ recipient_id__in=Message.objects.filter(realm=realm).values("recipient_id"),+ ).values_list("user_profile_id", "recipient_id")++ dmg_to_targets: dict[int, set[int]] = defaultdict(set)+ dmg_recipient_ids: set[int] = set()+ for target_id, recipient_id in target_dmg_subs:+ dmg_to_targets[recipient_id].add(target_id)+ dmg_recipient_ids.add(recipient_id)++ if dmg_recipient_ids:+ partner_query = Subscription.objects.filter(+ recipient_id__in=dmg_recipient_ids,+ )+ if not include_deactivated_users:+ partner_query = partner_query.filter(is_user_active=True)++ for recipient_id, user_id in partner_query.values_list("recipient_id", "user_profile_id"):+ for target_id in dmg_to_targets.get(recipient_id, set()):+ if user_id != target_id:+ direct_message_participants_dict[target_id].add(user_id)+return direct_message_participants_dictdiff --git a/zerver/models/recipients.py b/zerver/models/recipients.pyindex 1c5ef3bf32f..0c7e23529ca 100644--- a/zerver/models/recipients.py+++ b/zerver/models/recipients.py@@ -187,7 +187,7 @@ def get_direct_message_group(id_list: list[int]) -> DirectMessageGroup | None:the DirectMessageGroup object does not yet exist, it willreturn None."""-+ assert len(id_list) == len(set(id_list))try:direct_message_group_hash = get_direct_message_group_hash(id_list)return DirectMessageGroup.objects.get(diff --git a/zerver/tests/test_channel_fetch.py b/zerver/tests/test_channel_fetch.pyindex f42f7709440..e114fea014a 100644--- a/zerver/tests/test_channel_fetch.py+++ b/zerver/tests/test_channel_fetch.py@@ -643,7 +643,7 @@ class GetSubscribersTest(ZulipTestCase):# verify that the user was sent a message informing them about the subscriptionrealm = user.realmmsg = most_recent_message(user)- self.assertEqual(msg.recipient.type, msg.recipient.PERSONAL)+ self.assertEqual(msg.recipient.type, msg.recipient.DIRECT_MESSAGE_GROUP)self.assertEqual(msg.sender_id, self.notification_bot(realm).id)def non_ws(s: str) -> str:@@ -881,7 +881,7 @@ class GetSubscribersTest(ZulipTestCase):polonius.id,]- with self.assert_database_query_count(49):+ with self.assert_database_query_count(76):self.subscribe_via_post(self.user_profile,stream_names,diff --git a/zerver/tests/test_email_mirror.py b/zerver/tests/test_email_mirror.pyindex dd49d67eadf..91536a37905 100644--- a/zerver/tests/test_email_mirror.py+++ b/zerver/tests/test_email_mirror.py@@ -1274,6 +1274,7 @@ class TestStreamEmailMessagesEmptyBody(ZulipTestCase):class TestMissedMessageEmailMessages(ZulipTestCase):+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_receive_missed_personal_message_email_messages(self) -> None:# Build dummy messages for message notification email reply.# Have Hamlet send Othello a direct message. Othello willdiff --git a/zerver/tests/test_embedded_bot_system.py b/zerver/tests/test_embedded_bot_system.pyindex 17de3de861e..be85feaaf3d 100644--- a/zerver/tests/test_embedded_bot_system.py+++ b/zerver/tests/test_embedded_bot_system.py@@ -28,7 +28,8 @@ class TestEmbeddedBotMessaging(ZulipTestCase):config_data=orjson.dumps({"foo": "bar"}).decode(),)- def test_pm_to_embedded_bot(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_pm_to_embedded_bot_using_personal_recipient(self) -> None:assert self.bot_profile is not Noneself.send_personal_message(self.user_profile, self.bot_profile, content="help")last_message = self.get_last_message()diff --git a/zerver/tests/test_event_system.py b/zerver/tests/test_event_system.pyindex 76d09c3a12f..d36930a10f9 100644--- a/zerver/tests/test_event_system.py+++ b/zerver/tests/test_event_system.py@@ -382,6 +382,7 @@ class GetEventsTest(ZulipTestCase):email = user_profile.emailrecipient_user_profile = self.example_user("othello")recipient_email = recipient_user_profile.email+ recipient = self.get_dm_group_recipient(user_profile, recipient_user_profile)self.login_user(user_profile)result = self.tornado_call(@@ -457,7 +458,7 @@ class GetEventsTest(ZulipTestCase):self.assertEqual(events[0]["local_message_id"], local_id)self.assertEqual(events[0]["message"]["display_recipient"][0]["is_mirror_dummy"], False)self.assertEqual(events[0]["message"]["display_recipient"][1]["is_mirror_dummy"], False)- self.assertEqual(events[0]["message"]["recipient_id"], recipient_user_profile.recipient_id)+ self.assertEqual(events[0]["message"]["recipient_id"], recipient.id)last_event_id = events[0]["id"]local_id = "10.02"@@ -490,7 +491,7 @@ class GetEventsTest(ZulipTestCase):self.assertEqual(events[0]["type"], "message")self.assertEqual(events[0]["message"]["sender_email"], email)self.assertEqual(events[0]["local_message_id"], local_id)- self.assertEqual(events[0]["message"]["recipient_id"], recipient_user_profile.recipient_id)+ self.assertEqual(events[0]["message"]["recipient_id"], recipient.id)# Test that the received message in the receiver's event queue# exists and does not contain a local id@@ -511,11 +512,11 @@ class GetEventsTest(ZulipTestCase):self.assertEqual(recipient_events[0]["message"]["sender_email"], email)self.assertTrue("local_message_id" not in recipient_events[0])# Incoming DMs show the recipient_id that outgoing DMs would.- self.assertEqual(recipient_events[0]["message"]["recipient_id"], user_profile.recipient_id)+ self.assertEqual(events[0]["message"]["recipient_id"], recipient.id)self.assertEqual(recipient_events[1]["type"], "message")self.assertEqual(recipient_events[1]["message"]["sender_email"], email)self.assertTrue("local_message_id" not in recipient_events[1])- self.assertEqual(recipient_events[1]["message"]["recipient_id"], user_profile.recipient_id)+ self.assertEqual(recipient_events[1]["message"]["recipient_id"], recipient.id)@override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_get_events_narrow(self) -> None:diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.pyindex 39ce1d463f3..236f943234a 100644--- a/zerver/tests/test_events.py+++ b/zerver/tests/test_events.py@@ -306,7 +306,6 @@ from zerver.models.bots import get_bot_servicesfrom zerver.models.clients import get_clientfrom zerver.models.groups import SystemGroupsfrom zerver.models.realm_audit_logs import AuditLogEventType-from zerver.models.recipients import get_or_create_direct_message_groupfrom zerver.models.streams import StreamTopicsPolicyEnum, get_streamfrom zerver.models.users import get_user_by_delivery_emailfrom zerver.openapi.openapi import validate_against_openapi_schema@@ -652,7 +651,8 @@ class NormalActionsTest(BaseAction):skip_capture_on_commit_callbacks=True,)- def test_pm_send_message_events(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_pm_send_message_events_using_personal_recipients(self) -> None:with self.verify_action() as events:self.send_personal_message(self.example_user("cordelia"),@@ -708,9 +708,6 @@ class NormalActionsTest(BaseAction):hamlet = self.example_user("hamlet")cordelia = self.example_user("cordelia")- # Create a direct message group with hamlet and cordelia- get_or_create_direct_message_group(id_list=[hamlet.id, cordelia.id])-with self.verify_action():self.send_group_direct_message(from_user=hamlet,diff --git a/zerver/tests/test_example.py b/zerver/tests/test_example.pyindex 216fbe900c5..e6ab5d90940 100644--- a/zerver/tests/test_example.py+++ b/zerver/tests/test_example.py@@ -366,6 +366,27 @@ class TestQueryCounts(ZulipTestCase):hamlet = self.example_user("hamlet")cordelia = self.example_user("cordelia")+ # when direct message group doesn't exist and should be created as part of the flow+ with self.assert_database_query_count(25):+ self.send_personal_message(+ from_user=hamlet,+ to_user=cordelia,+ content="hello there!",+ )++ # when direct message group exists+ with self.assert_database_query_count(18):+ self.send_personal_message(+ from_user=hamlet,+ to_user=cordelia,+ content="hello there!",+ )++ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_capturing_queries_using_personal_recipient(self) -> None:+ hamlet = self.example_user("hamlet")+ cordelia = self.example_user("cordelia")+with self.assert_database_query_count(17):self.send_personal_message(from_user=hamlet,diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.pyindex a266755cad0..eaece944738 100644--- a/zerver/tests/test_home.py+++ b/zerver/tests/test_home.py@@ -615,12 +615,12 @@ class HomeTest(ZulipTestCase):# Verify number of queries for Realm admin isn't much higher than for normal users.self.login("iago")with (- self.assert_database_query_count(58),+ self.assert_database_query_count(59),patch("zerver.lib.cache.cache_set") as cache_mock,):result = self._get_home_page()self.check_rendered_logged_in_app(result)- self.assert_length(cache_mock.call_args_list, 8)+ self.assert_length(cache_mock.call_args_list, 9)def test_num_queries_with_streams(self) -> None:main_user = self.example_user("hamlet")diff --git a/zerver/tests/test_import_export.py b/zerver/tests/test_import_export.pyindex e8e33e6913a..9fa07a1648e 100644--- a/zerver/tests/test_import_export.py+++ b/zerver/tests/test_import_export.py@@ -114,10 +114,7 @@ from zerver.models.presence import PresenceSequencefrom zerver.models.realm_audit_logs import AuditLogEventTypefrom zerver.models.realm_emoji import get_all_custom_emoji_for_realmfrom zerver.models.realms import get_realm-from zerver.models.recipients import (- get_direct_message_group_hash,- get_or_create_direct_message_group,-)+from zerver.models.recipients import get_direct_message_group, get_direct_message_group_hashfrom zerver.models.streams import get_active_streams, get_streamfrom zerver.models.users import ExternalAuthID, get_system_bot, get_user_by_delivery_email@@ -955,15 +952,19 @@ class RealmImportExportTest(ExportFile):pm_a_msg_id = self.send_personal_message(self.example_user("AARON"), self.example_user("othello"))+ dm_group_pm_a = DirectMessageGroup.objects.last()pm_b_msg_id = self.send_personal_message(self.example_user("cordelia"), self.example_user("iago"))+ dm_group_pm_b = DirectMessageGroup.objects.last()pm_c_msg_id = self.send_personal_message(self.example_user("hamlet"), self.example_user("othello"))+ dm_group_pm_c = DirectMessageGroup.objects.last()pm_d_msg_id = self.send_personal_message(self.example_user("iago"), self.example_user("hamlet"))+ dm_group_pm_d = DirectMessageGroup.objects.last()# Create some non-message private data for users. We will use SavedSnippet objects as they're simple# to create and are private data that should not be exported for non-consenting users. There are many@@ -1157,25 +1158,19 @@ class RealmImportExportTest(ExportFile):realm_id=realm.id, recipient__in=private_stream_recipients).values_list("id", flat=True)- pm_recipients = Recipient.objects.filter(- type_id__in=consented_user_ids, type=Recipient.PERSONAL- )- pm_query = Q(recipient__in=pm_recipients) | Q(sender__in=consented_user_ids)- exported_pm_ids = (- Message.objects.filter(pm_query, realm=realm.id)- .values_list("id", flat=True)- .values_list("id", flat=True)- )-assert (direct_message_group_a is not Noneand direct_message_group_b is not Noneand direct_message_group_c is not None+ and dm_group_pm_a is not None+ and dm_group_pm_b is not None+ and dm_group_pm_c is not None+ and dm_group_pm_d is not None)# Third direct message group is not exported since none of# the members gave consentdirect_message_group_recipients = Recipient.objects.filter(- type_id__in=[direct_message_group_a.id, direct_message_group_b.id],+ type_id__in=[direct_message_group_a.id, direct_message_group_b.id, dm_group_pm_b.id],type=Recipient.DIRECT_MESSAGE_GROUP,)pm_query = Q(recipient__in=direct_message_group_recipients) | Q(@@ -1191,7 +1186,6 @@ class RealmImportExportTest(ExportFile):*public_stream_message_ids,*private_stream_message_ids,stream_b_second_message_id,- *exported_pm_ids,*exported_dm_group_message_ids,}self.assertEqual(self.get_set(data["zerver_message"], "id"), exported_msg_ids)@@ -1217,9 +1211,23 @@ class RealmImportExportTest(ExportFile):exported_direct_message_group_ids = self.get_set(realm_data["zerver_huddle"], "id")self.assertNotIn(direct_message_group_c.id, exported_direct_message_group_ids)+ self.assertNotIn(dm_group_pm_a.id, exported_direct_message_group_ids)++ # Because Iago schedules a message to himself in populate_db,+ # his DirectMessageGroup for DMs with himself already exists.+ iago_dm_group = get_direct_message_group(id_list=[self.example_user("iago").id])+ assert iago_dm_group is not None+self.assertEqual(exported_direct_message_group_ids,- {direct_message_group_a.id, direct_message_group_b.id},+ {+ iago_dm_group.id,+ direct_message_group_a.id,+ direct_message_group_b.id,+ dm_group_pm_b.id,+ dm_group_pm_c.id,+ dm_group_pm_d.id,+ },)# We also want to verify Subscriptions to the DirectMessageGroups were exported correctly.@@ -3379,7 +3387,6 @@ class SingleUserExportTest(ExportFile):)bye_hamlet_message_id = self.send_personal_message(cordelia, hamlet, "bye hamlet")-hi_myself_message_id = self.send_personal_message(cordelia, cordelia, "hi myself")bye_stream_message_id = self.send_stream_message(cordelia, "Denmark", "bye stream")@@ -3413,17 +3420,13 @@ class SingleUserExportTest(ExportFile):],)- @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)- def test_1_to_1_message_data_using_direct_message_group(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_message_data_using_personal_recipient(self) -> None:hamlet = self.example_user("hamlet")cordelia = self.example_user("cordelia")othello = self.example_user("othello")bot = self.create_test_bot("test-bot", hamlet)- get_or_create_direct_message_group([hamlet.id, cordelia.id])- get_or_create_direct_message_group([hamlet.id, bot.id])- get_or_create_direct_message_group([hamlet.id])-hi_hamlet_message_id = self.send_personal_message(othello, hamlet, "hi hamlet")hi_cordelia_message_id = self.send_personal_message(hamlet, cordelia, "hi cordelia")bye_hamlet_message_id = self.send_personal_message(cordelia, hamlet, "bye hamlet")diff --git a/zerver/tests/test_invite.py b/zerver/tests/test_invite.pyindex ce914d03430..c4af97a04f7 100644--- a/zerver/tests/test_invite.py+++ b/zerver/tests/test_invite.py@@ -1386,10 +1386,13 @@ [email protected]""",self.assert_json_success(self.invite(invitee, ["Denmark"], False))self.assertTrue(find_key_by_email(invitee))self.submit_reg_form_for_user(invitee, "password")+ notification_bot = self.notification_bot(realm)+ hamlet_and_notification_bot_recipient = self.get_dm_group_recipient(+ notification_bot, user_profile+ )- assert user_profile.recipient_id is not Noneinvite_acceptance_notification_message = Message.objects.filter(- recipient_id=user_profile.recipient_id, realm=realm+ recipient=hamlet_and_notification_bot_recipient, realm=realm).last()self.assertIsNone(@@ -1405,7 +1408,7 @@ [email protected]""",new_invitee_profile = self.nonreg_user("bob")new_invite_acceptance_notification_message = Message.objects.filter(- recipient_id=user_profile.recipient_id, realm=realm+ recipient=hamlet_and_notification_bot_recipient, realm=realm).last()assert new_invite_acceptance_notification_message is not Nonediff --git a/zerver/tests/test_mattermost_importer.py b/zerver/tests/test_mattermost_importer.pyindex 300b0625845..3bd722dd009 100644--- a/zerver/tests/test_mattermost_importer.py+++ b/zerver/tests/test_mattermost_importer.py@@ -1467,10 +1467,10 @@ class MatterMostImporter(MattermostImportTestBase):group_direct_messages = messages.filter(recipient__type=Recipient.DIRECT_MESSAGE_GROUP).order_by("date_sent")- self.assert_length(group_direct_messages, 7)+ self.assert_length(group_direct_messages, 11)direct_message_group_recipients = group_direct_messages.values_list("recipient", flat=True)- self.assert_length(set(direct_message_group_recipients), 3)+ self.assert_length(set(direct_message_group_recipients), 7)self.assertEqual(group_direct_messages[0].sender.email, "[email protected]")self.assertRegex(@@ -1490,7 +1490,7 @@ class MatterMostImporter(MattermostImportTestBase):personal_messages = messages.filter(recipient__type=Recipient.PERSONAL).order_by("date_sent")- self.assert_length(personal_messages, 4)+ self.assert_length(personal_messages, 0)def test_do_convert_data_with_masking(self) -> None:mattermost_data_dir = self.fixture_file_name("", "mattermost_fixtures")diff --git a/zerver/tests/test_message_delete.py b/zerver/tests/test_message_delete.pyindex f5cadd63c68..2c19647cc5c 100644--- a/zerver/tests/test_message_delete.py+++ b/zerver/tests/test_message_delete.py@@ -276,17 +276,37 @@ class DeleteMessageTest(ZulipTestCase):with self.capture_send_event_calls(expected_num_events=8) as events:do_delete_messages(realm, messages, acting_user=None)- expected_events: list[dict[str, Any]] = [- {- "type": "delete_message",- "message_ids": [dm_id_1],- "message_type": "private",- },- {- "type": "delete_message",- "message_ids": [dm_id_2],- "message_type": "private",- },+ actual_events = [event["event"] for event in events]+ self.assert_length(actual_events, 8)++ # Messages are grouped by (recipient_id, topic) via a database+ # GROUP BY with no explicit ORDER BY, so the order of event+ # groups is non-deterministic. With PREFER_DIRECT_MESSAGE_GROUP,+ # DM recipient IDs change from PERSONAL to DIRECT_MESSAGE_GROUP+ # type, which shifts where DM events appear relative to channel+ # events. We verify events by category rather than by position.++ # Verify DM delete events (order-independent).+ dm_delete_events = [+ e+ for e in actual_events+ if e["type"] == "delete_message" and e["message_type"] == "private"+ ]+ self.assert_length(dm_delete_events, 2)+ dm_message_id_sets = [set(e["message_ids"]) for e in dm_delete_events]+ self.assertIn({dm_id_1}, dm_message_id_sets)+ self.assertIn({dm_id_2}, dm_message_id_sets)++ # Verify channel events maintain their expected relative order.+ # Within a channel, topic groups are processed deterministically+ # (same recipient_id), and each group produces a paired+ # (first_message_id update, delete_message) sequence.+ channel_events = [+ e+ for e in actual_events+ if not (e["type"] == "delete_message" and e["message_type"] == "private")+ ]+ expected_channel_events: list[dict[str, Any]] = [{"type": "stream","op": "update",@@ -334,11 +354,8 @@ class DeleteMessageTest(ZulipTestCase):},]- actual_events = [event["event"] for event in events]-- self.assert_length(actual_events, len(expected_events))-- for actual, expected in zip(actual_events, expected_events, strict=True):+ self.assert_length(channel_events, len(expected_channel_events))+ for actual, expected in zip(channel_events, expected_channel_events, strict=True):for key, value in expected.items():if key == "message_ids":self.assertEqual(set(actual[key]), set(value))diff --git a/zerver/tests/test_message_dict.py b/zerver/tests/test_message_dict.pyindex 9564d3fe689..002d4203a92 100644--- a/zerver/tests/test_message_dict.py+++ b/zerver/tests/test_message_dict.py@@ -147,7 +147,9 @@ class MessageDictTest(ZulipTestCase):sender = self.example_user("othello")receiver = self.example_user("hamlet")realm = get_realm("zulip")- pm_recipient = Recipient.objects.get(type_id=receiver.id, type=Recipient.PERSONAL)+ pm_recipient = get_or_create_direct_message_group(+ id_list=[sender.id, receiver.id]+ ).recipientstream_name = "Çiğdem"stream = self.make_stream(stream_name)stream_recipient = Recipient.objects.get(type_id=stream.id, type=Recipient.STREAM)@@ -179,7 +181,7 @@ class MessageDictTest(ZulipTestCase):num_ids = len(ids)self.assertTrue(num_ids >= 600)- with self.assert_database_query_count(7):+ with self.assert_database_query_count(8):objs = MessageDict.ids_to_dict(ids)MessageDict.post_process_dicts(objs,@@ -195,11 +197,13 @@ class MessageDictTest(ZulipTestCase):def test_applying_markdown(self) -> None:sender = self.example_user("othello")receiver = self.example_user("hamlet")- recipient = Recipient.objects.get(type_id=receiver.id, type=Recipient.PERSONAL)+ direct_message_group = get_or_create_direct_message_group(+ id_list=[sender.id, receiver.id],+ )sending_client = make_client(name="test suite")message = Message(sender=sender,- recipient=recipient,+ recipient=direct_message_group.recipient,realm=receiver.realm,content="hello **world**",date_sent=timezone_now(),@@ -225,11 +229,13 @@ class MessageDictTest(ZulipTestCase):convert_mock.return_value = Nonesender = self.example_user("othello")receiver = self.example_user("hamlet")- recipient = Recipient.objects.get(type_id=receiver.id, type=Recipient.PERSONAL)+ direct_message_group = get_or_create_direct_message_group(+ id_list=[sender.id, receiver.id],+ )sending_client = make_client(name="test suite")message = Message(sender=sender,- recipient=recipient,+ recipient=direct_message_group.recipient,realm=receiver.realm,content="hello **world**",date_sent=timezone_now(),@@ -290,7 +296,7 @@ class MessageDictTest(ZulipTestCase):def test_reaction(self) -> None:sender = self.example_user("othello")receiver = self.example_user("hamlet")- recipient = Recipient.objects.get(type_id=receiver.id, type=Recipient.PERSONAL)+ recipient = get_or_create_direct_message_group(id_list=[sender.id, receiver.id]).recipientsending_client = make_client(name="test suite")message = Message(sender=sender,@@ -497,10 +503,8 @@ class MessageHydrationTest(ZulipTestCase):cordelia = self.example_user("cordelia")message_id = self.send_personal_message(hamlet, cordelia, "test")- cordelia_recipient = cordelia.recipient# Cause the display_recipient to get cached:- assert cordelia_recipient is not None- get_display_recipient(cordelia_recipient)+ get_display_recipient(self.get_dm_group_recipient(hamlet, cordelia))# Change cordelia's email:cordelia_new_email = "[email protected]"@@ -762,7 +766,9 @@ class SewMessageAndReactionTest(ZulipTestCase):sender = self.example_user("othello")receiver = self.example_user("hamlet")realm = get_realm("zulip")- pm_recipient = Recipient.objects.get(type_id=receiver.id, type=Recipient.PERSONAL)+ pm_recipient = get_or_create_direct_message_group(+ id_list=[sender.id, receiver.id]+ ).recipientstream_name = "Çiğdem"stream = self.make_stream(stream_name)stream_recipient = Recipient.objects.get(type_id=stream.id, type=Recipient.STREAM)diff --git a/zerver/tests/test_message_edit.py b/zerver/tests/test_message_edit.pyindex 6eff0f5ad55..8ed12515fab 100644--- a/zerver/tests/test_message_edit.py+++ b/zerver/tests/test_message_edit.py@@ -233,7 +233,10 @@ class EditMessageTest(ZulipTestCase):response_dict = self.assert_json_success(result)self.assertEqual(response_dict["raw_content"], "Outgoing direct message")self.assertEqual(response_dict["message"]["id"], msg_id)- self.assertEqual(response_dict["message"]["recipient_id"], cordelia.recipient_id)+ self.assertEqual(+ response_dict["message"]["recipient_id"],+ self.get_dm_group_recipient(hamlet, cordelia).id,+ )self.assertEqual(response_dict["message"]["flags"], ["read"])self.assertEqual(response_dict["message"][TOPIC_NAME], "")@@ -245,7 +248,10 @@ class EditMessageTest(ZulipTestCase):self.assertEqual(response_dict["raw_content"], "Incoming direct message")self.assertEqual(response_dict["message"]["id"], msg_id)# Incoming DMs show the recipient_id that outgoing DMs would.- self.assertEqual(response_dict["message"]["recipient_id"], cordelia.recipient_id)+ self.assertEqual(+ response_dict["message"]["recipient_id"],+ self.get_dm_group_recipient(hamlet, cordelia).id,+ )self.assertEqual(response_dict["message"]["flags"], [])self.assertEqual(response_dict["message"][TOPIC_NAME], "")diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.pyindex d5026ded92c..6fe0e21ced4 100644--- a/zerver/tests/test_message_fetch.py+++ b/zerver/tests/test_message_fetch.py@@ -358,13 +358,34 @@ class NarrowBuilderTest(ZulipTestCase):term = NarrowParameter(operator="sender", operand="[email protected]")self.assertRaises(BadNarrowOperatorError, self._build_query, term)- def test_add_term_using_dm_operator_and_not_the_same_user_as_operand(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_add_term_using_dm_operator_and_not_the_same_user_as_operand_with_no_direct_message_group(+ self,+ ) -> None:+ # During migration (PREFER_DIRECT_MESSAGE_GROUP=True), even without a DM group,+ # we query PERSONAL recipients since messages might exist with themterm = NarrowParameter(operator="dm", operand=self.othello_email)self._do_add_term_test(term,"WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s)",)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_add_term_using_dm_operator_and_not_the_same_user_as_operand(self) -> None:+ # Create a direct message group between users+ get_or_create_direct_message_group(+ [+ self.example_user("hamlet").id,+ self.example_user("othello").id,+ ]+ )+ term = NarrowParameter(operator="dm", operand=self.othello_email)+ # During migration, query includes both PERSONAL and DM group recipients+ self._do_add_term_test(+ term,+ "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s OR recipient_id = %(recipient_id_3)s)",+ )+def test_negated_is_dm_with_dm_operator(self) -> None:expected_error_message = ("Invalid narrow operator: No message can be both a channel message and direct message"@@ -408,25 +429,66 @@ class NarrowBuilderTest(ZulipTestCase):channel_term = NarrowParameter(operator="channels", operand="public", negated=True)self._build_query(channel_term)- def test_add_term_using_dm_operator_not_the_same_user_as_operand_and_negated(+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_add_term_using_dm_operator_not_the_same_user_as_operand_no_direct_message_group_and_negated(self,) -> None: # NEGATED+ # During migration, query PERSONAL recipients (negated)term = NarrowParameter(operator="dm", operand=self.othello_email, negated=True)self._do_add_term_test(term,"WHERE NOT ((flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s))",)- def test_add_term_using_dm_operator_the_same_user_as_operand(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_add_term_using_dm_operator_not_the_same_user_as_operand_and_negated(+ self,+ ) -> None: # NEGATED+ # Create a direct message group between users+ get_or_create_direct_message_group(+ [+ self.example_user("hamlet").id,+ self.example_user("othello").id,+ ]+ )+ term = NarrowParameter(operator="dm", operand=self.othello_email, negated=True)+ # During migration, query includes both PERSONAL and DM group recipients (negated)+ self._do_add_term_test(+ term,+ "WHERE NOT ((flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s OR recipient_id = %(recipient_id_3)s))",+ )++ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_add_term_using_dm_operator_the_same_user_as_operand_no_direct_message_group(+ self,+ ) -> None:+ # During migration, query PERSONAL recipients for self-DMterm = NarrowParameter(operator="dm", operand=self.hamlet_email)self._do_add_term_test(term,"WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s",)- def test_add_term_using_dm_operator_the_same_user_as_operand_and_negated(+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_add_term_using_dm_operator_the_same_user_as_operand(self) -> None:+ # Create a direct message group with the user+ get_or_create_direct_message_group(+ [+ self.example_user("hamlet").id,+ ]+ )+ term = NarrowParameter(operator="dm", operand=self.hamlet_email)+ # During migration, query includes both PERSONAL and DM group recipients for self-DM+ self._do_add_term_test(+ term,+ "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND sender_id = %(sender_id_1)s AND (recipient_id = %(recipient_id_1)s OR recipient_id = %(recipient_id_2)s)",+ )++ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_add_term_using_dm_operator_the_same_user_as_operand_no_direct_message_group_and_negated(self,) -> None: # NEGATED+ # During migration, query PERSONAL recipients for self-DM (negated)term = NarrowParameter(operator="dm", operand=self.hamlet_email, negated=True)self._do_add_term_test(term,@@ -434,41 +496,54 @@ class NarrowBuilderTest(ZulipTestCase):)@override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)- def test_add_term_using_dm_operator_the_same_user_as_operand_when_direct_message_group_exists(+ def test_add_term_using_dm_operator_the_same_user_as_operand_and_negated(self,- ) -> None:- hamlet = self.example_user("hamlet")-- # Make the direct message group for self messages- direct_message_group = get_or_create_direct_message_group(id_list=[hamlet.id])-- term = NarrowParameter(operator="dm", operand=hamlet.email)- params = {"recipient_id_1": direct_message_group.recipient_id}- self._do_add_term_test(term, "WHERE recipient_id = %(recipient_id_1)s", params)+ ) -> None: # NEGATED+ # Create a direct message group with the user+ get_or_create_direct_message_group(+ [+ self.example_user("hamlet").id,+ ]+ )+ term = NarrowParameter(operator="dm", operand=self.hamlet_email, negated=True)+ # During migration, query includes both PERSONAL and DM group recipients (negated)+ self._do_add_term_test(+ term,+ "WHERE NOT ((flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND sender_id = %(sender_id_1)s AND (recipient_id = %(recipient_id_1)s OR recipient_id = %(recipient_id_2)s))",+ )- def test_add_term_using_dm_operator_and_self_and_user_as_operand(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_add_term_using_dm_operator_and_self_and_user_as_operand_no_direct_message_group(+ self,+ ) -> None:myself_and_other = (f"{self.example_user('hamlet').email},{self.example_user('othello').email}")term = NarrowParameter(operator="dm", operand=myself_and_other)+ # Even with PREFER=True, if no DM group exists, query old personal messagesself._do_add_term_test(term,"WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s)",)@override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)- def test_add_term_using_dm_operator_and_self_and_user_as_operand_when_direct_message_group_exists(- self,- ) -> None:- hamlet = self.example_user("hamlet")- othello = self.example_user("othello")-- # Make the direct message group for 1:1 messages between hamlet and othello- direct_message_group = get_or_create_direct_message_group(id_list=[hamlet.id, othello.id])-- term = NarrowParameter(operator="dm", operand=f"{hamlet.email},{othello.email}")- params = {"recipient_id_1": direct_message_group.recipient_id}- self._do_add_term_test(term, "WHERE recipient_id = %(recipient_id_1)s", params)+ def test_add_term_using_dm_operator_and_self_and_user_as_operand(self) -> None:+ # Make the direct message group first+ get_or_create_direct_message_group(+ [+ self.example_user("hamlet").id,+ self.example_user("othello").id,+ ]+ )+ myself_and_other = (+ f"{self.example_user('hamlet').email},{self.example_user('othello').email}"+ )+ term = NarrowParameter(operator="dm", operand=myself_and_other)+ # During migration, query includes both PERSONAL and DM group recipients+ self._do_add_term_test(+ term,+ "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s OR recipient_id = %(recipient_id_3)s)",+ )def test_add_term_using_dm_operator_more_than_one_user_as_operand_no_direct_message_group(self,@@ -478,6 +553,7 @@ class NarrowBuilderTest(ZulipTestCase):term = NarrowParameter(operator="dm", operand=two_others)self._do_add_term_test(term, "WHERE false")+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_add_term_using_dm_operator_more_than_one_user_as_operand(self) -> None:# Make the direct message group firstget_or_create_direct_message_group(@@ -489,20 +565,47 @@ class NarrowBuilderTest(ZulipTestCase):)two_others = f"{self.example_user('cordelia').email},{self.example_user('othello').email}"term = NarrowParameter(operator="dm", operand=two_others)- self._do_add_term_test(term, "WHERE recipient_id = %(recipient_id_1)s")+ # 3+ person group DM uses simple recipient_id match+ self._do_add_term_test(+ term,+ "WHERE recipient_id = %(recipient_id_1)s",+ )- def test_add_term_using_dm_operator_self_and_user_as_operand_and_negated(+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_add_term_using_dm_operator_self_and_user_as_operand_no_group_direct_message_and_negated(self,) -> None: # NEGATEDmyself_and_other = (f"{self.example_user('hamlet').email},{self.example_user('othello').email}")term = NarrowParameter(operator="dm", operand=myself_and_other, negated=True)+ # Even with PREFER=True, if no DM group exists, query old personal messages (negated)self._do_add_term_test(term,"WHERE NOT ((flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s))",)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_add_term_using_dm_operator_self_and_user_as_operand_and_negated(+ self,+ ) -> None: # NEGATED+ # Make the direct message group first+ get_or_create_direct_message_group(+ [+ self.example_user("hamlet").id,+ self.example_user("othello").id,+ ]+ )+ myself_and_other = (+ f"{self.example_user('hamlet').email},{self.example_user('othello').email}"+ )+ term = NarrowParameter(operator="dm", operand=myself_and_other, negated=True)+ # During migration, query includes both PERSONAL and DM group recipients (negated)+ self._do_add_term_test(+ term,+ "WHERE NOT ((flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s OR recipient_id = %(recipient_id_3)s))",+ )+def test_add_term_using_dm_operator_more_than_one_user_as_operand_no_direct_message_group_and_negated(self,) -> None: # NEGATED@@ -511,6 +614,7 @@ class NarrowBuilderTest(ZulipTestCase):term = NarrowParameter(operator="dm", operand=two_others, negated=True)self._do_add_term_test(term, "WHERE true")+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_add_term_using_dm_operator_more_than_one_user_as_operand_and_negated(self,) -> None: # NEGATED@@ -524,7 +628,11 @@ class NarrowBuilderTest(ZulipTestCase):)two_others = f"{self.example_user('cordelia').email},{self.example_user('othello').email}"term = NarrowParameter(operator="dm", operand=two_others, negated=True)- self._do_add_term_test(term, "WHERE recipient_id != %(recipient_id_1)s")+ # 3+ person group DM uses simple recipient_id match (negated)+ self._do_add_term_test(+ term,+ "WHERE recipient_id != %(recipient_id_1)s",+ )def test_add_term_using_dm_operator_with_comma_noise(self) -> None:term = NarrowParameter(operator="dm", operand=" ,,, ,,, ,")@@ -543,11 +651,16 @@ class NarrowBuilderTest(ZulipTestCase):self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) != %(param_1)s")def test_add_term_using_dm_including_operator_with_different_user_email(self) -> None:+ # Dropping the personal recipient for Othello+ othello = self.example_user("othello")+ othello.recipient = None+ othello.save()+# Test without any such group direct messages existingterm = NarrowParameter(operator="dm-including", operand=self.othello_email)self._do_add_term_test(term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s OR recipient_id IN (__[POSTCOMPILE_recipient_id_3]))",+ "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND recipient_id IN (__[POSTCOMPILE_recipient_id_1])",)# Test with at least one such group direct messages existing@@ -558,28 +671,29 @@ class NarrowBuilderTest(ZulipTestCase):term = NarrowParameter(operator="dm-including", operand=self.othello_email)self._do_add_term_test(term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s OR recipient_id IN (__[POSTCOMPILE_recipient_id_3]))",+ "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND recipient_id IN (__[POSTCOMPILE_recipient_id_1])",)def test_add_term_using_dm_including_operator_with_different_user_email_and_negated(self,) -> None: # NEGATED- term = NarrowParameter(operator="dm-including", operand=self.othello_email, negated=True)- self._do_add_term_test(- term,- "WHERE NOT ((flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s OR recipient_id IN (__[POSTCOMPILE_recipient_id_3])))",- )-- def test_add_term_using_dm_including_operator_without_personal_recipient(self) -> None:# Dropping the personal recipient for Othelloothello = self.example_user("othello")othello.recipient = Noneothello.save()+ term = NarrowParameter(operator="dm-including", operand=self.othello_email, negated=True)+ self._do_add_term_test(+ term,+ "WHERE NOT ((flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND recipient_id IN (__[POSTCOMPILE_recipient_id_1]))",+ )++ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_add_term_using_dm_including_operator_with_personal_recipient(self) -> None:term = NarrowParameter(operator="dm-including", operand=self.othello_email)self._do_add_term_test(term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND recipient_id IN (__[POSTCOMPILE_recipient_id_1])",+ "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s OR recipient_id IN (__[POSTCOMPILE_recipient_id_3]))",)def test_add_term_using_id_operator_integer(self) -> None:@@ -726,16 +840,43 @@ class NarrowBuilderTest(ZulipTestCase):self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) = %(param_1)s")# Test that "pm-with" (legacy alias for "dm") works.- def test_add_term_using_pm_with_operator(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_add_term_using_pm_with_operator_no_direct_message_group(self) -> None:+ # During migration, query PERSONAL recipients for self-DM even without DM groupterm = NarrowParameter(operator="pm-with", operand=self.hamlet_email)self._do_add_term_test(term,"WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s",)+ # Test that "pm-with" (legacy alias for "dm") works.+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_add_term_using_pm_with_operator(self) -> None:+ # Create a direct message group with the user+ get_or_create_direct_message_group([self.user_profile.id])+ term = NarrowParameter(operator="pm-with", operand=self.hamlet_email)+ # During migration, query includes both PERSONAL and DM group recipients for self-DM+ self._do_add_term_test(+ term,+ "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND sender_id = %(sender_id_1)s AND (recipient_id = %(recipient_id_1)s OR recipient_id = %(recipient_id_2)s)",+ )+# Test that the underscore version of "pm-with" works.+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_add_term_using_underscore_version_of_pm_with_operator(self) -> None:+ # Create a direct message group with the user+ get_or_create_direct_message_group([self.user_profile.id])term = NarrowParameter(operator="pm_with", operand=self.hamlet_email)+ # During migration, query includes both PERSONAL and DM group recipients for self-DM+ self._do_add_term_test(+ term,+ "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND sender_id = %(sender_id_1)s AND (recipient_id = %(recipient_id_1)s OR recipient_id = %(recipient_id_2)s)",+ )++ # Test that "pm-with" (legacy alias for "dm") works.+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_add_term_using_pm_with_operator_and_with_personal_recipient(self) -> None:+ term = NarrowParameter(operator="pm-with", operand=self.hamlet_email)self._do_add_term_test(term,"WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s",@@ -2034,8 +2175,6 @@ class GetOldMessagesTest(ZulipTestCase):scotland_channel = get_stream("Scotland", hamlet_user.realm)assert scotland_channel.recipient_id is not None- assert hamlet_user.recipient_id is not None- assert othello_user.recipient_id is not Nonequery_ids["realm_id"] = hamlet_user.realm_idquery_ids["scotland_recipient"] = scotland_channel.recipient_idquery_ids["hamlet_id"] = hamlet_user.id@@ -2043,8 +2182,14 @@ class GetOldMessagesTest(ZulipTestCase):tuple(sorted(get_recursive_membership_groups(hamlet_user).values_list("id", flat=True))))query_ids["othello_id"] = othello_user.id- query_ids["hamlet_recipient"] = hamlet_user.recipient_id- query_ids["othello_recipient"] = othello_user.recipient_id+ query_ids["hamlet_recipient"] = self.get_dm_group_recipient(hamlet_user).id+ query_ids["hamlet_and_othello_recipient"] = self.get_dm_group_recipient(+ hamlet_user, othello_user+ ).id+ assert hamlet_user.recipient is not None+ query_ids["hamlet_personal_recipient"] = hamlet_user.recipient.id+ assert othello_user.recipient is not None+ query_ids["othello_personal_recipient"] = othello_user.recipient.idrecipients = (get_public_streams_queryset(hamlet_user.realm).values_list("recipient_id", flat=True)@@ -2496,6 +2641,7 @@ class GetOldMessagesTest(ZulipTestCase):message = result["messages"][0]self.assertIn("gravatar.com", message["avatar_url"])+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_get_messages_with_narrow_dm(self) -> None:"""A request for old messages with a narrow by direct message only returns@@ -2569,6 +2715,7 @@ class GetOldMessagesTest(ZulipTestCase):result = self.get_and_check_messages(dict(narrow=orjson.dumps(narrow).decode()))self.assertNotEqual(result["messages"], [])+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_get_1_to_1_messages_with_existent_group_dm(self) -> None:me = self.example_user("hamlet")other_user = self.example_user("iago")@@ -2593,6 +2740,7 @@ class GetOldMessagesTest(ZulipTestCase):self.assertIn(message["id"], message_ids)self.assertEqual(message["recipient_id"], direct_message_group.recipient_id)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_get_messages_to_self_with_existent_group_dm(self) -> None:me = self.example_user("hamlet")@@ -2615,6 +2763,112 @@ class GetOldMessagesTest(ZulipTestCase):self.assertEqual(message["sender_id"], me.id)self.assertEqual(message["recipient_id"], direct_message_group.recipient_id)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_dm_narrow_with_mixed_personal_and_dm_group_messages(self) -> None:+ """+ Test that fetching DMs between two users shows all messages,+ regardless of whether they were sent using personal recipients+ (legacy) or DirectMessageGroup recipients (new).++ This is important for the migration from personal recipients to+ DirectMessageGroup recipients for 1:1 DMs. Users should be able to+ see their complete message history after the migration.+ """+ me = self.example_user("hamlet")+ other_user = self.example_user("iago")+ self.login_user(me)+ user_ids = [me.id, other_user.id]+ narrow = [dict(operator="dm", operand=[other_user.id], negated=False)]+ modified_params: dict[str, str | int] = {+ "narrow": orjson.dumps(narrow).decode(),+ "num_before": 100,+ "num_after": 100,+ }++ # Step 1: Send messages using personal recipients (legacy behavior)+ # With PREFER_DIRECT_MESSAGE_GROUP=False, messages use PERSONAL recipients+ with self.settings(PREFER_DIRECT_MESSAGE_GROUP=False):+ personal_message_ids = [+ self.send_personal_message(me, other_user),+ self.send_personal_message(other_user, me),+ ]++ # Verify messages use PERSONAL recipient type+ for msg_id in personal_message_ids:+ msg = Message.objects.get(id=msg_id)+ self.assertEqual(msg.recipient.type, Recipient.PERSONAL)++ # Verify personal messages are visible in the conversation+ with self.settings(PREFER_DIRECT_MESSAGE_GROUP=False):+ result = self.get_and_check_messages(modified_params)+ result_ids = [m["id"] for m in result["messages"]]+ for msg_id in personal_message_ids:+ self.assertIn(msg_id, result_ids)++ # Step 2: Enable PREFER_DIRECT_MESSAGE_GROUP and send new messages+ # This simulates what happens after the migration is enabled+ with self.settings(PREFER_DIRECT_MESSAGE_GROUP=True):+ dm_group_message_ids = [+ self.send_personal_message(me, other_user),+ self.send_personal_message(other_user, me),+ ]++ # Verify new messages use DIRECT_MESSAGE_GROUP recipient type+ direct_message_group = get_or_create_direct_message_group(user_ids)+ for msg_id in dm_group_message_ids:+ msg = Message.objects.get(id=msg_id)+ self.assertEqual(msg.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)+ self.assertEqual(msg.recipient_id, direct_message_group.recipient_id)++ # Step 3: Fetch messages with dm narrow (with PREFER_DIRECT_MESSAGE_GROUP=True)+ # This is the key test: can users see BOTH old and new messages?+ with self.settings(PREFER_DIRECT_MESSAGE_GROUP=True):+ result = self.get_and_check_messages(modified_params)+ result_ids = [m["id"] for m in result["messages"]]++ # IMPORTANT: This verifies backward compatibility during the migration.+ # All messages should be visible - both old (personal) and new (DM group)+ all_message_ids = personal_message_ids + dm_group_message_ids+ for msg_id in all_message_ids:+ self.assertIn(+ msg_id,+ result_ids,+ f"Message {msg_id} not found in dm narrow results. "+ f"This indicates a potential issue with the migration - "+ f"old messages may not be visible after enabling PREFER_DIRECT_MESSAGE_GROUP.",+ )++ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_dm_including_narrow_with_mixed_recipients(self) -> None:+ """+ Test that the dm-including: narrow shows messages sent with both+ PERSONAL and DM group recipients. This validates the left sidebar+ "All DMs" view during the migration.+ """+ me = self.example_user("hamlet")+ other_user = self.example_user("iago")+ self.login_user(me)++ # Send with PERSONAL recipients+ with self.settings(PREFER_DIRECT_MESSAGE_GROUP=False):+ personal_msg_id = self.send_personal_message(me, other_user)++ # Send with DM group recipients+ with self.settings(PREFER_DIRECT_MESSAGE_GROUP=True):+ dm_group_msg_id = self.send_personal_message(me, other_user)++ narrow = [dict(operator="dm-including", operand=other_user.id)]+ result = self.get_and_check_messages(+ dict(+ narrow=orjson.dumps(narrow).decode(),+ num_before=100,+ num_after=100,+ )+ )+ result_ids = [m["id"] for m in result["messages"]]+ self.assertIn(personal_msg_id, result_ids)+ self.assertIn(dm_group_msg_id, result_ids)+def test_get_visible_messages_with_narrow_dm(self) -> None:me = self.example_user("hamlet")self.login_user(me)@@ -2916,6 +3170,7 @@ class GetOldMessagesTest(ZulipTestCase):""")+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_get_visible_messages_using_narrow_with(self) -> None:hamlet = self.example_user("hamlet")othello = self.example_user("othello")@@ -4667,6 +4922,7 @@ class GetOldMessagesTest(ZulipTestCase):self.assertFalse(result["found_newest"])self.assertFalse(result["found_oldest"])+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_use_first_unread_anchor_with_some_unread_messages(self) -> None:user_profile = self.example_user("hamlet")@@ -4800,6 +5056,7 @@ class GetOldMessagesTest(ZulipTestCase):self.assertNotIn("AND message_id <=", sql)self.assertNotIn("AND message_id >=", sql)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_use_first_unread_anchor_with_muted_topics(self) -> None:"""Test that our logic related to `use_first_unread_anchor`@@ -5115,7 +5372,100 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.{"anchor": 100, "num_before": 10, "num_after": 10}, sql)- def test_get_messages_with_narrow_queries(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_get_messages_with_narrow_queries_using_personal_recipient(self) -> None:+ query_ids = self.get_query_ids()+ othello_email = self.example_user("othello").email+ hamlet_email = self.example_user("hamlet").email+ sql_template = """\+SELECT anon_1.message_id, anon_1.flags \n\+FROM (SELECT message_id, flags \n\+FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\+WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\+FROM zerver_stream \n\+WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\+FROM zerver_subscription \n\+WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND (sender_id = {othello_id} AND recipient_id = {hamlet_personal_recipient} OR sender_id = {hamlet_id} AND recipient_id = {othello_personal_recipient} OR recipient_id = {hamlet_and_othello_recipient}) AND message_id = 0) AS anon_1 ORDER BY message_id ASC\+"""+ sql = sql_template.format(**query_ids)+ self.common_check_get_messages_query(+ {+ "anchor": 0,+ "num_before": 0,+ "num_after": 0,+ "narrow": f'[["dm", "{othello_email}"]]',+ },+ sql,+ )++ sql_template = """\+SELECT anon_1.message_id, anon_1.flags \n\+FROM (SELECT message_id, flags \n\+FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\+WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\+FROM zerver_stream \n\+WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\+FROM zerver_subscription \n\+WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND (sender_id = {othello_id} AND recipient_id = {hamlet_personal_recipient} OR sender_id = {hamlet_id} AND recipient_id = {othello_personal_recipient} OR recipient_id = {hamlet_and_othello_recipient}) AND message_id = 0) AS anon_1 ORDER BY message_id ASC\+"""+ sql = sql_template.format(**query_ids)+ self.common_check_get_messages_query(+ {+ "anchor": 0,+ "num_before": 1,+ "num_after": 0,+ "narrow": f'[["dm", "{othello_email}"]]',+ },+ sql,+ )+ sql_template = """\+SELECT anon_1.message_id, anon_1.flags \n\+FROM (SELECT message_id, flags \n\+FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\+WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\+FROM zerver_stream \n\+WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\+FROM zerver_subscription \n\+WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND (sender_id = {othello_id} AND recipient_id = {hamlet_personal_recipient} OR sender_id = {hamlet_id} AND recipient_id = {othello_personal_recipient} OR recipient_id = {hamlet_and_othello_recipient}) ORDER BY message_id ASC \n\+ LIMIT 10) AS anon_1 ORDER BY message_id ASC\+"""+ sql = sql_template.format(**query_ids)+ self.common_check_get_messages_query(+ {+ "anchor": 0,+ "num_before": 0,+ "num_after": 9,+ "narrow": f'[["dm", "{othello_email}"]]',+ },+ sql,+ )++ # Narrow to direct messages with yourself+ sql_template = """\+SELECT anon_1.message_id, anon_1.flags \n\+FROM (SELECT message_id, flags \n\+FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\+WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\+FROM zerver_stream \n\+WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\+FROM zerver_subscription \n\+WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND sender_id = {hamlet_id} AND (recipient_id = {hamlet_personal_recipient} OR recipient_id = {hamlet_recipient}) ORDER BY message_id ASC \n\+ LIMIT 10) AS anon_1 ORDER BY message_id ASC\+"""+ sql = sql_template.format(**query_ids)+ self.common_check_get_messages_query(+ {+ "anchor": 0,+ "num_before": 0,+ "num_after": 9,+ "narrow": f'[["dm", "{hamlet_email}"]]',+ },+ sql,+ )++ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_get_messages_with_narrow_queries_using_direct_message_group(self) -> None:+ # During migration, the query includes both PERSONAL and DM group recipientsquery_ids = self.get_query_ids()hamlet_email = self.example_user("hamlet").emailothello_email = self.example_user("othello").email@@ -5128,7 +5478,7 @@ WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (FROM zerver_stream \n\WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND (sender_id = {othello_id} AND recipient_id = {hamlet_recipient} OR sender_id = {hamlet_id} AND recipient_id = {othello_recipient}) AND message_id = 0) AS anon_1 ORDER BY message_id ASC\+WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND (sender_id = {othello_id} AND recipient_id = {hamlet_personal_recipient} OR sender_id = {hamlet_id} AND recipient_id = {othello_personal_recipient} OR recipient_id = {hamlet_and_othello_recipient}) AND message_id = 0) AS anon_1 ORDER BY message_id ASC\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5149,7 +5499,7 @@ WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (FROM zerver_stream \n\WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND (sender_id = {othello_id} AND recipient_id = {hamlet_recipient} OR sender_id = {hamlet_id} AND recipient_id = {othello_recipient}) AND message_id = 0) AS anon_1 ORDER BY message_id ASC\+WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND (sender_id = {othello_id} AND recipient_id = {hamlet_personal_recipient} OR sender_id = {hamlet_id} AND recipient_id = {othello_personal_recipient} OR recipient_id = {hamlet_and_othello_recipient}) AND message_id = 0) AS anon_1 ORDER BY message_id ASC\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5170,7 +5520,7 @@ WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (FROM zerver_stream \n\WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND (sender_id = {othello_id} AND recipient_id = {hamlet_recipient} OR sender_id = {hamlet_id} AND recipient_id = {othello_recipient}) ORDER BY message_id ASC \n\+WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND (sender_id = {othello_id} AND recipient_id = {hamlet_personal_recipient} OR sender_id = {hamlet_id} AND recipient_id = {othello_personal_recipient} OR recipient_id = {hamlet_and_othello_recipient}) ORDER BY message_id ASC \n\LIMIT 10) AS anon_1 ORDER BY message_id ASC\"""sql = sql_template.format(**query_ids)@@ -5305,6 +5655,7 @@ WHERE realm_id = 2 AND recipient_id = {scotland_recipient} AND upper(subject) =)# Narrow to direct messages with yourself+ # During migration, query includes both PERSONAL and DM group recipients for self-DMsql_template = """\SELECT anon_1.message_id, anon_1.flags \n\FROM (SELECT message_id, flags \n\@@ -5313,7 +5664,7 @@ WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (FROM zerver_stream \n\WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND sender_id = {hamlet_id} AND recipient_id = {hamlet_recipient} ORDER BY message_id ASC \n\+WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND sender_id = {hamlet_id} AND (recipient_id = {hamlet_personal_recipient} OR recipient_id = {hamlet_recipient}) ORDER BY message_id ASC \n\LIMIT 10) AS anon_1 ORDER BY message_id ASC\"""sql = sql_template.format(**query_ids)@@ -5479,7 +5830,8 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.'@<span class="highlight">Othello</span>, the Moor of Venice</span>?</p>',)- def test_dm_recipient_id(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_personal_dm_recipient_id(self) -> None:hamlet = self.example_user("hamlet")othello = self.example_user("othello")self.login_user(hamlet)@@ -5582,6 +5934,29 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.)self.assertGreater(len(result["messages"]), 0)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_group_dm_recipient_id(self) -> None:+ hamlet = self.example_user("hamlet")+ othello = self.example_user("othello")+ self.login_user(hamlet)++ direct_message_group = get_or_create_direct_message_group(id_list=[hamlet.id, othello.id])+ assert direct_message_group.recipient is not None+ self.assertIsNotNone(direct_message_group.recipient.label())++ outgoing_message_id = self.send_personal_message(hamlet, othello)+ incoming_message_id = self.send_personal_message(othello, hamlet)++ result = self.get_and_check_messages(dict(anchor="newest", num_before=2))+ self.assert_length(result["messages"], 2)+ self.assertEqual(result["messages"][0]["id"], outgoing_message_id)+ self.assertEqual(result["messages"][0]["sender_id"], hamlet.id)+ self.assertEqual(result["messages"][0]["recipient_id"], direct_message_group.recipient_id)+ self.assertEqual(result["messages"][1]["id"], incoming_message_id)+ self.assertEqual(result["messages"][1]["sender_id"], othello.id)+ # Incoming DMs show the recipient_id that outgoing DMs would.+ self.assertEqual(result["messages"][1]["recipient_id"], direct_message_group.recipient_id)+class MessageHasKeywordsTest(ZulipTestCase):"""Test for keywords like has_link, has_image, has_attachment."""diff --git a/zerver/tests/test_message_flags.py b/zerver/tests/test_message_flags.pyindex 191ac15fe53..6b2fb0ff2f6 100644--- a/zerver/tests/test_message_flags.py+++ b/zerver/tests/test_message_flags.py@@ -1178,6 +1178,29 @@ class GetUnreadMsgsTest(ZulipTestCase):dict(user_ids_string=direct_message_group_string),)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_raw_unread_personal_using_personal_recipients(self) -> None:+ cordelia = self.example_user("cordelia")+ othello = self.example_user("othello")+ hamlet = self.example_user("hamlet")++ cordelia_pm_message_ids = [self.send_personal_message(cordelia, hamlet) for i in range(3)]+ othello_pm_message_ids = [self.send_personal_message(othello, hamlet) for i in range(3)]++ raw_unread_data = get_raw_unread_data(user_profile=hamlet)++ pm_dict = raw_unread_data["pm_dict"]++ self.assertEqual(+ set(pm_dict.keys()),+ set(cordelia_pm_message_ids) | set(othello_pm_message_ids),+ )++ self.assertEqual(+ pm_dict[cordelia_pm_message_ids[0]],+ dict(other_user_id=cordelia.id),+ )+def test_raw_unread_personal(self) -> None:cordelia = self.example_user("cordelia")othello = self.example_user("othello")@@ -1235,6 +1258,7 @@ class GetUnreadMsgsTest(ZulipTestCase):dict(other_user_id=othello.id),)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_raw_unread_personal_from_self(self) -> None:hamlet = self.example_user("hamlet")diff --git a/zerver/tests/test_message_notification_emails.py b/zerver/tests/test_message_notification_emails.pyindex 7c7d1d440ce..de64905252b 100644--- a/zerver/tests/test_message_notification_emails.py+++ b/zerver/tests/test_message_notification_emails.py@@ -1130,10 +1130,18 @@ class TestMessageNotificationEmails(ZulipTestCase):self._resolved_topic_missed_stream_messages_thread_friendly()@override_settings(EMAIL_GATEWAY_PATTERN="")- def test_reply_warning_in_missed_personal_messages(self) -> None:+ def test_reply_warning_in_missed_personal_messages_with_direct_message_group(self) -> None:self._reply_warning_in_missed_personal_messages()- def test_extra_context_in_missed_personal_messages(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False, EMAIL_GATEWAY_PATTERN="")+ def test_reply_warning_in_missed_personal_messages_using_personal_recipients(self) -> None:+ self._reply_warning_in_missed_personal_messages()++ def test_extra_context_in_missed_personal_messages_with_direct_message_group(self) -> None:+ self._extra_context_in_missed_personal_messages()++ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_extra_context_in_missed_personal_messages_using_personal_recipients(self) -> None:self._extra_context_in_missed_personal_messages()def test_extra_context_in_missed_group_direct_messages_two_others(self) -> None:diff --git a/zerver/tests/test_message_report.py b/zerver/tests/test_message_report.pyindex 99f1c04a12c..993ff3c3183 100644--- a/zerver/tests/test_message_report.py+++ b/zerver/tests/test_message_report.py@@ -377,8 +377,9 @@ class ReportMessageTest(ZulipTestCase):assert report is not Noneself.assertIn(expected_message_link_syntax, report.content)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)@time_machine.travel(MOCKED_DATE_SENT, tick=False)- def test_dm_report(self) -> None:+ def test_dm_report_using_personal_recipients(self) -> None:# Send a DM to be reporteddm_recipient = self.hamletreported_dm_id = self.send_personal_message(diff --git a/zerver/tests/test_message_send.py b/zerver/tests/test_message_send.pyindex 9df4fdbedbb..ce599a6547d 100644--- a/zerver/tests/test_message_send.py+++ b/zerver/tests/test_message_send.py@@ -78,7 +78,7 @@ from zerver.models import (from zerver.models.constants import MAX_TOPIC_NAME_LENGTHfrom zerver.models.groups import SystemGroupsfrom zerver.models.realms import RealmTopicsPolicyEnum, get_realm-from zerver.models.recipients import get_direct_message_group, get_or_create_direct_message_group+from zerver.models.recipients import get_or_create_direct_message_groupfrom zerver.models.streams import StreamTopicsPolicyEnum, get_streamfrom zerver.models.users import (get_system_bot,@@ -897,11 +897,15 @@ class MessagePOSTTest(ZulipTestCase):# Now verify we have the appropriate self-pm data structureself.assertEqual(recent_conversations[frozenset()], self_message_id)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_personal_message_by_id(self) -> None:"""Sending a personal message to a valid user ID is successfulfor both valid strings for `type` parameter."""+ hamlet = self.example_user("hamlet")+ othello = self.example_user("othello")+self.login("hamlet")recipient_type_name = ["direct", "private"]@@ -911,14 +915,14 @@ class MessagePOSTTest(ZulipTestCase):{"type": type,"content": "Test message",- "to": orjson.dumps([self.example_user("othello").id]).decode(),+ "to": orjson.dumps([othello.id]).decode(),},)self.assert_json_success(result)msg = self.get_last_message()self.assertEqual("Test message", msg.content)- self.assertEqual(msg.recipient_id, self.example_user("othello").recipient_id)+ self.assertEqual(msg.recipient_id, self.get_dm_group_recipient(hamlet, othello).id)def test_group_personal_message_by_id(self) -> None:"""@@ -952,6 +956,7 @@ class MessagePOSTTest(ZulipTestCase):)self.assertEqual(msg.recipient_id, direct_message_group.recipient_id)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_personal_message_copying_self(self) -> None:"""Sending a personal message to yourself plus another user is successful,@@ -970,8 +975,8 @@ class MessagePOSTTest(ZulipTestCase):)self.assert_json_success(result)msg = self.get_last_message()- # Verify that we're not actually on the "recipient list"- self.assertNotIn("Hamlet", str(msg.recipient))+ # Verify that we're actually on the "recipient list"+ self.assertEqual(msg.recipient, self.get_dm_group_recipient(hamlet, othello))def test_personal_message_to_nonexistent_user(self) -> None:"""@@ -988,6 +993,7 @@ class MessagePOSTTest(ZulipTestCase):)self.assert_json_error(result, "Invalid email 'nonexistent'")+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_personal_message_to_deactivated_user(self) -> None:"""Sending a personal message to a deactivated user returns error JSON.@@ -1017,6 +1023,7 @@ class MessagePOSTTest(ZulipTestCase):)self.assert_json_error(result, f"'{othello.email}' is no longer using Zulip.")+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_personal_message_to_inaccessible_users(self) -> None:othello = self.example_user("othello")cordelia = self.example_user("cordelia")@@ -2712,7 +2719,8 @@ class StreamMessagesTest(ZulipTestCase):class PersonalMessageSendTest(ZulipTestCase):- def test_personal_to_self(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_personal_to_self_using_personal_recipient(self) -> None:"""If you send a personal to yourself, only you see it."""@@ -2732,6 +2740,7 @@ class PersonalMessageSendTest(ZulipTestCase):recipient = Recipient.objects.get(type_id=user_profile.id, type=Recipient.PERSONAL)self.assertEqual(most_recent_message(user_profile).recipient, recipient)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_personal_to_self_using_direct_message_group(self) -> None:"""If you send a personal to yourself using direct_message_group, only you see it.@@ -2753,6 +2762,23 @@ class PersonalMessageSendTest(ZulipTestCase):most_recent_message(user_profile).recipient, direct_message_group.recipient)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_personal_to_self_ratchets_to_existing_direct_message_group(self) -> None:+ """+ Self-DMs also ratchet: when a DM group for self already exists,+ PREFER=False still uses it.+ """+ user_profile = self.example_user("hamlet")++ direct_message_group = get_or_create_direct_message_group([user_profile.id])++ self.login("hamlet")+ self.send_personal_message(user_profile, user_profile)++ message = most_recent_message(user_profile)+ self.assertEqual(message.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)+ self.assertEqual(message.recipient_id, direct_message_group.recipient_id)+def assert_personal(self, sender: UserProfile, receiver: UserProfile, content: str = "testcontent") -> None:@@ -2776,12 +2802,9 @@ class PersonalMessageSendTest(ZulipTestCase):self.assertEqual(message_stream_count(sender), sender_messages + 1)self.assertEqual(message_stream_count(receiver), receiver_messages + 1)- direct_message_group = get_direct_message_group([sender.id, receiver.id])has_none_recipient = receiver.recipient is None or sender.recipient is None- if has_none_recipient:+ if has_none_recipient or settings.PREFER_DIRECT_MESSAGE_GROUP:recipient = get_or_create_direct_message_group([sender.id, receiver.id]).recipient- elif settings.PREFER_DIRECT_MESSAGE_GROUP and direct_message_group:- recipient = direct_message_group.recipientelse:recipient = Recipient.objects.get(type_id=receiver.id, type=Recipient.PERSONAL)@@ -2790,7 +2813,8 @@ class PersonalMessageSendTest(ZulipTestCase):self.assertEqual(most_recent_message(sender).topic_name(), Message.DM_TOPIC)self.assertEqual(most_recent_message(receiver).topic_name(), Message.DM_TOPIC)- def test_personal(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_personal_using_personal_recipient(self) -> None:"""If you send a personal, only you and the recipient see it."""@@ -2800,6 +2824,7 @@ class PersonalMessageSendTest(ZulipTestCase):receiver=self.example_user("othello"),)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_personal_using_direct_message_group(self) -> None:"""If you send a personal using direct_message_group, only you and the recipient see it.@@ -2815,6 +2840,27 @@ class PersonalMessageSendTest(ZulipTestCase):receiver=receiver,)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_personal_ratchets_to_existing_direct_message_group(self) -> None:+ """+ When a DM group already exists (created by a PREFER=True process),+ sending with PREFER=False uses the existing DM group rather than+ the personal recipient. This tests the ratcheting mechanism that+ ensures consistency during a rolling deployment.+ """+ sender = self.example_user("hamlet")+ receiver = self.example_user("othello")++ # Simulate a PREFER=True process having created the DM group+ direct_message_group = get_or_create_direct_message_group([sender.id, receiver.id])++ self.login("hamlet")+ self.send_personal_message(sender, receiver)++ message = most_recent_message(sender)+ self.assertEqual(message.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)+ self.assertEqual(message.recipient_id, direct_message_group.recipient_id)+def test_personal_when_personal_recipient_is_none(self) -> None:"""If you send a personal using direct_message_group, only you and the recipient see it.@@ -2835,7 +2881,61 @@ class PersonalMessageSendTest(ZulipTestCase):message = most_recent_message(sender)self.assertEqual(message.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)- def test_direct_message_initiator_group_setting(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_personal_message_using_personal_recipient(self) -> None:+ user_profile = self.example_user("hamlet")+ cordelia = self.example_user("cordelia")++ with self.assert_database_query_count(17):+ self.send_personal_message(user_profile, cordelia)++ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_personal_message_using_direct_message_group(self) -> None:+ user_profile = self.example_user("hamlet")+ cordelia = self.example_user("cordelia")++ with self.assert_database_query_count(25):+ self.send_personal_message(user_profile, cordelia)++ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_direct_message_initiator_group_setting_using_personal_recipient(self) -> None:+ """+ Tests that direct_message_initiator_group_setting works correctly,+ when personal recipients are used for 1:1 conversations.+ """+ user_profile = self.example_user("hamlet")+ polonius = self.example_user("polonius")+ admin = self.example_user("iago")+ cordelia = self.example_user("cordelia")+ realm = user_profile.realm+ administrators_system_group = NamedUserGroup.objects.get(+ name=SystemGroups.ADMINISTRATORS, realm=realm, is_system_group=True+ )+ self.login_user(user_profile)+ self.send_personal_message(user_profile, polonius)+ do_change_realm_permission_group_setting(+ realm,+ "direct_message_initiator_group",+ administrators_system_group,+ acting_user=None,+ )++ # We can send to Polonius because we'd previously messaged him.+ self.send_personal_message(user_profile, polonius)+ # Tests if we can send messages to self irrespective of the value of the setting.+ self.send_personal_message(user_profile, user_profile)+ # We cannot send to users with whom we does not have any direct message conversation.+ with self.assertRaises(DirectMessageInitiationError) as direct_message_initiation_error:+ self.send_personal_message(user_profile, cordelia)+ self.assertEqual(+ str(direct_message_initiation_error.exception),+ "You do not have permission to initiate direct message conversations.",+ )+ with self.assertRaises(DirectMessageInitiationError):+ self.send_personal_message(user_profile, admin)++ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_direct_message_initiator_group_setting_using_direct_message_group(self) -> None:"""Tests that direct_message_initiator_group_setting works correctly."""@@ -2875,7 +2975,7 @@ class PersonalMessageSendTest(ZulipTestCase):# Have the administrator send a message, and verify that allows the user to reply.self.send_personal_message(admin, user_profile)- with self.assert_database_query_count(17):+ with self.assert_database_query_count(19):self.send_personal_message(user_profile, admin)# Tests that user cannot initiate direct message thread in groups.@@ -2911,7 +3011,7 @@ class PersonalMessageSendTest(ZulipTestCase):user_group,acting_user=None,)- with self.assert_database_query_count(17):+ with self.assert_database_query_count(19):self.send_personal_message(user_profile, cordelia)# Test that query count decreases if setting is set to a system group.@@ -2925,9 +3025,10 @@ class PersonalMessageSendTest(ZulipTestCase):acting_user=None,)othello = self.example_user("othello")- with self.assert_database_query_count(16):+ with self.assert_database_query_count(24):self.send_personal_message(user_profile, othello)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_direct_message_permission_group_setting(self) -> None:"""Tests that direct_message_permission_group_setting works correctly.@@ -2953,7 +3054,7 @@ class PersonalMessageSendTest(ZulipTestCase):acting_user=None,)# Tests if the user is allowed to send to administrators.- with self.assert_database_query_count(17):+ with self.assert_database_query_count(25):self.send_personal_message(user_profile, admin)self.send_personal_message(admin, user_profile)# Tests if we can send messages to self irrespective of the value of the setting.@@ -3003,7 +3104,7 @@ class PersonalMessageSendTest(ZulipTestCase):with self.assertRaises(DirectMessagePermissionError):self.send_personal_message(cordelia, polonius)- with self.assert_database_query_count(17):+ with self.assert_database_query_count(19):self.send_personal_message(user_profile, cordelia)# Test that query count decreases if setting is set to a system group.@@ -3016,7 +3117,7 @@ class PersonalMessageSendTest(ZulipTestCase):members_group,acting_user=None,)- with self.assert_database_query_count(16):+ with self.assert_database_query_count(18):self.send_personal_message(user_profile, cordelia)do_change_realm_permission_group_setting(diff --git a/zerver/tests/test_messages.py b/zerver/tests/test_messages.pyindex 41650482ee9..8066452ec53 100644--- a/zerver/tests/test_messages.py+++ b/zerver/tests/test_messages.py@@ -7,6 +7,7 @@ from zerver.lib.test_classes import ZulipTestCasefrom zerver.models import Message, UserPresence, UserProfilefrom zerver.models.recipients import (bulk_get_direct_message_group_user_ids,+ get_direct_message_group,get_direct_message_group_user_ids,get_or_create_direct_message_group,)@@ -126,3 +127,28 @@ class TestBulkGetDirectMessageGroupUserIds(ZulipTestCase):def test_bulk_get_direct_message_group_user_ids_empty_list(self) -> None:self.assertEqual(bulk_get_direct_message_group_user_ids([]), {})+++class TestGetDirectMessageGroup(ZulipTestCase):+ def test_get_direct_message_group_nonexistent(self) -> None:+ """Test that get_direct_message_group returns None when the group doesn't exist."""+ hamlet = self.example_user("hamlet")+ cordelia = self.example_user("cordelia")++ # These users haven't had any group DM, so no DirectMessageGroup exists+ result = get_direct_message_group([hamlet.id, cordelia.id])+ self.assertIsNone(result)++ def test_get_direct_message_group_exists(self) -> None:+ """Test that get_direct_message_group returns the group when it exists."""+ hamlet = self.example_user("hamlet")+ cordelia = self.example_user("cordelia")+ othello = self.example_user("othello")++ # Create a group DM which will create the DirectMessageGroup+ self.send_group_direct_message(hamlet, [cordelia, othello], "test")++ # Now the DirectMessageGroup should exist+ result = get_direct_message_group([hamlet.id, cordelia.id, othello.id])+ assert result is not None+ self.assertEqual(result.group_size, 3)diff --git a/zerver/tests/test_outgoing_webhook_system.py b/zerver/tests/test_outgoing_webhook_system.pyindex bcf13afc9be..97cf7046eb5 100644--- a/zerver/tests/test_outgoing_webhook_system.py+++ b/zerver/tests/test_outgoing_webhook_system.py@@ -22,6 +22,7 @@ from zerver.lib.url_encoding import message_link_urlfrom zerver.lib.users import add_servicefrom zerver.models import Recipient, Service, UserProfilefrom zerver.models.realms import get_realm+from zerver.models.recipients import get_or_create_direct_message_groupfrom zerver.models.streams import get_stream@@ -147,7 +148,10 @@ The webhook got a response with status code *500*.""",)assert bot_user.bot_owner is not None- self.assertEqual(bot_owner_notification.recipient_id, bot_user.bot_owner.recipient_id)+ self.assertEqual(+ bot_owner_notification.recipient_id,+ self.get_dm_group_recipient(bot_user, bot_user.bot_owner).id,+ )def test_bad_msg_type(self) -> None:bot_user = self.example_user("outgoing_webhook_bot")@@ -215,7 +219,10 @@ The webhook got a response with status code *400*.""",)assert bot_user.bot_owner is not None- self.assertEqual(bot_owner_notification.recipient_id, bot_user.bot_owner.recipient_id)+ self.assertEqual(+ bot_owner_notification.recipient_id,+ self.get_dm_group_recipient(bot_user, bot_user.bot_owner).id,+ )def test_headers(self) -> None:bot_user = self.example_user("outgoing_webhook_bot")@@ -259,7 +266,10 @@ The webhook got a response with status code *400*.""",self.assertIn(error_text, bot_owner_notification.content)self.assertIn("triggered", bot_owner_notification.content)assert bot_user.bot_owner is not None- self.assertEqual(bot_owner_notification.recipient_id, bot_user.bot_owner.recipient_id)+ self.assertEqual(+ bot_owner_notification.recipient_id,+ self.get_dm_group_recipient(bot_user, bot_user.bot_owner).id,+ )with self.assertLogs(level="INFO") as i:helper(side_effect=timeout_error, error_text="Request timed out after")@@ -305,7 +315,10 @@ I'm a generic exception :(```""",)assert bot_user.bot_owner is not None- self.assertEqual(bot_owner_notification.recipient_id, bot_user.bot_owner.recipient_id)+ self.assertEqual(+ bot_owner_notification.recipient_id,+ self.get_dm_group_recipient(bot_user, bot_user.bot_owner).id,+ )@override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_jsonable_exception(self) -> None:@@ -335,7 +348,10 @@ The outgoing webhook server attempted to send a message in Zulip, but that reque> Widgets: API programmer sent invalid JSON content\nThe response contains the following payload:\n```\n'{"content": "whatever", "widget_content": "test"}'\n```""",)assert bot_user.bot_owner is not None- self.assertEqual(bot_owner_notification.recipient_id, bot_user.bot_owner.recipient_id)+ self.assertEqual(+ bot_owner_notification.recipient_id,+ self.get_dm_group_recipient(bot_user, bot_user.bot_owner).id,+ )@override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_invalid_response_format(self) -> None:@@ -363,7 +379,10 @@ The outgoing webhook server attempted to send a message in Zulip, but that reque> Invalid response format\nThe response contains the following payload:\n```\n'true'\n```""",)assert bot_user.bot_owner is not None- self.assertEqual(bot_owner_notification.recipient_id, bot_user.bot_owner.recipient_id)+ self.assertEqual(+ bot_owner_notification.recipient_id,+ self.get_dm_group_recipient(bot_user, bot_user.bot_owner).id,+ )@override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_invalid_json_in_response(self) -> None:@@ -393,7 +412,10 @@ The outgoing webhook server attempted to send a message in Zulip, but that reque> Invalid JSON in response\nThe response contains the following payload:\n```\n"this isn't valid json"\n```""",)assert bot_user.bot_owner is not None- self.assertEqual(bot_owner_notification.recipient_id, bot_user.bot_owner.recipient_id)+ self.assertEqual(+ bot_owner_notification.recipient_id,+ self.get_dm_group_recipient(bot_user, bot_user.bot_owner).id,+ )class TestOutgoingWebhookMessaging(ZulipTestCase):@@ -498,11 +520,11 @@ class TestOutgoingWebhookMessaging(ZulipTestCase):self.assertEqual(last_message.sender_id, bot.id)self.assertEqual(last_message.recipient.type_id,- sender.id,+ get_or_create_direct_message_group([bot.id, sender.id]).id,)self.assertEqual(last_message.recipient.type,- Recipient.PERSONAL,+ Recipient.DIRECT_MESSAGE_GROUP,)@override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)@@ -539,11 +561,11 @@ class TestOutgoingWebhookMessaging(ZulipTestCase):self.assertEqual(last_message.sender_id, bot.id)self.assertEqual(last_message.recipient.type_id,- bot_owner.id,+ get_or_create_direct_message_group([bot.id, bot_owner.id]).id,)self.assertEqual(last_message.recipient.type,- Recipient.PERSONAL,+ Recipient.DIRECT_MESSAGE_GROUP,)self.assertTrue(mock_fail.called)@@ -621,7 +643,9 @@ class TestOutgoingWebhookMessaging(ZulipTestCase):)self.assertEqual(last_message.sender_id, bot.id)assert bot.bot_owner is not None- self.assertEqual(last_message.recipient_id, bot.bot_owner.recipient_id)+ self.assertEqual(+ last_message.recipient_id, self.get_dm_group_recipient(bot, bot.bot_owner).id+ )stream_message = self.get_second_to_last_message()self.assertEqual(stream_message.content, "Failure! Bot is unavailable")diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.pyindex 6c258dfe363..a572bf5d260 100644--- a/zerver/tests/test_push_notifications.py+++ b/zerver/tests/test_push_notifications.py@@ -735,6 +735,9 @@ class PushBouncerNotificationTest(BouncerTestCase):def test_send_notification_endpoint_on_free_plans(self) -> None:hamlet = self.example_user("hamlet")+ othello = self.example_user("othello")+ recipient = get_or_create_direct_message_group(id_list=[hamlet.id, othello.id]).recipient+remote_server = self.serverRemotePushDeviceToken.objects.create(kind=RemotePushDeviceToken.FCM,@@ -746,7 +749,7 @@ class PushBouncerNotificationTest(BouncerTestCase):current_time = now()message = Message(sender=hamlet,- recipient=self.example_user("othello").recipient,+ recipient=recipient,realm_id=hamlet.realm_id,content="This is test content",rendered_content="This is test content",@@ -776,12 +779,12 @@ class PushBouncerNotificationTest(BouncerTestCase):"realm_id": hamlet.realm.id,"realm_uri": hamlet.realm.url,"realm_url": hamlet.realm.url,- "user_id": self.example_user("othello").id,+ "user_id": othello.id,}},}old_gcm_payload = {- "user_id": self.example_user("othello").id,+ "user_id": othello.id,"event": "message","alert": "New private message from King Hamlet","zulip_message_id": message.id,@@ -1958,6 +1961,24 @@ class TestGetGCMPayload(PushNotificationTestCase):},)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_get_message_payload_personal_message_to_self(self) -> None:+ hamlet = self.example_user("hamlet")++ # Create a message to self using PERSONAL recipient type+ message = self.get_message(+ Recipient.PERSONAL,+ type_id=hamlet.id,+ realm_id=hamlet.realm_id,+ )+ self.assertEqual(message.sender_id, hamlet.id)+ self.assertEqual(message.recipient.type, Recipient.PERSONAL)++ payload = get_message_payload(hamlet, message, for_legacy_clients=False)++ self.assertEqual(payload["recipient_type"], "direct")+ self.assertEqual(payload["recipient_user_ids"], [hamlet.id])+def test_get_message_payload_gcm_stream_message_from_inaccessible_user(self) -> None:self.set_up_db_for_testing_user_access()diff --git a/zerver/tests/test_realm_creation.py b/zerver/tests/test_realm_creation.pyindex 5cb84a817c4..c34c48f99be 100644--- a/zerver/tests/test_realm_creation.py+++ b/zerver/tests/test_realm_creation.py@@ -81,7 +81,7 @@ class DemoCreationTest(ZulipTestCase):welcome_msg = Message.objects.filter(realm_id=realm.id,sender__email="[email protected]",- recipient__type=Recipient.PERSONAL,+ recipient__type=Recipient.DIRECT_MESSAGE_GROUP,).latest("id")self.assertTrue(welcome_msg.content.startswith("Hello, and welcome to Zulip!"))self.assertIn("getting started guide", welcome_msg.content)@@ -647,7 +647,7 @@ class RealmCreationTest(ZulipTestCase):welcome_msg = Message.objects.filter(realm_id=realm.id,sender__email="[email protected]",- recipient__type=Recipient.PERSONAL,+ recipient__type=Recipient.DIRECT_MESSAGE_GROUP,).latest("id")self.assertTrue(welcome_msg.content.startswith("Hello, and welcome to Zulip!"))@@ -668,7 +668,7 @@ class RealmCreationTest(ZulipTestCase):welcome_msg = Message.objects.filter(realm_id=realm.id,sender__email="[email protected]",- recipient__type=Recipient.PERSONAL,+ recipient__type=Recipient.DIRECT_MESSAGE_GROUP,).latest("id")self.assertTrue(welcome_msg.content.startswith("Hello, and welcome to Zulip!"))self.assertNotIn("I've kicked off some conversations", welcome_msg.content)@@ -715,7 +715,7 @@ class RealmCreationTest(ZulipTestCase):welcome_msg = Message.objects.filter(realm_id=get_realm(string_id).id,sender__email="[email protected]",- recipient__type=Recipient.PERSONAL,+ recipient__type=Recipient.DIRECT_MESSAGE_GROUP,).latest("id")self.assertTrue(welcome_msg.content.startswith("Hello, and welcome to Zulip!"))diff --git a/zerver/tests/test_reminders.py b/zerver/tests/test_reminders.pyindex 113e324ceb3..c18333b1e14 100644--- a/zerver/tests/test_reminders.py+++ b/zerver/tests/test_reminders.py@@ -76,7 +76,8 @@ class RemindersTest(ZulipTestCase):f"@_**King Hamlet|10** [said](http://zulip.testserver/#narrow/channel/3-Verona/topic/test/near/{msg_id}) in [#Verona > test](#narrow/channel/3-Verona/topic/test/with/{msg_id}):\n```quote\n{msg_content}\n```")- def test_schedule_reminder(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_schedule_reminder_using_personal_recipient(self) -> None:self.login("hamlet")content = "Test message"scheduled_delivery_timestamp = int(time.time() + 86400)@@ -91,7 +92,7 @@ class RemindersTest(ZulipTestCase):self.get_channel_message_reminder_content(content, message_id),)# Recipient and sender are the same for reminders.- self.assertEqual(scheduled_message.recipient.type_id, self.example_user("hamlet").id)+ self.assertEqual(scheduled_message.recipient, self.example_user("hamlet").recipient)self.assertEqual(scheduled_message.sender, self.example_user("hamlet"))self.assertEqual(scheduled_message.scheduled_timestamp,@@ -105,6 +106,7 @@ class RemindersTest(ZulipTestCase):# Scheduling a direct message with user IDs is successful.othello = self.example_user("othello")+ hamlet = self.example_user("hamlet")message_id = self.send_dm_from_hamlet_to_othello(content)result = self.do_schedule_reminder(message_id, scheduled_delivery_timestamp)self.assert_json_success(result)@@ -113,8 +115,8 @@ class RemindersTest(ZulipTestCase):scheduled_message.content,self.get_dm_reminder_content(content, message_id, [othello]),)- self.assertEqual(scheduled_message.recipient.type_id, self.example_user("hamlet").id)- self.assertEqual(scheduled_message.sender, self.example_user("hamlet"))+ self.assertEqual(scheduled_message.recipient, hamlet.recipient)+ self.assertEqual(scheduled_message.sender, hamlet)self.assertEqual(scheduled_message.scheduled_timestamp,timestamp_to_datetime(scheduled_delivery_timestamp),diff --git a/zerver/tests/test_rocketchat_importer.py b/zerver/tests/test_rocketchat_importer.pyindex fdcb530f3f7..33adb417fbe 100644--- a/zerver/tests/test_rocketchat_importer.py+++ b/zerver/tests/test_rocketchat_importer.py@@ -1003,7 +1003,7 @@ class RocketChatImporter(ZulipTestCase):return orjson.loads(f.read())@override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)- def test_do_convert_data(self) -> None:+ def test_do_convert_data_using_personal_recipient(self) -> None:rocketchat_data_dir = self.fixture_file_name("", "rocketchat_fixtures")output_dir = self.make_import_output_dir("rocketchat")diff --git a/zerver/tests/test_scheduled_messages.py b/zerver/tests/test_scheduled_messages.pyindex dc7696ae9e0..a91f7002de3 100644--- a/zerver/tests/test_scheduled_messages.py+++ b/zerver/tests/test_scheduled_messages.py@@ -164,6 +164,7 @@ class ScheduledMessageTest(ZulipTestCase):recipient = Recipient.objects.get(type=Recipient.STREAM, type_id=stream_id)self.assert_scheduled_message_delivered(scheduled_message, recipient)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_successful_deliver_direct_scheduled_message_to_other(self) -> None:# No scheduled messageself.assertFalse(try_deliver_one_scheduled_message())@@ -195,7 +196,9 @@ class ScheduledMessageTest(ZulipTestCase):self.assert_json_error(updated_response, "Scheduled message was already sent")@override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)- def test_successful_deliver_personal_scheduled_message_using_direct_message_group(self) -> None:+ def test_successful_deliver_direct_scheduled_message_to_other_using_direct_message_group(+ self,+ ) -> None:# No scheduled messageself.assertFalse(try_deliver_one_scheduled_message())@@ -204,45 +207,18 @@ class ScheduledMessageTest(ZulipTestCase):scheduled_delivery_timestamp = int(scheduled_delivery_datetime.timestamp())sender = self.example_user("hamlet")othello = self.example_user("othello")-- # Create a direct message group for the sender and othello.- direct_message_group = get_or_create_direct_message_group(id_list=[sender.id, othello.id])-response = self.do_schedule_message(- "direct", [othello.id], f"{content} 4", scheduled_delivery_timestamp+ "direct", [othello.id], f"{content} 3", scheduled_delivery_timestamp)self.assert_json_success(response)scheduled_message = self.last_scheduled_message()- # mock current time to be greater than the scheduled time.- more_than_scheduled_delivery_datetime = scheduled_delivery_datetime + timedelta(minutes=1)-- with (- time_machine.travel(more_than_scheduled_delivery_datetime, tick=False),- self.assertLogs(level="INFO") as logs,- ):- result = try_deliver_one_scheduled_message()- self.assertTrue(result)- self.assertEqual(- logs.output,- [- f"INFO:root:Sending scheduled message {scheduled_message.id} with date {scheduled_message.scheduled_timestamp} (sender: {scheduled_message.sender_id})"- ],- )- scheduled_message.refresh_from_db()- assert isinstance(scheduled_message.delivered_message_id, int)- self.assertEqual(scheduled_message.delivered, True)- self.assertEqual(scheduled_message.failed, False)- delivered_message = Message.objects.get(id=scheduled_message.delivered_message_id)- self.assertEqual(delivered_message.content, scheduled_message.content)- self.assertEqual(delivered_message.recipient, direct_message_group.recipient)- self.assertEqual(delivered_message.rendered_content, scheduled_message.rendered_content)- self.assertEqual(delivered_message.date_sent, more_than_scheduled_delivery_datetime)- sender_user_message = UserMessage.objects.get(- message_id=scheduled_message.delivered_message_id, user_profile_id=sender.id- )- self.assertTrue(sender_user_message.flags.read)+ direct_message_group = get_or_create_direct_message_group(id_list=[sender.id, othello.id])+ self.assert_scheduled_message_delivered(+ scheduled_message, recipient=direct_message_group.recipient+ )+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_successful_deliver_direct_scheduled_message_to_self(self) -> None:# No scheduled messageself.assertFalse(try_deliver_one_scheduled_message())@@ -320,7 +296,7 @@ class ScheduledMessageTest(ZulipTestCase):# the failed scheduled message.realm = scheduled_message.realmmsg = most_recent_message(scheduled_message.sender)- self.assertEqual(msg.recipient.type, msg.recipient.PERSONAL)+ self.assertEqual(msg.recipient.type, msg.recipient.DIRECT_MESSAGE_GROUP)self.assertEqual(msg.sender_id, self.notification_bot(realm).id)self.assertIn(expected_failure_message, msg.content)@@ -379,9 +355,8 @@ class ScheduledMessageTest(ZulipTestCase):self.assertEqual(message_after_deactivation.content, message_before_deactivation.content)self.assertNotIn(expected_failure_message, message_after_deactivation.content)- def test_failed_to_deliver_scheduled_message_unknown_exception(- self,- ) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_failed_to_deliver_scheduled_message_unknown_exception(self) -> None:self.create_scheduled_message()scheduled_message = self.last_scheduled_message()@@ -472,6 +447,7 @@ class ScheduledMessageTest(ZulipTestCase):)self.assert_json_error(result, "Scheduled delivery time must be in the future.")+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_edit_schedule_message(self) -> None:content = "Original test message"scheduled_delivery_timestamp = int(time.time() + 86400)diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.pyindex ee8a1306f17..23175110830 100644--- a/zerver/tests/test_signup.py+++ b/zerver/tests/test_signup.py@@ -439,7 +439,7 @@ class AddNewUserHistoryTest(ZulipTestCase):# Initial DM sent by welcome bot is also starred.initial_direct_user_message = UserMessage.objects.get(- user_profile=hamlet, message__recipient__type=Recipient.PERSONAL+ user_profile=hamlet, message__recipient__type=Recipient.DIRECT_MESSAGE_GROUP)self.assertTrue(initial_direct_user_message.flags.starred.is_set)@@ -457,7 +457,7 @@ class AddNewUserHistoryTest(ZulipTestCase):new_messages_count = message_stream_count(user_profile)self.assertEqual(new_messages_count, old_messages_count + 1)- recipient = Recipient.objects.get(type_id=user_profile.id, type=Recipient.PERSONAL)+ recipient = self.get_dm_group_recipient(user_profile)message = most_recent_message(user_profile)self.assertEqual(message.recipient, recipient)@@ -1070,7 +1070,7 @@ class LoginTest(ZulipTestCase):# to sending messages, such as getting the welcome bot, looking up# the alert words for a realm, etc.with (- self.assert_database_query_count(97),+ self.assert_database_query_count(105),self.assert_memcached_count(18),self.captureOnCommitCallbacks(execute=True),):@@ -3619,7 +3619,7 @@ class UserSignUpTest(ZulipTestCase):welcome_msg = Message.objects.filter(realm_id=realm.id,sender__email="[email protected]",- recipient__type=Recipient.PERSONAL,+ recipient__type=Recipient.DIRECT_MESSAGE_GROUP,).latest("id")self.assertTrue(welcome_msg.content.startswith("Hello, and welcome to Zulip!"))diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.pyindex 9fc4fb3d9f9..e29eddb201d 100644--- a/zerver/tests/test_subs.py+++ b/zerver/tests/test_subs.py@@ -11,6 +11,7 @@ from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.db import transactionfrom django.http import HttpResponse+from django.test import override_settingsfrom django.utils.timezone import now as timezone_nowfrom typing_extensions import override@@ -5358,6 +5359,7 @@ class SubscriptionAPITest(ZulipTestCase):expected_difference=0,)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_notification_bot_dm_on_subscription(self) -> None:desdemona = self.example_user("desdemona")realm = desdemona.realmdiff --git a/zerver/tests/test_tutorial.py b/zerver/tests/test_tutorial.pyindex b8659ff1012..7933a2d3dca 100644--- a/zerver/tests/test_tutorial.py+++ b/zerver/tests/test_tutorial.py@@ -131,9 +131,17 @@ class TutorialTests(ZulipTestCase):)self.assertEqual(most_recent_message(user).content, expected_response)- def test_response_to_pm_for_help(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_response_to_pm_for_help_using_personal_recipient(self) -> None:user = self.example_user("hamlet")bot = get_system_bot(settings.WELCOME_BOT, user.realm_id)++ # We delete the DM group because @override_settings does not+ # include the setUp phase, which will have pre-created the DM+ # group already; and we always use the DM group if it exists.+ direct_group_message = get_or_create_direct_message_group(id_list=[user.id, bot.id])+ direct_group_message.delete()+messages = ["help", "Help", "?"]self.login_user(user)for content in messages:@@ -183,7 +191,8 @@ class TutorialTests(ZulipTestCase):self.assertEqual(message.content, content)self.assertEqual(message.sender, user)- def test_response_to_pm_for_undefined(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)+ def test_response_to_pm_for_undefined_using_personal_recipient(self) -> None:user = self.example_user("hamlet")bot = get_system_bot(settings.WELCOME_BOT, user.realm_id)messages = ["Hello", "HAHAHA", "OKOK", "LalulaLapas"]diff --git a/zerver/tests/test_typing.py b/zerver/tests/test_typing.pyindex 214ef4f3222..727a1a877d3 100644--- a/zerver/tests/test_typing.py+++ b/zerver/tests/test_typing.py@@ -1,4 +1,5 @@import orjson+from django.test import override_settingsfrom zerver.actions.streams import do_deactivate_stream, do_unarchive_streamfrom zerver.lib.test_classes import ZulipTestCase@@ -796,6 +797,7 @@ class TestSendTypingNotificationsSettings(ZulipTestCase):self.assertNotIn(aaron.id, event_user_ids)self.assertIn(iago.id, event_user_ids)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_send_direct_message_edit_typing_notifications_setting(self) -> None:sender = self.example_user("hamlet")recipient_user = self.example_user("othello")diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.pyindex 6a89d50929c..82969dc51fa 100644--- a/zerver/tests/test_users.py+++ b/zerver/tests/test_users.py@@ -426,6 +426,7 @@ class PermissionTest(ZulipTestCase):result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req)self.assert_json_error(result, "Insufficient permission")+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_admin_user_can_change_full_name(self) -> None:new_name = "new name"self.login("iago")@@ -440,7 +441,12 @@ class PermissionTest(ZulipTestCase):# Check that notification was sentmessage = most_recent_message(hamlet)- self.assertEqual(message.recipient.type_id, hamlet.id)+ self.assertEqual(message.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)++ notification_bot = get_system_bot(settings.NOTIFICATION_BOT, hamlet.realm.id)+ dm_group_recipient = self.get_dm_group_recipient(notification_bot, hamlet)+ self.assertEqual(message.recipient, dm_group_recipient)+self.assertIn(f"{silent_mention_syntax_for_user(iago)} has made the following changes to your account.",message.content,@@ -548,6 +554,7 @@ class PermissionTest(ZulipTestCase):result = self.client_patch("/json/users/{}".format(self.example_user("hamlet").id), req)self.assert_json_error(result, "Invalid characters in name!")+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_access_user_by_id(self) -> None:iago = self.example_user("iago")internal_realm = get_realm(settings.SYSTEM_BOT_REALM)@@ -772,7 +779,12 @@ class PermissionTest(ZulipTestCase):# Test notification is sentmessage = most_recent_message(user_profile)- self.assertEqual(message.recipient.type_id, user_profile.id)+ self.assertEqual(message.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)++ notification_bot = get_system_bot(settings.NOTIFICATION_BOT, user_profile.realm_id)+ dm_group_recipient = self.get_dm_group_recipient(notification_bot, user_profile)+ self.assertEqual(message.recipient, dm_group_recipient)+self.assertIn(f"{silent_mention_syntax_for_user(admin)} has made the following changes to your account.",message.content,@@ -782,53 +794,67 @@ class PermissionTest(ZulipTestCase):message.content,)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_change_regular_member_to_guest(self) -> None:self.check_user_role_change("hamlet", UserProfile.ROLE_GUEST)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_change_guest_to_regular_member(self) -> None:self.check_user_role_change("polonius", UserProfile.ROLE_MEMBER)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_change_admin_to_guest(self) -> None:self.check_user_role_change("iago", UserProfile.ROLE_GUEST)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_change_guest_to_admin(self) -> None:self.check_user_role_change("polonius", UserProfile.ROLE_REALM_ADMINISTRATOR)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_change_owner_to_guest(self) -> None:self.login("desdemona")iago = self.example_user("iago")self.set_user_role(iago, UserProfile.ROLE_REALM_OWNER)self.check_user_role_change("iago", UserProfile.ROLE_GUEST)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_change_guest_to_owner(self) -> None:self.check_user_role_change("polonius", UserProfile.ROLE_REALM_OWNER)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_change_admin_to_owner(self) -> None:self.check_user_role_change("iago", UserProfile.ROLE_REALM_OWNER)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_change_owner_to_admin(self) -> None:self.login("desdemona")iago = self.example_user("iago")self.set_user_role(iago, UserProfile.ROLE_REALM_OWNER)self.check_user_role_change("iago", UserProfile.ROLE_REALM_ADMINISTRATOR)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_change_owner_to_moderator(self) -> None:iago = self.example_user("iago")self.set_user_role(iago, UserProfile.ROLE_REALM_OWNER)self.check_user_role_change("iago", UserProfile.ROLE_MODERATOR)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_change_moderator_to_owner(self) -> None:self.check_user_role_change("shiva", UserProfile.ROLE_REALM_OWNER)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_change_admin_to_moderator(self) -> None:self.check_user_role_change("iago", UserProfile.ROLE_MODERATOR)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_change_moderator_to_admin(self) -> None:self.check_user_role_change("shiva", UserProfile.ROLE_REALM_ADMINISTRATOR)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_change_guest_to_moderator(self) -> None:self.check_user_role_change("polonius", UserProfile.ROLE_MODERATOR)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_change_moderator_to_guest(self) -> None:self.check_user_role_change("shiva", UserProfile.ROLE_GUEST)@@ -1103,7 +1129,8 @@ class PermissionTest(ZulipTestCase):class QueryCountTest(ZulipTestCase):- def test_create_user_with_multiple_streams(self) -> None:+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_create_user_with_multiple_streams_with_direct_message_group(self) -> None:# add_new_user_history needs messages to be currentMessage.objects.all().update(date_sent=timezone_now())@@ -1140,7 +1167,7 @@ class QueryCountTest(ZulipTestCase):prereg_user = PreregistrationUser.objects.get(email="[email protected]")with (- self.assert_database_query_count(88),+ self.assert_database_query_count(104),self.assert_memcached_count(23),self.capture_send_event_calls(expected_num_events=11) as events,):@@ -1465,7 +1492,8 @@ class AdminCreateUserTest(ZulipTestCase):# Make sure the recipient field is set correctly.self.assertEqual(- new_user.recipient, Recipient.objects.get(type=Recipient.PERSONAL, type_id=new_user.id)+ new_user.recipient,+ Recipient.objects.get(type=Recipient.PERSONAL, type_id=new_user.id),)# we can't create the same user twice.@@ -2704,6 +2732,7 @@ class DeactivateActionsTest(ZulipTestCase):self.assert_length(user_message_ids, 7)self.assertCountEqual(user_message_ids, [*public_channel_msg_ids, *dm_msg_ids])+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_deactivation_with_deleting_direct_messages(self) -> None:admin = self.example_user("iago")user = self.example_user("cordelia")@@ -3574,6 +3603,7 @@ class GetProfileTest(ZulipTestCase):self.assertEqual(result["user"].get("delivery_email"), hamlet.delivery_email)self.assertEqual(result["user"].get("email"), hamlet.delivery_email)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_restricted_access_to_users(self) -> None:hamlet = self.example_user("hamlet")iago = self.example_user("iago")@@ -3586,7 +3616,7 @@ class GetProfileTest(ZulipTestCase):self.set_up_db_for_testing_user_access()self.login("polonius")- with self.assert_database_query_count(9):+ with self.assert_database_query_count(10):result = orjson.loads(self.client_get("/json/users").content)accessible_users = result["members"]# The user can access 3 bot users and 7 human users.@@ -3641,7 +3671,7 @@ class GetProfileTest(ZulipTestCase):accessible_user_ids_subset = [hamlet.id, iago.id, aaron.id, zoe.id, webhook_bot.id]inaccessible_user_ids_subset = [cordelia.id, desdemona.id]user_ids_to_fetch = accessible_user_ids_subset + inaccessible_user_ids_subset- with self.assert_database_query_count(9):+ with self.assert_database_query_count(11):result = orjson.loads(self.client_get("/json/users", {"user_ids": orjson.dumps(user_ids_to_fetch).decode()}@@ -3710,7 +3740,7 @@ class GetProfileTest(ZulipTestCase):result = self.client_get(f"/json/users/{user.id}")self.assert_json_error(result, "Insufficient permission")- with self.settings(PARTIAL_USERS=True), self.assert_database_query_count(9):+ with self.settings(PARTIAL_USERS=True), self.assert_database_query_count(11):result = self.client_get("/json/users")self.assert_json_success(result)@@ -3721,6 +3751,7 @@ class GetProfileTest(ZulipTestCase):UserProfile.objects.filter(realm=hamlet.realm, is_bot=True).count() + 1,)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=False)def test_get_inaccessible_user_ids(self) -> None:polonius = self.example_user("polonius")bot = self.example_user("default_bot")@@ -3820,6 +3851,36 @@ class GetProfileTest(ZulipTestCase):self.assertIn(othello.id, users_involved_with_deactivated[hamlet.id])self.assertIn(cordelia.id, users_involved_with_deactivated[hamlet.id])+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)+ def test_get_users_involved_in_dms_with_dm_group_recipients(self) -> None:+ hamlet = self.example_user("hamlet")+ othello = self.example_user("othello")+ cordelia = self.example_user("cordelia")+ realm = hamlet.realm++ self.send_personal_message(hamlet, othello, "Hello othello!")+ self.send_personal_message(hamlet, cordelia, "Hello cordelia!")++ users_involved = get_users_involved_in_dms_with_target_users(+ [hamlet], realm, include_deactivated_users=False+ )+ self.assertIn(othello.id, users_involved[hamlet.id])+ self.assertIn(cordelia.id, users_involved[hamlet.id])++ do_deactivate_user(othello, acting_user=None)++ users_involved_after = get_users_involved_in_dms_with_target_users(+ [hamlet], realm, include_deactivated_users=False+ )+ self.assertNotIn(othello.id, users_involved_after[hamlet.id])+ self.assertIn(cordelia.id, users_involved_after[hamlet.id])++ users_involved_with_deactivated = get_users_involved_in_dms_with_target_users(+ [hamlet], realm, include_deactivated_users=True+ )+ self.assertIn(othello.id, users_involved_with_deactivated[hamlet.id])+ self.assertIn(cordelia.id, users_involved_with_deactivated[hamlet.id])+def test_get_users_for_spectators(self) -> None:# Checks that spectators can fetch users data.hamlet = self.example_user("hamlet")@@ -3869,12 +3930,13 @@ class GetProfileTest(ZulipTestCase):class DeleteUserTest(ZulipTestCase):+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_do_delete_user(self) -> None:realm = get_realm("zulip")cordelia = self.example_user("cordelia")othello = self.example_user("othello")hamlet = self.example_user("hamlet")- hamlet_personal_recipient = hamlet.recipient+ hamlet_and_cordelia_recipient = self.get_dm_group_recipient(hamlet, cordelia)hamlet_user_id = hamlet.idhamlet_date_joined = hamlet.date_joined@@ -3886,7 +3948,7 @@ class DeleteUserTest(ZulipTestCase):self.send_personal_message(hamlet, cordelia)personal_message_ids_to_hamlet = Message.objects.filter(- realm_id=realm.id, recipient=hamlet_personal_recipient+ realm_id=realm.id, recipient=hamlet_and_cordelia_recipient).values_list("id", flat=True)personal_message_ids_to_hamlet_original_count = len(personal_message_ids_to_hamlet)self.assertGreater(personal_message_ids_to_hamlet_original_count, 0)@@ -3929,15 +3991,9 @@ class DeleteUserTest(ZulipTestCase):self.assertEqual(hamlet.is_active, False)self.assertEqual(hamlet.date_joined, hamlet_date_joined)- # Messages that were sent TO the user are preserved. They'll just appear- # to the senders as sent to a deleted dummy user.- self.assertEqual(- Message.objects.filter(id__in=personal_message_ids_to_hamlet).count(),- personal_message_ids_to_hamlet_original_count,- )-# Group direct messages from hamlet should have been deleted, but messages of other# participants should be kept.+ self.assertEqual(Message.objects.filter(id__in=personal_message_ids_to_hamlet).count(), 1)self.assertEqual(Message.objects.filter(id__in=group_direct_message_ids_from_hamlet).count(), 0)@@ -3971,6 +4027,7 @@ class DeleteUserTest(ZulipTestCase):self.assertEqual(ScheduledEmail.objects.count(), 0)+ @override_settings(PREFER_DIRECT_MESSAGE_GROUP=True)def test_do_delete_user_preserving_messages(self) -> None:"""Since do_delete_user and do_delete_user_preserving_messages share the same@@ -3984,14 +4041,14 @@ class DeleteUserTest(ZulipTestCase):cordelia = self.example_user("cordelia")othello = self.example_user("othello")hamlet = self.example_user("hamlet")- hamlet_personal_recipient = hamlet.recipient+ hamlet_and_cordelia_recipient = self.get_dm_group_recipient(hamlet, cordelia)hamlet_user_id = hamlet.idself.send_personal_message(cordelia, hamlet)self.send_personal_message(hamlet, cordelia)personal_message_ids_to_hamlet = Message.objects.filter(- realm_id=realm.id, recipient=hamlet_personal_recipient+ realm_id=realm.id, recipient=hamlet_and_cordelia_recipient).values_list("id", flat=True)self.assertGreater(len(personal_message_ids_to_hamlet), 0)self.assertTrue(Message.objects.filter(realm_id=realm.id, sender=hamlet).exists())diff --git a/zerver/tests/test_zulip_update_announcements.py b/zerver/tests/test_zulip_update_announcements.pyindex b5a55629436..9fe530c1261 100644--- a/zerver/tests/test_zulip_update_announcements.py+++ b/zerver/tests/test_zulip_update_announcements.py@@ -444,13 +444,15 @@ class ZulipUpdateAnnouncementsTest(ZulipTestCase):self.assertEqual(imported_realm.zulip_update_announcements_stream, gryffindor_common_room)- personal_message = Message.objects.filter(- realm=imported_realm, sender=notification_bot, recipient__type=Recipient.PERSONAL+ bot_message = Message.objects.filter(+ realm=imported_realm,+ sender=notification_bot,+ recipient__type=Recipient.DIRECT_MESSAGE_GROUP,).first()- assert personal_message is not None+ assert bot_message is not Noneself.assertIn("Starting tomorrow, users in your organization will receive",- personal_message.content,+ bot_message.content,)# Two new updates added.diff --git a/zerver/webhooks/freshstatus/tests.py b/zerver/webhooks/freshstatus/tests.pyindex f88c7f20647..fbbc9e9f441 100644--- a/zerver/webhooks/freshstatus/tests.py+++ b/zerver/webhooks/freshstatus/tests.py@@ -203,4 +203,4 @@ The following scheduled maintenance has been closed: **Scheduled Maintenance Tesmsg = self.get_last_message()self.assertEqual(msg.content, expected_message)- self.assertEqual(msg.recipient.type, Recipient.PERSONAL)+ self.assertEqual(msg.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)diff --git a/zerver/webhooks/teamcity/tests.py b/zerver/webhooks/teamcity/tests.pyindex 88aaed0f65c..a8607f4b6f5 100644--- a/zerver/webhooks/teamcity/tests.py+++ b/zerver/webhooks/teamcity/tests.py@@ -41,7 +41,7 @@ class TeamCityHookTests(WebhookTestCase):msg = self.get_last_message()self.assertEqual(msg.content, expected_message)- self.assertEqual(msg.recipient.type, Recipient.PERSONAL)+ self.assertEqual(msg.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)def test_non_generic_payload_ignore_pm_notification(self) -> None:expected_message = MISCONFIGURED_PAYLOAD_TYPE_ERROR_MESSAGE.format(@@ -55,4 +55,4 @@ class TeamCityHookTests(WebhookTestCase):msg = self.get_last_message()self.assertEqual(msg.content, expected_message)- self.assertEqual(msg.recipient.type, Recipient.PERSONAL)+ self.assertEqual(msg.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)diff --git a/zerver/webhooks/uptimerobot/tests.py b/zerver/webhooks/uptimerobot/tests.pyindex 39d7432ab6d..a7513c8954c 100644--- a/zerver/webhooks/uptimerobot/tests.py+++ b/zerver/webhooks/uptimerobot/tests.py@@ -40,4 +40,4 @@ It was down for 44 minutes and 37 seconds.msg = self.get_last_message()self.assertEqual(msg.content, expected_message)- self.assertEqual(msg.recipient.type, Recipient.PERSONAL)+ self.assertEqual(msg.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)diff --git a/zerver/webhooks/zabbix/tests.py b/zerver/webhooks/zabbix/tests.pyindex ad4fbb5450c..a68a1a8aeb7 100644--- a/zerver/webhooks/zabbix/tests.py+++ b/zerver/webhooks/zabbix/tests.py@@ -29,4 +29,4 @@ class ZabbixHookTests(WebhookTestCase):msg = self.get_last_message()self.assertEqual(msg.content, expected_message)- self.assertEqual(msg.recipient.type, Recipient.PERSONAL)+ self.assertEqual(msg.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)