Send troubleshooting report with Never uploads a pending crash report

Open
#23,795 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
57/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
android, kotlin
Domain
mobile, security

Research direction

Start with CrashReportService.sendReport and the consent handling in AnkiDroid/src/test/java/com/ichi2/anki/analytics/ManualCrashReportConsentTest.kt; the test describes how a report left pending from an earlier Ask session can be uploaded when reporting is set to Never. Trace how sending a troubleshooting report triggers ACRA startup processing, then add or adapt a regression test that verifies the pending report remains unapproved and is not scheduled for upload.

Written by the indexing model from the issue text.

Description

code-scan

Assisted-by: Claude Fable 5.2 max

[EXISTING] Send troubleshooting report with Never uploads a pending crash report
Subject: [EXISTING] Send troubleshooting report with Never uploads a pending crash report

With reporting set to Never, sending a troubleshooting report from Help approves and uploads an older crash report the user never agreed to send.

⚠️ This issue existed before the PR and should likely be split off into a separate issue. The PR extends it to non-default profiles, whose approved reports the sender could not reach before.

---
diff --git a/AnkiDroid/src/test/java/com/ichi2/anki/analytics/ManualCrashReportConsentTest.kt b/AnkiDroid/src/test/java/com/ichi2/anki/analytics/ManualCrashReportConsentTest.kt
new file mode 100644
index 0000000000..a7bbac47f2
--- /dev/null
+++ b/AnkiDroid/src/test/java/com/ichi2/anki/analytics/ManualCrashReportConsentTest.kt
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package com.ichi2.anki.analytics
+
+import android.app.Application
+import android.os.Looper
+import androidx.core.content.edit
+import androidx.core.content.pm.PackageInfoCompat
+import androidx.test.core.app.ApplicationProvider
+import com.ichi2.anki.AnkiActivity
+import com.ichi2.anki.acraCoreConfigBuilder
+import com.ichi2.anki.common.analytics.Analytics
+import com.ichi2.anki.common.crashreporting.CrashReportService
+import com.ichi2.anki.common.crashreporting.CrashReporter.Companion.FEEDBACK_REPORT_KEY
+import com.ichi2.anki.common.crashreporting.CrashReporter.Companion.FEEDBACK_REPORT_NEVER
+import com.ichi2.anki.common.preferences.sharedPrefs
+import com.ichi2.anki.initializeAcraCrashReporter
+import com.ichi2.testutils.EmptyApplication
+import com.ichi2.testutils.common.OS
+import io.mockk.every
+import io.mockk.mockk
+import io.mockk.mockkConstructor
+import io.mockk.mockkObject
+import io.mockk.mockkStatic
+import io.mockk.unmockkAll
+import io.mockk.verify
+import org.acra.ACRA
+import org.acra.ACRAConstants
+import org.acra.ErrorReporter
+import org.acra.ReportField
+import org.acra.config.CoreConfiguration
+import org.acra.config.CoreConfigurationBuilder
+import org.acra.data.CrashReportData
+import org.acra.file.CrashReportPersister
+import org.acra.file.ReportLocator
+import org.acra.interaction.ToastInteraction
+import org.acra.plugins.Plugin
+import org.acra.plugins.PluginLoader
+import org.acra.prefs.SharedPreferencesFactory
+import org.acra.scheduler.SchedulerStarter
+import org.acra.startup.StartupProcessor
+import org.acra.startup.StartupProcessorExecutor
+import org.junit.After
+import org.junit.Assume.assumeFalse
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.Robolectric
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.annotation.Config
+import java.io.File
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
+import kotlin.test.assertFalse
+import kotlin.test.assertTrue
+
+@RunWith(RobolectricTestRunner::class)
+@Config(application = EmptyApplication::class)
+class ManualCrashReportConsentTest {
+    private lateinit var application: Application
+    private val initCalls = mutableListOf<Pair<CoreConfigurationBuilder, Boolean>>()
+
+    @Before
+    fun setUp() {
+        assumeFalse("ACRA's report file names contain ':', which Windows doesn't allow", OS.WINDOWS.isRunning())
+        application = ApplicationProvider.getApplicationContext()
+        // Build AnkiDroid's real configuration without installing a process-wide crash handler.
+        mockkStatic(ACRA::class)
+        every { ACRA.init(any<Application>(), any<CoreConfigurationBuilder>(), any()) } answers {
+            initCalls += secondArg<CoreConfigurationBuilder>() to thirdArg<Boolean>()
+        }
+        every { ACRA.errorReporter } returns mockk<ErrorReporter>(relaxed = true)
+        mockkObject(Analytics)
+        every { Analytics.sendAnalyticsException(any(), any()) } returns Unit
+        with(application) { initializeAcraCrashReporter() }
+        // ToastInteraction always accepts; skip its private looper and display delay.
+        mockkConstructor(ToastInteraction::class)
+        every { anyConstructed<ToastInteraction>().performInteraction(any(), any(), any()) } returns true
+    }
+
+    @After
+    fun tearDown() {
+        unmockkAll()
+    }
+
+    @Test
+    fun `manual report with Never keeps a report awaiting consent`() {
+        application.sharedPrefs().edit(commit = true) { putString(FEEDBACK_REPORT_KEY, FEEDBACK_REPORT_NEVER) }
+        markCurrentVersion()
+        // Back/dismiss leaves a report from an earlier Ask session in the unapproved queue.
+        val report = pendingReport()
+        val scheduler = mockk<SchedulerStarter>(relaxed = true)
+
+        val earlierInitCalls = initCalls.size
+        CrashReportService.sendReport(Robolectric.buildActivity(AnkiActivity::class.java).get())
+        // Each ACRA.init checks the stored reports unless told not to.
+        for ((builder, checksReports) in initCalls.drop(earlierInitCalls)) {
+            if (checksReports) processReports(builder, scheduler)
+        }
+
+        verify(exactly = 0) { scheduler.scheduleReports(report, any()) }
+        assertTrue(report.exists(), "A report awaiting consent must remain pending")
+    }
+
+    private fun pendingReport(): File {
+        val timestamp = SimpleDateFormat(ACRAConstants.DATE_TIME_FORMAT_STRING, Locale.ENGLISH).format(Date(0))
+        val report = File(ReportLocator(application).unapprovedFolder, timestamp + ACRAConstants.REPORTFILE_EXTENSION)
+        val data =
+            CrashReportData().apply {
+                put(ReportField.FILE_PATH, application.filesDir.absolutePath)
+                put(ReportField.USER_CRASH_DATE, timestamp)
+                put(ReportField.APP_VERSION_CODE, appVersion())
+            }
+        CrashReportPersister().store(data, report)
+        return report
+    }
+
+    private fun markCurrentVersion() {
+        val config = CrashReportService.acraCoreConfigBuilder.build()
+        SharedPreferencesFactory(application, config).create().edit(commit = true) {
+            putLong(ACRA.PREF_LAST_VERSION_NR, appVersion())
+        }
+    }
+
+    private fun appVersion() = PackageInfoCompat.getLongVersionCode(application.packageManager.getPackageInfo(application.packageName, 0))
+
+    private fun processReports(
+        builder: CoreConfigurationBuilder,
+        scheduler: SchedulerStarter,
+    ) {
+        val loader = StartupThreadTracker(builder.build().pluginLoader)
+        val config = builder.withPluginLoader(loader).build()
+        StartupProcessorExecutor(application, config, scheduler).processReports(true)
+        shadowOf(Looper.getMainLooper()).idle()
+        assertTrue(loader.started.await(10, TimeUnit.SECONDS), "ACRA startup worker did not start")
+        loader.worker.join(10_000)
+        assertFalse(loader.worker.isAlive, "ACRA startup worker did not finish")
+    }
+
+    private class StartupThreadTracker(
+        private val delegate: PluginLoader,
+    ) : PluginLoader by delegate {
+        val started = CountDownLatch(1)
+        lateinit var worker: Thread
+
+        override fun <T : Plugin> loadEnabled(
+            config: CoreConfiguration,
+            clazz: Class<T>,
+        ): List<T> {
+            if (clazz == StartupProcessor::class.java) {
+                worker = Thread.currentThread()
+                started.countDown()
+            }
+            return delegate.loadEnabled(config, clazz)
+        }
+    }
+}

Found while reviewing https://github.com/ankidroid/Anki-Android/pull/23337

Dominant language
Kotlin
Stars
12.3k
Forks
3.1k
Avg merge
2d 1h
Merged PRs (30d)
311

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from ankidroid/Anki-Android

All issues in ankidroid/Anki-Android

Similar issues

More Kotlin issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.