From d0e2eac701832704322b350840e776f798d0d653 Mon Sep 17 00:00:00 2001 From: Artem Smirnov Date: Mon, 23 Nov 2026 22:31:10 +0200 Subject: [PATCH] Pin the current behaviour of the outgoing SMS/MMS pipeline with Robolectric tests behind a driver interface that a new implementation can reuse --- .../action/InsertNewMessageActionTest.kt | 225 +++++++++++ .../action/OutgoingPipelineActionRunner.kt | 149 +++++++ .../action/OutgoingPipelineDriver.kt | 156 +++++++ .../action/OutgoingPipelineTelephony.kt | 382 ++++++++++++++++++ .../action/OutgoingPipelineTestBase.kt | 44 ++ .../datamodel/action/OutgoingPipelineWorld.kt | 355 ++++++++++++++++ .../action/OutgoingProcessRestartTest.kt | 71 ++++ .../ProcessPendingMessagesActionTest.kt | 190 +++++++++ .../action/ResendMessageActionTest.kt | 105 +++++ .../datamodel/action/SendMessageActionTest.kt | 270 +++++++++++++ 10 files changed, 1947 insertions(+) create mode 100644 app/src/test/kotlin/com/android/messaging/datamodel/action/InsertNewMessageActionTest.kt create mode 100644 app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineActionRunner.kt create mode 100644 app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineDriver.kt create mode 100644 app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineTelephony.kt create mode 100644 app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineTestBase.kt create mode 100644 app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineWorld.kt create mode 100644 app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingProcessRestartTest.kt create mode 100644 app/src/test/kotlin/com/android/messaging/datamodel/action/ProcessPendingMessagesActionTest.kt create mode 100644 app/src/test/kotlin/com/android/messaging/datamodel/action/ResendMessageActionTest.kt create mode 100644 app/src/test/kotlin/com/android/messaging/datamodel/action/SendMessageActionTest.kt diff --git a/app/src/test/kotlin/com/android/messaging/datamodel/action/InsertNewMessageActionTest.kt b/app/src/test/kotlin/com/android/messaging/datamodel/action/InsertNewMessageActionTest.kt new file mode 100644 index 000000000..4252d2979 --- /dev/null +++ b/app/src/test/kotlin/com/android/messaging/datamodel/action/InsertNewMessageActionTest.kt @@ -0,0 +1,225 @@ +package com.android.messaging.datamodel.action + +import android.app.Activity +import android.provider.Telephony.Mms +import android.provider.Telephony.Sms +import com.android.messaging.datamodel.data.MessageData +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class InsertNewMessageActionTest : OutgoingPipelineTestBase() { + + @Test + fun singleSegmentSmsIsWrittenToTelephonyAndSentOnItsConversationSim() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + + driver.sendSmsDraft(conversationId = conversationId, text = SHORT_TEXT) + + val message = world.messagesIn(conversationId = conversationId).single() + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, message.status) + assertEquals(MessageData.PROTOCOL_SMS, message.protocol) + assertEquals(world.selfIdFor(subId = FakeTelephony.SUB_ID_SIM_1), message.selfId) + val insert = telephony.smsInserts.single() + assertEquals(FakeTelephony.SUB_ID_SIM_1, insert.subId) + assertEquals(RECIPIENT_A, insert.address) + assertEquals(SHORT_TEXT, insert.text) + assertEquals(Sms.STATUS_NONE, insert.status) + assertEquals(Sms.MESSAGE_TYPE_SENT, insert.type) + assertEquals(insert.uri.toString(), message.smsMessageUri) + val send = telephony.smsSends.single() + assertEquals(RECIPIENT_A, send.destination) + assertEquals(listOf(SHORT_TEXT), send.parts) + assertEquals(listOf(0), send.partIds) + assertEquals(FakeTelephony.SUB_ID_SIM_1, send.subId) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_SENDING, send.localStatusAtSend) + assertEquals( + listOf(Sms.MESSAGE_TYPE_SENT, Sms.MESSAGE_TYPE_SENT), + telephony.smsStatusUpdates.map { update -> update.typeOrBox }, + ) + assertNull(driver.pendingRetryDelayMillis(subId = FakeTelephony.SUB_ID_SIM_1)) + } + + @Test + fun broadcastSmsKeepsOneSentCopyAndSendsOneMessagePerRecipientInItsOwnConversation() { + val recipients = listOf(RECIPIENT_A, RECIPIENT_B) + val conversationId = world.createConversation(recipients = recipients) + + driver.sendSmsDraft(conversationId = conversationId, text = SHORT_TEXT) + + val broadcast = world.messagesIn(conversationId = conversationId).single() + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, broadcast.status) + val broadcastInsert = telephony.smsInserts.first() + assertEquals(broadcastInsert.uri.toString(), broadcast.smsMessageUri) + assertEquals(recipients.joinToString(separator = " "), broadcastInsert.address) + assertEquals(Sms.STATUS_COMPLETE, broadcastInsert.status) + assertEquals(telephony.threadIdFor(recipients = recipients), broadcastInsert.threadId) + val perRecipientInserts = telephony.smsInserts.drop(1) + assertEquals(recipients, perRecipientInserts.map { insert -> insert.address }) + assertEquals( + perRecipientInserts.map { insert -> insert.timestamp + 1 }.distinct(), + listOf(broadcastInsert.timestamp), + ) + recipients.forEach { recipient -> + val oneToOneConversationId = requireNotNull( + world.conversationIdForThread( + threadId = telephony.threadIdFor(recipients = listOf(recipient)), + ), + ) + val sent = world.messagesIn(conversationId = oneToOneConversationId).single() + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, sent.status) + assertEquals(world.selfIdFor(subId = FakeTelephony.SUB_ID_SIM_1), sent.selfId) + } + assertEquals( + recipients.sorted(), + telephony.smsSends.map { send -> send.destination }.sorted(), + ) + telephony.smsSends.forEach { send -> + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_SENDING, send.localStatusAtSend) + assertEquals(listOf(SHORT_TEXT), send.parts) + } + } + + @Test + fun groupMmsIsWrittenToTelephonyOnceAndCompletesWhenThePlatformReportsSuccess() { + val recipients = listOf(RECIPIENT_A, RECIPIENT_B) + val conversationId = world.createConversation(recipients = recipients) + + driver.sendMmsDraft(conversationId = conversationId, text = SHORT_TEXT) + + val sending = world.messagesIn(conversationId = conversationId).single() + assertEquals(MessageData.PROTOCOL_MMS, sending.protocol) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_SENDING, sending.status) + assertEquals(0L, sending.receivedTimestamp % MILLIS_PER_SECOND) + val insert = telephony.mmsInserts.single() + assertEquals(recipients, insert.recipients) + assertEquals(FakeTelephony.SUB_ID_SIM_1, insert.subId) + assertEquals(SHORT_TEXT, insert.text) + assertEquals(insert.uri.toString(), sending.smsMessageUri) + val send = telephony.mmsSends.single() + assertEquals(FakeTelephony.SUB_ID_SIM_1, send.subId) + assertEquals(insert.uri, send.messageUri) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_SENDING, send.localStatusAtSend) + assertEquals( + sending.id, + send.sentIntentExtras.getString(SendMessageAction.EXTRA_MESSAGE_ID), + ) + assertEquals(emptyList(), telephony.mmsStatusUpdates) + + driver.deliverMmsSentResult(resultCode = Activity.RESULT_OK) + + val sent = world.message(messageId = sending.id) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, sent.status) + assertEquals(insert.uri.toString(), sent.smsMessageUri) + assertEquals( + listOf(Mms.MESSAGE_BOX_SENT), + telephony.mmsStatusUpdates.map { update -> update.typeOrBox }, + ) + assertNull(driver.pendingRetryDelayMillis(subId = FakeTelephony.SUB_ID_SIM_1)) + } + + @Test + fun recipientsWithoutSubjectAreSentAsSmsOnTheRequestedSim() { + driver.sendToRecipients( + subId = FakeTelephony.SUB_ID_SIM_2, + recipients = listOf(RECIPIENT_A), + text = SHORT_TEXT, + subject = null, + ) + + val conversationId = requireNotNull( + world.conversationIdForThread( + threadId = telephony.threadIdFor(recipients = listOf(RECIPIENT_A)), + ), + ) + val message = world.messagesIn(conversationId = conversationId).single() + assertEquals(MessageData.PROTOCOL_SMS, message.protocol) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, message.status) + assertEquals(world.selfIdFor(subId = FakeTelephony.SUB_ID_SIM_2), message.selfId) + assertEquals(FakeTelephony.SUB_ID_SIM_2, telephony.smsSends.single().subId) + } + + @Test + fun recipientsWithSubjectAreSentAsMms() { + driver.sendToRecipients( + subId = FakeTelephony.SUB_ID_SIM_1, + recipients = listOf(RECIPIENT_A), + text = SHORT_TEXT, + subject = SUBJECT, + ) + + val message = world.allMessages().single() + assertEquals(MessageData.PROTOCOL_MMS, message.protocol) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_SENDING, message.status) + assertEquals(SUBJECT, telephony.mmsInserts.single().subject) + assertEquals(FakeTelephony.SUB_ID_SIM_1, telephony.mmsSends.single().subId) + assertEquals(emptyList(), telephony.smsSends) + } + + @Test + fun simPickedAtSendOverridesTheConversationSim() { + val conversationId = world.createConversation( + recipients = listOf(RECIPIENT_A), + selfSubId = FakeTelephony.SUB_ID_SIM_1, + ) + + driver.sendSmsDraft( + conversationId = conversationId, + text = SHORT_TEXT, + requestedSubId = FakeTelephony.SUB_ID_SIM_2, + ) + + assertSentOnSim(conversationId = conversationId, subId = FakeTelephony.SUB_ID_SIM_2) + } + + @Test + fun draftSimIsUsedWhenNoSimIsPickedAtSend() { + val conversationId = world.createConversation( + recipients = listOf(RECIPIENT_A), + selfSubId = FakeTelephony.SUB_ID_SIM_1, + ) + + driver.sendSmsDraft( + conversationId = conversationId, + text = SHORT_TEXT, + draftSelfSubId = FakeTelephony.SUB_ID_SIM_2, + ) + + assertSentOnSim(conversationId = conversationId, subId = FakeTelephony.SUB_ID_SIM_2) + } + + @Test + fun conversationSimIsUsedWhenTheDraftHasNoSim() { + val conversationId = world.createConversation( + recipients = listOf(RECIPIENT_A), + selfSubId = FakeTelephony.SUB_ID_SIM_2, + ) + + driver.sendSmsDraft(conversationId = conversationId, text = SHORT_TEXT) + + assertSentOnSim(conversationId = conversationId, subId = FakeTelephony.SUB_ID_SIM_2) + } + + @Test + fun conversationWithoutSimFollowsTheSystemDefaultSmsSim() { + telephony.defaultSmsSubscriptionId = FakeTelephony.SUB_ID_SIM_2 + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + + driver.sendSmsDraft(conversationId = conversationId, text = SHORT_TEXT) + + assertSentOnSim(conversationId = conversationId, subId = FakeTelephony.SUB_ID_SIM_2) + } + + private fun assertSentOnSim(conversationId: String, subId: Int) { + val message = world.messagesIn(conversationId = conversationId).single() + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, message.status) + assertEquals(world.selfIdFor(subId = subId), message.selfId) + assertEquals(subId, telephony.smsInserts.single().subId) + assertEquals(subId, telephony.smsSends.single().subId) + } + + private companion object { + private const val SUBJECT = "subject" + private const val MILLIS_PER_SECOND = 1_000L + } +} diff --git a/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineActionRunner.kt b/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineActionRunner.kt new file mode 100644 index 000000000..4319292df --- /dev/null +++ b/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineActionRunner.kt @@ -0,0 +1,149 @@ +package com.android.messaging.datamodel.action + +import android.os.Bundle +import android.os.Parcel + +internal data class ScheduledAlarm( + val requestCode: Int, + val delayMillis: Long, + val action: Action, +) + +/** + * Stands in for the ActionService and BackgroundWorkerService process boundary: every action + * crosses it as a parcel, as it does through the real intents, and alarms wait until fired. + */ +internal class RecordingActionService : ActionService() { + + private val startedActions = ArrayDeque() + private val pendingAlarms = LinkedHashMap() + + @Synchronized + override fun startAction(action: Action) { + action.markStart() + startedActions.addLast(action.parcelRoundTrip()) + } + + @Synchronized + override fun scheduleAction(action: Action, code: Int, delayMs: Long) { + when (delayMs) { + Long.MAX_VALUE -> pendingAlarms.remove(code) + else -> pendingAlarms[code] = ScheduledAlarm( + requestCode = code, + delayMillis = delayMs, + action = action.parcelRoundTrip(), + ) + } + } + + @Synchronized + fun pollStartedAction(): Action? { + return startedActions.removeFirstOrNull() + } + + @Synchronized + fun pendingAlarm(requestCode: Int): ScheduledAlarm? { + return pendingAlarms[requestCode] + } + + @Synchronized + fun pendingAlarms(): List { + return pendingAlarms.values.toList() + } + + @Synchronized + fun fireAlarm(requestCode: Int) { + val alarm = requireNotNull(pendingAlarms.remove(requestCode)) { + "No alarm is scheduled for request code $requestCode" + } + startAction(alarm.action) + } +} + +internal class CapturingBackgroundWorker : BackgroundWorker() { + + private val queuedActions = ArrayDeque() + + @Synchronized + override fun queueBackgroundWork(backgroundActions: List) { + backgroundActions.forEach { action -> + queuedActions.addLast(action.parcelRoundTrip()) + } + } + + @Synchronized + fun pollQueuedAction(): Action? { + return queuedActions.removeFirstOrNull() + } +} + +/** + * Runs actions the way ActionServiceImpl and BackgroundWorkerService do, one at a time, started + * actions first. Must be called on a thread that may touch the database. + */ +internal class OutgoingPipelineActionRunner( + private val actionService: RecordingActionService, + private val backgroundWorker: CapturingBackgroundWorker, +) { + + fun runUntilIdle() { + var steps = 0 + while (runNextStep()) { + steps++ + check(steps < MAX_STEPS) { "Actions did not settle after $MAX_STEPS steps" } + } + } + + private fun runNextStep(): Boolean { + val startedAction = actionService.pollStartedAction() + val backgroundAction = when (startedAction) { + null -> backgroundWorker.pollQueuedAction() + else -> null + } + when { + startedAction != null -> executeStartedAction(action = startedAction) + backgroundAction != null -> executeBackgroundAction(action = backgroundAction) + } + return startedAction != null || backgroundAction != null + } + + private fun executeStartedAction(action: Action) { + action.markBeginExecute() + val result = action.executeAction() + action.markEndExecute(result) + action.sendBackgroundActions(backgroundWorker) + } + + private fun executeBackgroundAction(action: Action) { + action.markBackgroundWorkStarting() + val response: Result = runCatching { action.doBackgroundWork() } + action.markBackgroundCompletionQueued() + val deliveredAction = action.parcelRoundTrip() + response + .onSuccess { bundle -> deliveredAction.processBackgroundWorkResponse(bundle) } + .onFailure { throwable -> + if (throwable !is Exception) { + throw throwable + } + deliveredAction.processBackgroundWorkFailure() + } + deliveredAction.sendBackgroundActions(backgroundWorker) + } + + private companion object { + private const val MAX_STEPS = 500 + } +} + +internal fun Action.parcelRoundTrip(): Action { + val parcel = Parcel.obtain() + try { + parcel.writeParcelable(this, 0) + parcel.setDataPosition(0) + return requireNotNull( + parcel.readParcelable(Action::class.java.classLoader, Action::class.java), + ) + } finally { + parcel.recycle() + } +} diff --git a/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineDriver.kt b/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineDriver.kt new file mode 100644 index 000000000..66466678e --- /dev/null +++ b/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineDriver.kt @@ -0,0 +1,156 @@ +package com.android.messaging.datamodel.action + +import android.os.Bundle +import android.telephony.SmsManager +import com.android.messaging.datamodel.MmsFileProvider +import com.android.messaging.datamodel.data.MessageData + +/** + * What a user, the platform and the process lifecycle do to the outgoing pipeline. The cases in + * the *ActionTest classes go through this interface only, so they can run against a replacement + * of the legacy actions. + */ +internal interface OutgoingPipelineDriver { + + fun sendSmsDraft( + conversationId: String, + text: String, + draftSelfSubId: Int? = null, + requestedSubId: Int? = null, + ) + + fun sendMmsDraft(conversationId: String, text: String, draftSelfSubId: Int? = null) + + fun sendToRecipients(subId: Int, recipients: List, text: String, subject: String?) + + fun resend(messageId: String) + + fun processPendingMessages() + + fun restartProcess() + + fun fireRetryAlarm(subId: Int) + + fun pendingRetryDelayMillis(subId: Int): Long? + + fun deliverMmsSentResult( + resultCode: Int, + httpStatus: Int = 0, + withSendConfirmation: Boolean = true, + ) +} + +internal class LegacyOutgoingPipelineDriver( + private val world: OutgoingPipelineWorld, +) : OutgoingPipelineDriver { + + override fun sendSmsDraft( + conversationId: String, + text: String, + draftSelfSubId: Int?, + requestedSubId: Int?, + ) { + val draft = MessageData.createDraftSmsMessage( + conversationId, + draftSelfSubId?.let { subId -> world.selfIdFor(subId = subId) }, + text, + ) + runAndSettle { + when (requestedSubId) { + null -> InsertNewMessageAction.insertNewMessage(draft) + else -> InsertNewMessageAction.insertNewMessage(draft, requestedSubId) + } + } + } + + override fun sendMmsDraft(conversationId: String, text: String, draftSelfSubId: Int?) { + val draft = MessageData.createDraftMmsMessage( + conversationId, + draftSelfSubId?.let { subId -> world.selfIdFor(subId = subId) }, + text, + null, + ) + runAndSettle { InsertNewMessageAction.insertNewMessage(draft) } + } + + override fun sendToRecipients( + subId: Int, + recipients: List, + text: String, + subject: String?, + ) { + runAndSettle { + InsertNewMessageAction.insertNewMessage( + subId, + recipients.joinToString(separator = ","), + text, + subject, + ) + } + } + + override fun resend(messageId: String) { + runAndSettle { ResendMessageAction.resendMessage(messageId) } + } + + override fun processPendingMessages() { + runAndSettle { ProcessPendingMessagesAction.processFirstPendingMessage() } + } + + override fun restartProcess() { + runAndSettle { + FixupMessageStatusOnStartupAction.fixupMessageStatus() + ProcessPendingMessagesAction.processFirstPendingMessage() + } + } + + override fun fireRetryAlarm(subId: Int) { + runAndSettle { + world.actionService.fireAlarm(requestCode = retryRequestCode(subId = subId)) + } + } + + override fun pendingRetryDelayMillis(subId: Int): Long? { + return world.actionService.pendingAlarm(requestCode = retryRequestCode(subId = subId)) + ?.delayMillis + } + + override fun deliverMmsSentResult( + resultCode: Int, + httpStatus: Int, + withSendConfirmation: Boolean, + ) { + val send = requireNotNull(world.telephony.mmsSends.lastOrNull()) { + "No MMS was handed to the platform" + } + runAndSettle { + val extras = Bundle(send.sentIntentExtras).apply { + putParcelable(SendMessageAction.EXTRA_CONTENT_URI, MmsFileProvider.buildRawMmsUri()) + putBoolean(SendMessageAction.EXTRA_RESPONSE_IMPORTANT, true) + putInt(SmsManager.EXTRA_MMS_HTTP_STATUS, httpStatus) + if (withSendConfirmation) { + putByteArray( + SmsManager.EXTRA_MMS_DATA, + FakeTelephony.SEND_CONF_RESPONSE.copyOf(), + ) + } + } + ProcessSentMessageAction.processMmsSent(resultCode, send.messageUri, extras) + } + } + + private fun runAndSettle(trigger: () -> Unit) { + world.onWorker { + trigger() + world.runner.runUntilIdle() + } + } + + private fun retryRequestCode(subId: Int): Int { + return RETRY_REQUEST_CODE_BASE + subId + } + + private companion object { + private const val RETRY_REQUEST_CODE_BASE = 103 + } +} diff --git a/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineTelephony.kt b/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineTelephony.kt new file mode 100644 index 000000000..cf679be8e --- /dev/null +++ b/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineTelephony.kt @@ -0,0 +1,382 @@ +package com.android.messaging.datamodel.action + +import android.app.Activity +import android.app.PendingIntent +import android.content.Context +import android.net.Uri +import android.os.Bundle +import android.telephony.PhoneNumberUtils +import android.telephony.SmsManager +import android.telephony.SubscriptionInfo +import com.android.messaging.datamodel.BugleNotifications +import com.android.messaging.datamodel.DataModel +import com.android.messaging.datamodel.DatabaseHelper +import com.android.messaging.datamodel.DatabaseHelper.MessageColumns +import com.android.messaging.datamodel.ParticipantRefresh +import com.android.messaging.datamodel.data.MessageData +import com.android.messaging.mmslib.pdu.SendConf +import com.android.messaging.receiver.SendStatusReceiver +import com.android.messaging.sms.MmsConfig +import com.android.messaging.sms.MmsSender +import com.android.messaging.sms.MmsUtils +import com.android.messaging.sms.SmsSender +import com.android.messaging.util.PhoneUtils +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkStatic +import org.robolectric.Shadows.shadowOf +import org.robolectric.shadows.ShadowSubscriptionManager + +internal data class TelephonySmsInsert( + val uri: Uri, + val subId: Int, + val address: String, + val text: String, + val timestamp: Long, + val status: Int, + val type: Int, + val threadId: Long, +) + +internal data class TelephonyStatusUpdate( + val uri: Uri, + val typeOrBox: Int, + val timestamp: Long, +) + +internal data class TelephonyMmsInsert( + val uri: Uri, + val recipients: List, + val subId: Int, + val text: String?, + val subject: String?, + val timestamp: Long, +) + +internal data class PlatformSmsSend( + val destination: String, + val parts: List, + val partIds: List, + val subId: Int, + val messageUri: Uri, + val localStatusAtSend: Int?, +) + +internal data class PlatformMmsSend( + val subId: Int, + val messageUri: Uri, + val sentIntentExtras: Bundle, + val localStatusAtSend: Int?, +) + +/** + * Fakes the telephony provider and the radio below MmsUtils, SmsSender and MmsSender. SMS part + * results are delivered through SmsSender.setResult, as SendStatusReceiver does; MMS results + * arrive only when a test delivers them. + */ +internal class FakeTelephony { + + val smsInserts: MutableList = mutableListOf() + val smsStatusUpdates: MutableList = mutableListOf() + val mmsInserts: MutableList = mutableListOf() + val mmsStatusUpdates: MutableList = mutableListOf() + val smsSends: MutableList = mutableListOf() + val mmsSends: MutableList = mutableListOf() + val emergencyNotifications: MutableList = mutableListOf() + val errorNotificationUpdates: MutableList = mutableListOf() + + var isDefaultSmsApp: Boolean = true + var defaultSmsSubscriptionId: Int = SUB_ID_SIM_1 + var activeSubscriptionIds: List = listOf(SUB_ID_SIM_1, SUB_ID_SIM_2) + var failMmsInsert: Boolean = false + var mmsSendConfStatus: Int = MmsUtils.MMS_REQUEST_SUCCEEDED + + val phoneUtils: PhoneUtils = mockk(relaxed = true) + + private val smsManager: SmsManager = mockk(relaxed = true) + private val scriptedSmsResults = ArrayDeque>() + private val scriptedMmsOutcomes = ArrayDeque() + private val threadIds = mutableMapOf, Long>() + private var nextRowId = FIRST_TELEPHONY_ROW_ID + + init { + every { phoneUtils.getCanonicalBySimLocale(any()) } answers { firstArg() } + every { phoneUtils.formatForDisplay(any()) } answers { firstArg() } + every { phoneUtils.isDefaultSmsApp } answers { isDefaultSmsApp } + every { phoneUtils.defaultSmsSubscriptionId } answers { defaultSmsSubscriptionId } + every { phoneUtils.activeSubscriptionInfoList } answers { buildSubscriptionInfos() } + every { phoneUtils.getEffectiveSubId(any()) } answers { firstArg() } + every { phoneUtils.smsManager } returns smsManager + every { smsManager.divideMessage(any()) } answers { + ArrayList(firstArg().chunked(SMS_SEGMENT_LENGTH)) + } + every { + smsManager.sendMultipartTextMessage( + any(), + any(), + any>(), + any>(), + any>(), + ) + } answers { + onSmsSent( + destination = firstArg(), + parts = thirdArg(), + sentIntents = arg(3), + ) + } + } + + fun install() { + mockkStatic(MmsUtils::class) + mockkStatic(MmsConfig::class) + mockkStatic(MmsSender::class) + mockkStatic(PhoneNumberUtils::class) + mockkStatic(BugleNotifications::class) + mockkStatic(BugleActionToasts::class) + mockkStatic(ParticipantRefresh::class) + installMmsUtils() + installSupportingStatics() + } + + fun scriptSmsPartResults(vararg resultCodes: Int) { + synchronized(this) { scriptedSmsResults.addLast(resultCodes.toList()) } + } + + fun scriptMmsSendOutcome(outcome: MmsUtils.StatusPlusUri) { + synchronized(this) { scriptedMmsOutcomes.addLast(outcome) } + } + + fun threadIdFor(recipients: List): Long { + return synchronized(this) { + threadIds.getOrPut(recipients.sorted()) { FIRST_THREAD_ID + threadIds.size } + } + } + + fun allocateSmsUri(): Uri { + return nextUri(authority = "sms") + } + + private fun installMmsUtils() { + every { MmsUtils.getOrCreateThreadId(any(), any>()) } answers { + threadIdFor(recipients = secondArg()) + } + every { MmsUtils.getOrCreateSmsThreadId(any(), any()) } answers { + threadIdFor(recipients = listOf(secondArg())) + } + every { + MmsUtils.insertSmsMessage(any(), any(), any(), any(), any(), any(), any(), any(), any()) + } answers { recordSmsInsert(arguments = args) } + every { MmsUtils.updateSmsMessageSendingStatus(any(), any(), any(), any()) } answers { + smsStatusUpdates += TelephonyStatusUpdate( + uri = secondArg(), + typeOrBox = thirdArg(), + timestamp = arg(3), + ) + true + } + every { MmsUtils.updateMmsMessageSendingStatus(any(), any(), any(), any()) } answers { + mmsStatusUpdates += TelephonyStatusUpdate( + uri = secondArg(), + typeOrBox = thirdArg(), + timestamp = arg(3), + ) + true + } + every { MmsUtils.isDeliveryReportRequired(any()) } returns false + every { + MmsUtils.insertSendingMmsMessage(any(), any(), any(), any(), any(), any()) + } answers { recordMmsInsert(arguments = args) } + every { MmsUtils.sendMmsMessage(any(), any(), any(), any()) } answers { + recordMmsSend(subId = secondArg(), messageUri = thirdArg(), extras = arg(3)) + } + every { MmsUtils.readSendingMmsMessage(any(), any(), any(), any()) } answers { + readSendingMms( + messageUri = firstArg(), + conversationId = secondArg(), + participantId = thirdArg(), + selfId = arg(3), + ) + } + every { MmsUtils.updateSentMmsMessageStatus(any(), any(), any()) } answers { + MmsUtils.StatusPlusUri(mmsSendConfStatus, MMS_RESPONSE_STATUS_OK, secondArg()) + } + } + + private fun installSupportingStatics() { + val mmsConfig = mockk(relaxed = true) + every { mmsConfig.emailGateway } returns "" + every { mmsConfig.sendMultipartSmsAsSeparateMessages } returns false + every { mmsConfig.maxMessageSize } returns MAX_MMS_SIZE_BYTES + every { MmsConfig.get(any()) } returns mmsConfig + val sendConf = mockk(relaxed = true) + every { MmsSender.parseSendConf(any(), any()) } answers { + when { + firstArg() contentEquals SEND_CONF_RESPONSE -> sendConf + else -> null + } + } + every { PhoneNumberUtils.isEmergencyNumber(any()) } answers { + firstArg() == EMERGENCY_NUMBER + } + every { BugleNotifications.notifyEmergencySmsFailed(any(), any()) } answers { + emergencyNotifications += firstArg() + } + every { BugleNotifications.update(any()) } answers { + errorNotificationUpdates += firstArg() + } + every { + BugleActionToasts.onSendMessageOrManualDownloadActionCompleted( + any(), + any(), + any(), + any(), + any(), + any(), + ) + } returns Unit + every { ParticipantRefresh.refreshParticipant(any(), any()) } returns false + } + + private fun recordSmsInsert(arguments: List): Uri { + val uri = nextUri(authority = "sms") + smsInserts += TelephonySmsInsert( + uri = uri, + subId = arguments[2] as Int, + address = arguments[3] as String, + text = arguments[4] as String, + timestamp = arguments[5] as Long, + status = arguments[6] as Int, + type = arguments[7] as Int, + threadId = arguments[8] as Long, + ) + return uri + } + + private fun recordMmsInsert(arguments: List): Uri? { + val message = arguments[2] as MessageData + val uri = when { + failMmsInsert -> null + else -> nextUri(authority = "mms") + } + uri?.let { insertedUri -> + @Suppress("UNCHECKED_CAST") + mmsInserts += TelephonyMmsInsert( + uri = insertedUri, + recipients = (arguments[1] as List).toList(), + subId = arguments[3] as Int, + text = message.messageText, + subject = message.mmsSubject, + timestamp = arguments[5] as Long, + ) + } + return uri + } + + private fun recordMmsSend(subId: Int, messageUri: Uri, extras: Bundle): MmsUtils.StatusPlusUri { + val outcome = synchronized(this) { scriptedMmsOutcomes.removeFirstOrNull() } + val sentIntentExtras = Bundle(extras).apply { + putInt(SendMessageAction.KEY_SUB_ID, subId) + } + mmsSends += PlatformMmsSend( + subId = subId, + messageUri = messageUri, + sentIntentExtras = sentIntentExtras, + localStatusAtSend = localStatusOf(messageUri = messageUri), + ) + return outcome ?: MmsUtils.STATUS_PENDING + } + + private fun readSendingMms( + messageUri: Uri, + conversationId: String, + participantId: String?, + selfId: String, + ): MessageData? { + val inserted = mmsInserts.lastOrNull { insert -> insert.uri == messageUri } + return inserted?.let { insert -> + MessageData.createDraftMmsMessage(conversationId, selfId, insert.text, insert.subject) + .apply { + bindParticipantId(participantId) + updateSendingMessage(conversationId, messageUri, insert.timestamp) + } + } + } + + private fun onSmsSent( + destination: String, + parts: ArrayList, + sentIntents: ArrayList, + ) { + val sentBroadcasts = sentIntents.map { pendingIntent -> + shadowOf(pendingIntent).savedIntent + } + val messageUri = requireNotNull(sentBroadcasts.first().data) + val subId = sentBroadcasts.first().getIntExtra(SendStatusReceiver.EXTRA_SUB_ID, -1) + val partIds = sentBroadcasts.map { intent -> + intent.getIntExtra(SendStatusReceiver.EXTRA_PART_ID, -1) + } + smsSends += PlatformSmsSend( + destination = destination, + parts = parts.toList(), + partIds = partIds, + subId = subId, + messageUri = messageUri, + localStatusAtSend = localStatusOf(messageUri = messageUri), + ) + val resultCodes = synchronized(this) { scriptedSmsResults.removeFirstOrNull() } + ?: List(parts.size) { Activity.RESULT_OK } + partIds.forEachIndexed { index, partId -> + SmsSender.setResult( + messageUri, + resultCodes[index], + SendStatusReceiver.NO_ERROR_CODE, + partId, + subId, + ) + } + } + + private fun localStatusOf(messageUri: Uri): Int? { + return DataModel.get().database.query( + DatabaseHelper.MESSAGES_TABLE, + arrayOf(MessageColumns.STATUS), + "${MessageColumns.SMS_MESSAGE_URI} = ?", + arrayOf(messageUri.toString()), + null, + null, + null, + ).use { cursor -> + when { + cursor.moveToFirst() -> cursor.getInt(0) + else -> null + } + } + } + + private fun buildSubscriptionInfos(): List { + return activeSubscriptionIds.mapIndexed { slot, subId -> + ShadowSubscriptionManager.SubscriptionInfoBuilder.newBuilder() + .setId(subId) + .setSimSlotIndex(slot) + .buildSubscriptionInfo() + } + } + + private fun nextUri(authority: String): Uri { + val rowId = synchronized(this) { nextRowId++ } + return Uri.parse("content://$authority/$rowId") + } + + companion object { + const val SUB_ID_SIM_1 = 1 + const val SUB_ID_SIM_2 = 2 + const val EMERGENCY_NUMBER = "911" + const val SMS_SEGMENT_LENGTH = 160 + const val MAX_MMS_SIZE_BYTES = 300 * 1024 + val SEND_CONF_RESPONSE: ByteArray = byteArrayOf(0x8C.toByte(), 0x81.toByte()) + private const val MMS_RESPONSE_STATUS_OK = 0x80 + private const val FIRST_THREAD_ID = 500L + private const val FIRST_TELEPHONY_ROW_ID = 9_000L + } +} diff --git a/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineTestBase.kt b/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineTestBase.kt new file mode 100644 index 000000000..326dec2d5 --- /dev/null +++ b/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineTestBase.kt @@ -0,0 +1,44 @@ +package com.android.messaging.datamodel.action + +import org.junit.After +import org.junit.Before +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(application = OutgoingPipelineTestApplication::class, sdk = [36]) +abstract class OutgoingPipelineTestBase { + + internal val world = OutgoingPipelineWorld() + internal val telephony = world.telephony + internal val driver: OutgoingPipelineDriver = LegacyOutgoingPipelineDriver(world = world) + + @Before + fun setUpWorld() { + world.setUp() + } + + @After + fun tearDownWorld() { + world.tearDown() + } + + internal fun now(): Long { + return System.currentTimeMillis() + } + + internal fun statusOf(messageId: String): Int { + return world.message(messageId = messageId).status + } + + companion object { + internal const val RECIPIENT_A = "+15550100001" + internal const val RECIPIENT_B = "+15550100002" + internal const val RECIPIENT_C = "+15550100003" + internal const val SHORT_TEXT = "hello" + internal const val RETRY_REQUEST_DELAY_FIRST_MILLIS = 5_000L + internal const val RETRY_REQUEST_DELAY_SECOND_MILLIS = 10_000L + internal const val RESEND_WINDOW_MILLIS = 20 * 60 * 1_000L + } +} diff --git a/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineWorld.kt b/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineWorld.kt new file mode 100644 index 000000000..598ce17ad --- /dev/null +++ b/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingPipelineWorld.kt @@ -0,0 +1,355 @@ +package com.android.messaging.datamodel.action + +import android.content.Context +import android.net.Uri +import android.provider.BaseColumns +import androidx.core.content.contentValuesOf +import com.android.messaging.BugleApplication +import com.android.messaging.FactoryTestAccess +import com.android.messaging.datamodel.ActionSyncTestDataModel +import com.android.messaging.datamodel.BugleDatabaseOperations +import com.android.messaging.datamodel.DatabaseHelper +import com.android.messaging.datamodel.DatabaseHelper.MessageColumns +import com.android.messaging.datamodel.DatabaseHelper.ParticipantColumns +import com.android.messaging.datamodel.DatabaseWrapper +import com.android.messaging.datamodel.createInMemoryActionSyncTestDatabase +import com.android.messaging.datamodel.data.MessageData +import com.android.messaging.datamodel.data.ParticipantData +import com.android.messaging.testutil.FakeBuglePrefs +import com.android.messaging.testutil.createTestFactory +import com.android.messaging.util.BuglePrefsKeys +import io.mockk.every +import io.mockk.unmockkAll +import org.robolectric.RuntimeEnvironment +import org.robolectric.shadows.ShadowContentResolver + +internal class OutgoingPipelineTestApplication : BugleApplication() { + override fun onCreate() { + setTestsRunning() + } +} + +internal data class OutgoingMessageRow( + val id: String, + val conversationId: String, + val selfId: String, + val protocol: Int, + val status: Int, + val receivedTimestamp: Long, + val sentTimestamp: Long, + val retryStartTimestamp: Long, + val seen: Boolean, + val rawTelephonyStatus: Int, + val smsMessageUri: String?, +) + +private class PipelineTestDataModel( + private val actionService: ActionService, + private val backgroundWorker: BackgroundWorker, +) : ActionSyncTestDataModel() { + + override fun getActionService(): ActionService { + return actionService + } + + override fun getBackgroundWorkerForActionService(): BackgroundWorker { + return backgroundWorker + } +} + +/** + * The legacy outgoing pipeline's surroundings: an in-memory bugle_db with one self per SIM, the + * fake telephony layer, and an action service that only runs actions when asked to. + */ +internal class OutgoingPipelineWorld { + + val context: Context = RuntimeEnvironment.getApplication() + val telephony = FakeTelephony() + val actionService = RecordingActionService() + val backgroundWorker = CapturingBackgroundWorker() + val runner = OutgoingPipelineActionRunner( + actionService = actionService, + backgroundWorker = backgroundWorker, + ) + + private val prefsBySubId = mutableMapOf() + private val dataModel = PipelineTestDataModel( + actionService = actionService, + backgroundWorker = backgroundWorker, + ) + private lateinit var database: DatabaseWrapper + + fun setUp() { + telephony.install() + val factory = createTestFactory( + context = context, + dataModel = dataModel, + prefs = FakeBuglePrefs(), + phoneUtils = telephony.phoneUtils, + ) + every { factory.getSubscriptionPrefs(any()) } answers { prefsFor(subId = firstArg()) } + FactoryTestAccess.install(factory) + onWorker { + database = createInMemoryActionSyncTestDatabase(context) + dataModel.setDatabase(database) + clearParticipantCaches() + seedSelves() + } + } + + fun tearDown() { + ShadowContentResolver.reset() + FactoryTestAccess.reset() + unmockkAll() + } + + fun onWorker(block: () -> T): T { + var result: Result? = null + val worker = Thread( + { result = runCatching(block) }, + WORKER_THREAD_NAME, + ) + worker.start() + worker.join() + return requireNotNull(result).getOrThrow() + } + + fun prefsFor(subId: Int): FakeBuglePrefs { + return synchronized(prefsBySubId) { + prefsBySubId.getOrPut(subId) { FakeBuglePrefs(sharedPreferencesName = "sub_$subId") } + } + } + + fun pendingRetryAttempt(subId: Int): Int { + return prefsFor(subId = subId).getInt( + BuglePrefsKeys.PROCESS_PENDING_MESSAGES_RETRY_COUNT, + 0, + ) + } + + fun selfIdFor(subId: Int): String { + return requireNotNull(SELF_IDS[subId]) { "No self is seeded for subId $subId" } + } + + fun createConversation(recipients: List, selfSubId: Int? = null): String { + return onWorker { + val participants = ArrayList( + recipients.map { recipient -> + ParticipantData.getFromRawPhoneBySimLocale( + recipient, + FakeTelephony.SUB_ID_SIM_1, + ) + }, + ) + val conversationId = BugleDatabaseOperations.getOrCreateConversation( + database, + telephony.threadIdFor(recipients = recipients), + false, + participants, + false, + false, + null, + ) + selfSubId?.let { subId -> + inTransaction { + BugleDatabaseOperations.updateConversationSelfIdInTransaction( + database, + conversationId, + selfIdFor(subId = subId), + ) + } + } + conversationId + } + } + + fun seedOutgoingSms( + conversationId: String, + selfSubId: Int, + text: String, + status: Int, + receivedTimestamp: Long, + retryStartTimestamp: Long = receivedTimestamp, + ): String { + val message = MessageData.createDraftSmsMessage( + conversationId, + selfIdFor(subId = selfSubId), + text, + ) + return seedOutgoing( + message = message, + smsMessageUri = telephony.allocateSmsUri(), + status = status, + receivedTimestamp = receivedTimestamp, + retryStartTimestamp = retryStartTimestamp, + ) + } + + fun seedOutgoingMms( + conversationId: String, + selfSubId: Int, + text: String, + status: Int, + receivedTimestamp: Long, + retryStartTimestamp: Long = receivedTimestamp, + ): String { + val message = MessageData.createDraftMmsMessage( + conversationId, + selfIdFor(subId = selfSubId), + text, + null, + ) + return seedOutgoing( + message = message, + smsMessageUri = null, + status = status, + receivedTimestamp = receivedTimestamp, + retryStartTimestamp = retryStartTimestamp, + ) + } + + fun message(messageId: String): OutgoingMessageRow { + return requireNotNull( + queryMessages( + selection = "${BaseColumns._ID} = ?", + selectionArgs = arrayOf(messageId), + ).singleOrNull(), + ) { "Message $messageId is missing" } + } + + fun messagesIn(conversationId: String): List { + return queryMessages( + selection = "${MessageColumns.CONVERSATION_ID} = ?", + selectionArgs = arrayOf(conversationId), + ) + } + + fun allMessages(): List { + return queryMessages(selection = null, selectionArgs = null) + } + + fun conversationIdForThread(threadId: Long): String? { + return onWorker { + BugleDatabaseOperations.getExistingConversation(database, threadId, false) + } + } + + private fun seedOutgoing( + message: MessageData, + smsMessageUri: Uri?, + status: Int, + receivedTimestamp: Long, + retryStartTimestamp: Long, + ): String { + return onWorker { + message.updateSendingMessage(message.conversationId, smsMessageUri, receivedTimestamp) + inTransaction { + BugleDatabaseOperations.insertNewMessageInTransaction(database, message) + BugleDatabaseOperations.updateMessageRow( + database, + message.messageId, + contentValuesOf( + MessageColumns.STATUS to status, + MessageColumns.RETRY_START_TIMESTAMP to retryStartTimestamp, + ), + ) + } + message.messageId + } + } + + private fun queryMessages( + selection: String?, + selectionArgs: Array?, + ): List { + return onWorker { + database.query( + DatabaseHelper.MESSAGES_TABLE, + MESSAGE_COLUMNS, + selection, + selectionArgs, + null, + null, + "${MessageColumns.RECEIVED_TIMESTAMP} ASC, ${BaseColumns._ID} ASC", + ).use { cursor -> + buildList { + while (cursor.moveToNext()) { + add( + OutgoingMessageRow( + id = cursor.getString(0), + conversationId = cursor.getString(1), + selfId = cursor.getString(2), + protocol = cursor.getInt(3), + status = cursor.getInt(4), + receivedTimestamp = cursor.getLong(5), + sentTimestamp = cursor.getLong(6), + retryStartTimestamp = cursor.getLong(7), + seen = cursor.getInt(8) != 0, + rawTelephonyStatus = cursor.getInt(9), + smsMessageUri = cursor.getString(10), + ), + ) + } + } + } + } + } + + private fun seedSelves() { + SELF_IDS.forEach { (subId, selfId) -> + val values = ParticipantData.getSelfParticipant(subId).toContentValues().apply { + put(BaseColumns._ID, selfId.toLong()) + put(ParticipantColumns.SIM_SLOT_ID, SIM_SLOTS.getValue(subId)) + } + database.insert(DatabaseHelper.PARTICIPANTS_TABLE, null, values) + } + } + + private fun clearParticipantCaches() { + BugleDatabaseOperations.clearParticipantIdCache() + val cacheField = ParticipantData::class.java.getDeclaredField(PARTICIPANT_ID_CACHE_FIELD) + cacheField.isAccessible = true + (cacheField.get(null) as MutableMap<*, *>).clear() + } + + private fun inTransaction(block: () -> Unit) { + database.beginTransaction() + try { + block() + database.setTransactionSuccessful() + } finally { + database.endTransaction() + } + } + + companion object { + const val SUB_ID_INACTIVE_SIM = 3 + private const val WORKER_THREAD_NAME = "outgoing-pipeline-test-worker" + private const val PARTICIPANT_ID_CACHE_FIELD = "sSubIdtoParticipantIdCache" + private val SELF_IDS = linkedMapOf( + ParticipantData.DEFAULT_SELF_SUB_ID to "1", + FakeTelephony.SUB_ID_SIM_1 to "2", + FakeTelephony.SUB_ID_SIM_2 to "3", + SUB_ID_INACTIVE_SIM to "4", + ) + private val SIM_SLOTS = mapOf( + ParticipantData.DEFAULT_SELF_SUB_ID to ParticipantData.INVALID_SLOT_ID, + FakeTelephony.SUB_ID_SIM_1 to 0, + FakeTelephony.SUB_ID_SIM_2 to 1, + SUB_ID_INACTIVE_SIM to ParticipantData.INVALID_SLOT_ID, + ) + private val MESSAGE_COLUMNS = arrayOf( + BaseColumns._ID, + MessageColumns.CONVERSATION_ID, + MessageColumns.SELF_PARTICIPANT_ID, + MessageColumns.PROTOCOL, + MessageColumns.STATUS, + MessageColumns.RECEIVED_TIMESTAMP, + MessageColumns.SENT_TIMESTAMP, + MessageColumns.RETRY_START_TIMESTAMP, + MessageColumns.SEEN, + MessageColumns.RAW_TELEPHONY_STATUS, + MessageColumns.SMS_MESSAGE_URI, + ) + } +} diff --git a/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingProcessRestartTest.kt b/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingProcessRestartTest.kt new file mode 100644 index 000000000..b9bbe53a4 --- /dev/null +++ b/app/src/test/kotlin/com/android/messaging/datamodel/action/OutgoingProcessRestartTest.kt @@ -0,0 +1,71 @@ +package com.android.messaging.datamodel.action + +import com.android.messaging.datamodel.data.MessageData +import org.junit.Assert.assertEquals +import org.junit.Test + +class OutgoingProcessRestartTest : OutgoingPipelineTestBase() { + + @Test + fun messagesInFlightWhenTheProcessDiedFailAndQueuedOnesAreSent() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + val sending = seedSms( + conversationId = conversationId, + status = MessageData.BUGLE_STATUS_OUTGOING_SENDING, + receivedTimestamp = now() - 4_000, + ) + val resending = seedSms( + conversationId = conversationId, + status = MessageData.BUGLE_STATUS_OUTGOING_RESENDING, + receivedTimestamp = now() - 3_000, + ) + val queued = seedSms( + conversationId = conversationId, + status = MessageData.BUGLE_STATUS_OUTGOING_YET_TO_SEND, + receivedTimestamp = now() - 2_000, + ) + val retrying = seedSms( + conversationId = conversationId, + status = MessageData.BUGLE_STATUS_OUTGOING_AWAITING_RETRY, + receivedTimestamp = now() - 1_000, + selfSubId = FakeTelephony.SUB_ID_SIM_2, + ) + val sendingMms = world.seedOutgoingMms( + conversationId = conversationId, + selfSubId = FakeTelephony.SUB_ID_SIM_2, + text = SHORT_TEXT, + status = MessageData.BUGLE_STATUS_OUTGOING_SENDING, + receivedTimestamp = now() - 5_000, + ) + + driver.restartProcess() + + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_FAILED, statusOf(messageId = sending)) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_FAILED, statusOf(messageId = resending)) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_FAILED, statusOf(messageId = sendingMms)) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, statusOf(messageId = queued)) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, statusOf(messageId = retrying)) + assertEquals( + listOf(queued, retrying).map { messageId -> + requireNotNull(world.message(messageId = messageId).smsMessageUri) + }.sorted(), + telephony.smsSends.map { send -> send.messageUri.toString() }.sorted(), + ) + assertEquals(emptyList(), telephony.mmsSends) + } + + private fun seedSms( + conversationId: String, + status: Int, + receivedTimestamp: Long, + selfSubId: Int = FakeTelephony.SUB_ID_SIM_1, + ): String { + return world.seedOutgoingSms( + conversationId = conversationId, + selfSubId = selfSubId, + text = SHORT_TEXT, + status = status, + receivedTimestamp = receivedTimestamp, + ) + } +} diff --git a/app/src/test/kotlin/com/android/messaging/datamodel/action/ProcessPendingMessagesActionTest.kt b/app/src/test/kotlin/com/android/messaging/datamodel/action/ProcessPendingMessagesActionTest.kt new file mode 100644 index 000000000..826d3cf1f --- /dev/null +++ b/app/src/test/kotlin/com/android/messaging/datamodel/action/ProcessPendingMessagesActionTest.kt @@ -0,0 +1,190 @@ +package com.android.messaging.datamodel.action + +import com.android.messaging.datamodel.data.MessageData +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class ProcessPendingMessagesActionTest : OutgoingPipelineTestBase() { + + @Test + fun queuedMessagesAreSentOneAtATimeInReceivedOrder() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + val start = now() + val newest = seedSms(conversationId = conversationId, receivedTimestamp = start - 1_000) + val oldest = seedSms(conversationId = conversationId, receivedTimestamp = start - 3_000) + val middle = seedSms(conversationId = conversationId, receivedTimestamp = start - 2_000) + + driver.processPendingMessages() + + val expectedOrder = listOf(oldest, middle, newest) + assertEquals( + expectedOrder.map { messageId -> world.message(messageId = messageId).smsMessageUri }, + telephony.smsSends.map { send -> send.messageUri.toString() }, + ) + telephony.smsSends.forEach { send -> + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_SENDING, send.localStatusAtSend) + } + expectedOrder.forEach { messageId -> + assertEquals( + MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, + statusOf(messageId = messageId), + ) + } + } + + @Test + fun messageAlreadySendingBlocksTheQueueOfItsSim() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + val sending = seedSms( + conversationId = conversationId, + receivedTimestamp = now() - 2_000, + status = MessageData.BUGLE_STATUS_OUTGOING_SENDING, + ) + val queued = seedSms(conversationId = conversationId, receivedTimestamp = now() - 1_000) + + driver.processPendingMessages() + + assertEquals(emptyList(), telephony.smsSends) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_SENDING, statusOf(messageId = sending)) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_YET_TO_SEND, statusOf(messageId = queued)) + assertNull(driver.pendingRetryDelayMillis(subId = FakeTelephony.SUB_ID_SIM_1)) + } + + @Test + fun eachSimHasItsOwnQueue() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + seedSms( + conversationId = conversationId, + receivedTimestamp = now() - 3_000, + status = MessageData.BUGLE_STATUS_OUTGOING_SENDING, + ) + val blockedOnSim1 = seedSms( + conversationId = conversationId, + receivedTimestamp = now() - 2_000, + ) + val queuedOnSim2 = seedSms( + conversationId = conversationId, + receivedTimestamp = now() - 1_000, + selfSubId = FakeTelephony.SUB_ID_SIM_2, + ) + + driver.processPendingMessages() + + assertEquals( + MessageData.BUGLE_STATUS_OUTGOING_YET_TO_SEND, + statusOf(messageId = blockedOnSim1), + ) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, statusOf(messageId = queuedOnSim2)) + assertEquals(FakeTelephony.SUB_ID_SIM_2, telephony.smsSends.single().subId) + } + + @Test + fun messageOnASimTheSystemListsButWithoutASlotFailsWithoutBeingSent() { + telephony.activeSubscriptionIds = listOf( + FakeTelephony.SUB_ID_SIM_1, + FakeTelephony.SUB_ID_SIM_2, + OutgoingPipelineWorld.SUB_ID_INACTIVE_SIM, + ) + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + val queued = seedSms( + conversationId = conversationId, + receivedTimestamp = now() - 1_000, + selfSubId = OutgoingPipelineWorld.SUB_ID_INACTIVE_SIM, + ) + + driver.processPendingMessages() + + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_FAILED, statusOf(messageId = queued)) + assertEquals(emptyList(), telephony.smsSends) + } + + @Test + fun messageOnASimMissingFromTheSystemStaysQueued() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + val queued = seedSms( + conversationId = conversationId, + receivedTimestamp = now() - 1_000, + selfSubId = OutgoingPipelineWorld.SUB_ID_INACTIVE_SIM, + ) + + driver.processPendingMessages() + + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_YET_TO_SEND, statusOf(messageId = queued)) + assertEquals(emptyList(), telephony.smsSends) + assertNull( + driver.pendingRetryDelayMillis(subId = OutgoingPipelineWorld.SUB_ID_INACTIVE_SIM), + ) + } + + @Test + fun messageOutsideTheResendWindowFailsAndTheNextOneIsSent() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + val expired = seedSms( + conversationId = conversationId, + receivedTimestamp = now() - RESEND_WINDOW_MILLIS - 2_000, + status = MessageData.BUGLE_STATUS_OUTGOING_AWAITING_RETRY, + ) + val queued = seedSms(conversationId = conversationId, receivedTimestamp = now() - 1_000) + + driver.processPendingMessages() + + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_FAILED, statusOf(messageId = expired)) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, statusOf(messageId = queued)) + assertEquals( + world.message(messageId = queued).smsMessageUri, + telephony.smsSends.single().messageUri.toString(), + ) + } + + @Test + fun messageJustInsideTheResendWindowIsStillSent() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + val retrying = seedSms( + conversationId = conversationId, + receivedTimestamp = now() - RESEND_WINDOW_MILLIS + 60_000, + status = MessageData.BUGLE_STATUS_OUTGOING_AWAITING_RETRY, + ) + + driver.processPendingMessages() + + assertEquals( + MessageData.BUGLE_STATUS_OUTGOING_RESENDING, + telephony.smsSends.single().localStatusAtSend, + ) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, statusOf(messageId = retrying)) + } + + @Test + fun nothingIsSentWhileNotTheDefaultSmsAppAndARetryIsScheduled() { + telephony.isDefaultSmsApp = false + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + val queued = seedSms(conversationId = conversationId, receivedTimestamp = now() - 1_000) + + driver.processPendingMessages() + + assertEquals(emptyList(), telephony.smsSends) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_YET_TO_SEND, statusOf(messageId = queued)) + assertEquals( + RETRY_REQUEST_DELAY_FIRST_MILLIS, + driver.pendingRetryDelayMillis(subId = FakeTelephony.SUB_ID_SIM_1), + ) + assertNull(driver.pendingRetryDelayMillis(subId = FakeTelephony.SUB_ID_SIM_2)) + assertEquals(1, world.pendingRetryAttempt(subId = FakeTelephony.SUB_ID_SIM_1)) + } + + private fun seedSms( + conversationId: String, + receivedTimestamp: Long, + status: Int = MessageData.BUGLE_STATUS_OUTGOING_YET_TO_SEND, + selfSubId: Int = FakeTelephony.SUB_ID_SIM_1, + ): String { + return world.seedOutgoingSms( + conversationId = conversationId, + selfSubId = selfSubId, + text = SHORT_TEXT, + status = status, + receivedTimestamp = receivedTimestamp, + ) + } +} diff --git a/app/src/test/kotlin/com/android/messaging/datamodel/action/ResendMessageActionTest.kt b/app/src/test/kotlin/com/android/messaging/datamodel/action/ResendMessageActionTest.kt new file mode 100644 index 000000000..505fadbf0 --- /dev/null +++ b/app/src/test/kotlin/com/android/messaging/datamodel/action/ResendMessageActionTest.kt @@ -0,0 +1,105 @@ +package com.android.messaging.datamodel.action + +import com.android.messaging.datamodel.data.MessageData +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class ResendMessageActionTest : OutgoingPipelineTestBase() { + + @Test + fun failedSmsOlderThanTheResendWindowIsResentInANewWindow() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + val originalTimestamp = now() - RESEND_WINDOW_MILLIS - 5 * 60_000 + val messageId = seedSms( + conversationId = conversationId, + status = MessageData.BUGLE_STATUS_OUTGOING_FAILED, + receivedTimestamp = originalTimestamp, + ) + + driver.resend(messageId = messageId) + + val send = telephony.smsSends.single() + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_SENDING, send.localStatusAtSend) + val resent = world.message(messageId = messageId) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, resent.status) + assertTrue(resent.retryStartTimestamp > originalTimestamp) + assertTrue(resent.receivedTimestamp >= resent.retryStartTimestamp) + assertEquals(world.message(messageId = messageId).smsMessageUri, send.messageUri.toString()) + } + + @Test + fun resentMessageGoesAheadOfNewerQueuedMessages() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + val failed = seedSms( + conversationId = conversationId, + status = MessageData.BUGLE_STATUS_OUTGOING_FAILED, + receivedTimestamp = now() - 60_000, + ) + val queued = seedSms( + conversationId = conversationId, + status = MessageData.BUGLE_STATUS_OUTGOING_YET_TO_SEND, + receivedTimestamp = now() - 1_000, + ) + val failedUri = world.message(messageId = failed).smsMessageUri + val queuedUri = world.message(messageId = queued).smsMessageUri + + driver.resend(messageId = failed) + + assertEquals( + listOf(failedUri, queuedUri), + telephony.smsSends.map { send -> send.messageUri.toString() }, + ) + } + + @Test + fun onlyFailedMessagesCanBeResent() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + val statuses = listOf( + MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, + MessageData.BUGLE_STATUS_OUTGOING_FAILED_EMERGENCY_NUMBER, + MessageData.BUGLE_STATUS_OUTGOING_SENDING, + ) + val messageIds = statuses.mapIndexed { index, status -> + seedSms( + conversationId = conversationId, + status = status, + receivedTimestamp = now() - 10_000 + index, + ) + } + + messageIds.forEach { messageId -> driver.resend(messageId = messageId) } + + assertEquals(statuses, messageIds.map { messageId -> statusOf(messageId = messageId) }) + assertEquals(emptyList(), telephony.smsSends) + } + + @Test + fun failedMmsIsResentOnItsSim() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + val messageId = world.seedOutgoingMms( + conversationId = conversationId, + selfSubId = FakeTelephony.SUB_ID_SIM_2, + text = SHORT_TEXT, + status = MessageData.BUGLE_STATUS_OUTGOING_FAILED, + receivedTimestamp = now() - 60_000, + ) + + driver.resend(messageId = messageId) + + val send = telephony.mmsSends.single() + assertEquals(FakeTelephony.SUB_ID_SIM_2, send.subId) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_SENDING, send.localStatusAtSend) + assertEquals(0L, world.message(messageId = messageId).retryStartTimestamp % 1_000L) + } + + private fun seedSms(conversationId: String, status: Int, receivedTimestamp: Long): String { + return world.seedOutgoingSms( + conversationId = conversationId, + selfSubId = FakeTelephony.SUB_ID_SIM_1, + text = SHORT_TEXT, + status = status, + receivedTimestamp = receivedTimestamp, + ) + } +} diff --git a/app/src/test/kotlin/com/android/messaging/datamodel/action/SendMessageActionTest.kt b/app/src/test/kotlin/com/android/messaging/datamodel/action/SendMessageActionTest.kt new file mode 100644 index 000000000..fb969e891 --- /dev/null +++ b/app/src/test/kotlin/com/android/messaging/datamodel/action/SendMessageActionTest.kt @@ -0,0 +1,270 @@ +package com.android.messaging.datamodel.action + +import android.app.Activity +import android.provider.Telephony.Mms +import android.provider.Telephony.Sms +import android.telephony.SmsManager +import com.android.messaging.datamodel.BugleNotifications +import com.android.messaging.datamodel.data.MessageData +import com.android.messaging.sms.MmsUtils +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Test + +class SendMessageActionTest : OutgoingPipelineTestBase() { + + @Test + fun longSmsIsSentAsOneMultipartMessage() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + val text = "x".repeat(FakeTelephony.SMS_SEGMENT_LENGTH + 40) + + driver.sendSmsDraft(conversationId = conversationId, text = text) + + val send = telephony.smsSends.single() + assertEquals(text.chunked(FakeTelephony.SMS_SEGMENT_LENGTH), send.parts) + assertEquals(listOf(1, 2), send.partIds) + assertEquals( + MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, + world.messagesIn(conversationId = conversationId).single().status, + ) + } + + @Test + fun partFailingPermanentlyFailsTheWholeMultipartMessage() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + telephony.scriptSmsPartResults(Activity.RESULT_OK, SmsManager.RESULT_ERROR_GENERIC_FAILURE) + + driver.sendSmsDraft( + conversationId = conversationId, + text = "x".repeat(FakeTelephony.SMS_SEGMENT_LENGTH + 1), + ) + + assertEquals( + MessageData.BUGLE_STATUS_OUTGOING_FAILED, + world.messagesIn(conversationId = conversationId).single().status, + ) + } + + @Test + fun temporaryFailureWaitsForTheBackoffAlarmAndResends() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + telephony.scriptSmsPartResults(SmsManager.RESULT_ERROR_NO_SERVICE) + telephony.scriptSmsPartResults(SmsManager.RESULT_ERROR_NO_SERVICE) + + driver.sendSmsDraft(conversationId = conversationId, text = SHORT_TEXT) + + val messageId = world.messagesIn(conversationId = conversationId).single().id + val afterFirstFailure = world.message(messageId = messageId) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_AWAITING_RETRY, afterFirstFailure.status) + assertEquals(afterFirstFailure.receivedTimestamp, afterFirstFailure.retryStartTimestamp) + assertEquals(Sms.MESSAGE_TYPE_SENT, telephony.smsStatusUpdates.last().typeOrBox) + assertEquals(emptyList(), telephony.errorNotificationUpdates) + assertEquals( + RETRY_REQUEST_DELAY_FIRST_MILLIS, + driver.pendingRetryDelayMillis(subId = FakeTelephony.SUB_ID_SIM_1), + ) + assertEquals(1, world.pendingRetryAttempt(subId = FakeTelephony.SUB_ID_SIM_1)) + + driver.fireRetryAlarm(subId = FakeTelephony.SUB_ID_SIM_1) + + assertEquals( + MessageData.BUGLE_STATUS_OUTGOING_RESENDING, + telephony.smsSends.last().localStatusAtSend, + ) + assertEquals( + MessageData.BUGLE_STATUS_OUTGOING_AWAITING_RETRY, + statusOf(messageId = messageId), + ) + assertEquals( + RETRY_REQUEST_DELAY_SECOND_MILLIS, + driver.pendingRetryDelayMillis(subId = FakeTelephony.SUB_ID_SIM_1), + ) + assertEquals(2, world.pendingRetryAttempt(subId = FakeTelephony.SUB_ID_SIM_1)) + + driver.fireRetryAlarm(subId = FakeTelephony.SUB_ID_SIM_1) + + assertEquals(3, telephony.smsSends.size) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, statusOf(messageId = messageId)) + assertNull(driver.pendingRetryDelayMillis(subId = FakeTelephony.SUB_ID_SIM_1)) + assertEquals(0, world.pendingRetryAttempt(subId = FakeTelephony.SUB_ID_SIM_1)) + } + + @Test + fun permanentFailureMarksTheMessageFailedUnseenAndHoldsTheQueueUntilTheAlarm() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + val failing = world.seedOutgoingSms( + conversationId = conversationId, + selfSubId = FakeTelephony.SUB_ID_SIM_1, + text = SHORT_TEXT, + status = MessageData.BUGLE_STATUS_OUTGOING_YET_TO_SEND, + receivedTimestamp = now() - 2_000, + ) + val next = world.seedOutgoingSms( + conversationId = conversationId, + selfSubId = FakeTelephony.SUB_ID_SIM_1, + text = SHORT_TEXT, + status = MessageData.BUGLE_STATUS_OUTGOING_YET_TO_SEND, + receivedTimestamp = now() - 1_000, + ) + telephony.scriptSmsPartResults(SmsManager.RESULT_ERROR_GENERIC_FAILURE) + + driver.processPendingMessages() + + val failed = world.message(messageId = failing) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_FAILED, failed.status) + assertFalse(failed.seen) + assertEquals(Sms.MESSAGE_TYPE_FAILED, telephony.smsStatusUpdates.last().typeOrBox) + assertEquals(listOf(BugleNotifications.UPDATE_ERRORS), telephony.errorNotificationUpdates) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_YET_TO_SEND, statusOf(messageId = next)) + assertEquals(1, telephony.smsSends.size) + assertEquals( + RETRY_REQUEST_DELAY_FIRST_MILLIS, + driver.pendingRetryDelayMillis(subId = FakeTelephony.SUB_ID_SIM_1), + ) + + driver.fireRetryAlarm(subId = FakeTelephony.SUB_ID_SIM_1) + + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_COMPLETE, statusOf(messageId = next)) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_FAILED, statusOf(messageId = failing)) + } + + @Test + fun permanentFailureOfTheLastQueuedMessageSchedulesNoAlarm() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + telephony.scriptSmsPartResults(SmsManager.RESULT_ERROR_RADIO_OFF) + + driver.sendSmsDraft(conversationId = conversationId, text = SHORT_TEXT) + + assertEquals( + MessageData.BUGLE_STATUS_OUTGOING_FAILED, + world.messagesIn(conversationId = conversationId).single().status, + ) + assertNull(driver.pendingRetryDelayMillis(subId = FakeTelephony.SUB_ID_SIM_1)) + assertEquals(0, world.pendingRetryAttempt(subId = FakeTelephony.SUB_ID_SIM_1)) + } + + @Test + fun anyFailureToAnEmergencyNumberFailsAtOnceAndNotifies() { + val conversationId = world.createConversation( + recipients = listOf(FakeTelephony.EMERGENCY_NUMBER), + ) + telephony.scriptSmsPartResults(SmsManager.RESULT_ERROR_NO_SERVICE) + + driver.sendSmsDraft(conversationId = conversationId, text = SHORT_TEXT) + + val message = world.messagesIn(conversationId = conversationId).single() + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_FAILED_EMERGENCY_NUMBER, message.status) + assertEquals(listOf(FakeTelephony.EMERGENCY_NUMBER), telephony.emergencyNotifications) + assertEquals(listOf(BugleNotifications.UPDATE_ERRORS), telephony.errorNotificationUpdates) + assertEquals(Sms.MESSAGE_TYPE_FAILED, telephony.smsStatusUpdates.last().typeOrBox) + assertNull(driver.pendingRetryDelayMillis(subId = FakeTelephony.SUB_ID_SIM_1)) + } + + @Test + fun mmsThatCannotBeWrittenToTelephonyFailsWithoutBeingSent() { + telephony.failMmsInsert = true + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + + driver.sendMmsDraft(conversationId = conversationId, text = SHORT_TEXT) + + val message = world.messagesIn(conversationId = conversationId).single() + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_FAILED, message.status) + assertNull(message.smsMessageUri) + assertEquals(emptyList(), telephony.mmsSends) + } + + @Test + fun mmsRejectedBeforeReachingThePlatformFollowsTheReturnedStatus() { + telephony.scriptMmsSendOutcome( + MmsUtils.StatusPlusUri( + MmsUtils.MMS_REQUEST_AUTO_RETRY, + MessageData.RAW_TELEPHONY_STATUS_UNDEFINED, + null, + ), + ) + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + + driver.sendMmsDraft(conversationId = conversationId, text = SHORT_TEXT) + + val message = world.messagesIn(conversationId = conversationId).single() + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_AWAITING_RETRY, message.status) + assertEquals(telephony.mmsInserts.single().uri.toString(), message.smsMessageUri) + assertEquals( + RETRY_REQUEST_DELAY_FIRST_MILLIS, + driver.pendingRetryDelayMillis(subId = FakeTelephony.SUB_ID_SIM_1), + ) + } + + @Test + fun mmsIoErrorFromThePlatformIsRetried() { + val messageId = sendMmsAndDeliver(resultCode = SmsManager.MMS_ERROR_IO_ERROR) + + assertEquals( + MessageData.BUGLE_STATUS_OUTGOING_AWAITING_RETRY, + statusOf(messageId = messageId), + ) + assertEquals( + RETRY_REQUEST_DELAY_FIRST_MILLIS, + driver.pendingRetryDelayMillis(subId = FakeTelephony.SUB_ID_SIM_1), + ) + + driver.fireRetryAlarm(subId = FakeTelephony.SUB_ID_SIM_1) + + assertEquals(1, telephony.mmsInserts.size) + assertEquals( + MessageData.BUGLE_STATUS_OUTGOING_RESENDING, + telephony.mmsSends.last().localStatusAtSend, + ) + } + + @Test + fun mmsHttpNotFoundFromThePlatformFails() { + val messageId = sendMmsAndDeliver( + resultCode = SmsManager.MMS_ERROR_HTTP_FAILURE, + httpStatus = HTTP_NOT_FOUND, + ) + + val message = world.message(messageId = messageId) + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_FAILED, message.status) + assertFalse(message.seen) + assertEquals(Mms.MESSAGE_BOX_FAILED, telephony.mmsStatusUpdates.last().typeOrBox) + assertNull(driver.pendingRetryDelayMillis(subId = FakeTelephony.SUB_ID_SIM_1)) + } + + @Test + fun mmsRejectedByTheCarrierInTheSendConfirmationFails() { + telephony.mmsSendConfStatus = MmsUtils.MMS_REQUEST_MANUAL_RETRY + + val messageId = sendMmsAndDeliver(resultCode = Activity.RESULT_OK) + + assertEquals(MessageData.BUGLE_STATUS_OUTGOING_FAILED, statusOf(messageId = messageId)) + } + + @Test + fun mmsAcceptedByThePlatformWithoutASendConfirmationFails() { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + driver.sendMmsDraft(conversationId = conversationId, text = SHORT_TEXT) + + driver.deliverMmsSentResult( + resultCode = Activity.RESULT_OK, + withSendConfirmation = false, + ) + + assertEquals( + MessageData.BUGLE_STATUS_OUTGOING_FAILED, + world.messagesIn(conversationId = conversationId).single().status, + ) + } + + private fun sendMmsAndDeliver(resultCode: Int, httpStatus: Int = 0): String { + val conversationId = world.createConversation(recipients = listOf(RECIPIENT_A)) + driver.sendMmsDraft(conversationId = conversationId, text = SHORT_TEXT) + driver.deliverMmsSentResult(resultCode = resultCode, httpStatus = httpStatus) + return world.messagesIn(conversationId = conversationId).single().id + } + + private companion object { + private const val HTTP_NOT_FOUND = 404 + } +}