Send troubleshooting report with Never uploads a pending crash report

Aperta
#23,795 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
57/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
android, kotlin
Ambito
mobile, security

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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

Lingua principale
Kotlin
Stelle
12.3k
Fork
3.1k
Merge medio
2g 1h
PR unite (30g)
311

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di ankidroid/Anki-Android

Tutte le issue di ankidroid/Anki-Android

Issue simili

Altre issue su Kotlin

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.