forked from ankidroid/Anki-Android
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeckPickerTest.kt
More file actions
865 lines (788 loc) · 32.9 KB
/
DeckPickerTest.kt
File metadata and controls
865 lines (788 loc) · 32.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
// noinspection MissingCopyrightHeader #8659
package com.ichi2.anki
import android.annotation.SuppressLint
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.Menu
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.content.edit
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.view.children
import androidx.fragment.app.FragmentManager
import androidx.test.core.app.ActivityScenario
import app.cash.turbine.test
import com.ichi2.anki.common.annotations.NeedsTest
import com.ichi2.anki.common.time.TimeManager
import com.ichi2.anki.common.utils.annotation.KotlinCleanup
import com.ichi2.anki.dialogs.DatabaseErrorDialog
import com.ichi2.anki.dialogs.DatabaseErrorDialog.DatabaseErrorDialogType
import com.ichi2.anki.dialogs.DeckPickerContextMenu
import com.ichi2.anki.dialogs.DeckPickerContextMenu.DeckPickerContextMenuOption
import com.ichi2.anki.dialogs.utils.title
import com.ichi2.anki.exception.UnknownDatabaseVersionException
import com.ichi2.anki.libanki.DeckId
import com.ichi2.anki.libanki.Storage
import com.ichi2.anki.libanki.sched.Ease
import com.ichi2.anki.preferences.sharedPrefs
import com.ichi2.anki.settings.Prefs
import com.ichi2.anki.utils.Destination
import com.ichi2.anki.utils.ext.dismissAllDialogFragments
import com.ichi2.testutils.BackendEmulatingOpenConflict
import com.ichi2.testutils.BackupManagerTestUtilities
import com.ichi2.testutils.DbUtils
import com.ichi2.testutils.common.Flaky
import com.ichi2.testutils.common.OS
import com.ichi2.testutils.ext.addBasicNoteWithOp
import com.ichi2.testutils.ext.menu
import com.ichi2.testutils.grantWritePermissions
import com.ichi2.testutils.revokeWritePermissions
import com.ichi2.utils.ResourceLoader
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.containsInAnyOrder
import org.hamcrest.Matchers.containsString
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.not
import org.hamcrest.Matchers.notNullValue
import org.hamcrest.Matchers.nullValue
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.mock
import org.mockito.Mockito.never
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.kotlin.whenever
import org.robolectric.ParameterizedRobolectricTestRunner
import org.robolectric.Robolectric
import org.robolectric.RuntimeEnvironment
import org.robolectric.shadows.ShadowDialog
import org.robolectric.shadows.ShadowLooper
import timber.log.Timber
import java.io.File
import kotlin.test.assertFailsWith
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.seconds
@KotlinCleanup("SPMockBuilder")
@RunWith(ParameterizedRobolectricTestRunner::class)
class DeckPickerTest : RobolectricTest() {
@ParameterizedRobolectricTestRunner.Parameter
@JvmField // required for Parameter
var mQualifiers: String? = null
companion object {
@ParameterizedRobolectricTestRunner.Parameters
@JvmStatic // required for initParameters
fun initParameters(): Collection<String> = listOf("normal", "xlarge")
}
@Before
fun before() {
RuntimeEnvironment.setQualifiers(mQualifiers)
getPreferences().edit {
putBoolean(IntroductionActivity.INTRODUCTION_SLIDES_SHOWN, true)
}
}
@Test
@SuppressLint("UseKtx")
fun getPreviousVersionUpgradeFrom201to292() {
val newVersion = 20900302 // 2.9.2
val preferences = mock(SharedPreferences::class.java)
whenever(preferences.getLong(DeckPicker.UPGRADE_VERSION_KEY, newVersion.toLong()))
.thenThrow(ClassCastException::class.java)
whenever(preferences.getInt(DeckPicker.UPGRADE_VERSION_KEY, newVersion))
.thenThrow(ClassCastException::class.java)
whenever(preferences.getString(DeckPicker.UPGRADE_VERSION_KEY, ""))
.thenReturn("2.0.1")
val editor = mock(SharedPreferences.Editor::class.java)
whenever(preferences.edit()).thenReturn(editor)
val updated = mock(SharedPreferences.Editor::class.java)
whenever(editor.remove(DeckPicker.UPGRADE_VERSION_KEY)).thenReturn(updated)
ActivityScenario.launch(DeckPicker::class.java).use { scenario ->
scenario.onActivity { deckPicker: DeckPicker ->
val previousVersion =
deckPicker.getPreviousVersion(preferences, newVersion.toLong())
assertEquals(0, previousVersion)
}
}
verify(editor, times(1)).remove(DeckPicker.UPGRADE_VERSION_KEY)
verify(updated, times(1)).apply()
}
@Test
@SuppressLint("UseKtx")
fun getPreviousVersionUpgradeFrom202to292() {
val newVersion: Long = 20900302 // 2.9.2
val preferences = mock(SharedPreferences::class.java)
whenever(preferences.getLong(DeckPicker.UPGRADE_VERSION_KEY, newVersion))
.thenThrow(ClassCastException::class.java)
whenever(preferences.getInt(DeckPicker.UPGRADE_VERSION_KEY, 20900203))
.thenThrow(ClassCastException::class.java)
whenever(preferences.getString(DeckPicker.UPGRADE_VERSION_KEY, ""))
.thenReturn("2.0.2")
val editor = mock(SharedPreferences.Editor::class.java)
whenever(preferences.edit()).thenReturn(editor)
val updated = mock(SharedPreferences.Editor::class.java)
whenever(editor.remove(DeckPicker.UPGRADE_VERSION_KEY)).thenReturn(updated)
ActivityScenario.launch(DeckPicker::class.java).use { scenario ->
scenario.onActivity { deckPicker: DeckPicker ->
val previousVersion = deckPicker.getPreviousVersion(preferences, newVersion)
assertEquals(40, previousVersion)
}
}
verify(editor, times(1)).remove(DeckPicker.UPGRADE_VERSION_KEY)
verify(updated, times(1)).apply()
}
@Test
@SuppressLint("UseKtx")
fun getPreviousVersionUpgradeFrom281to291() {
val prevVersion = 20800301 // 2.8.1
val newVersion: Long = 20900301 // 2.9.1
val preferences = mock(SharedPreferences::class.java)
whenever(preferences.getLong(DeckPicker.UPGRADE_VERSION_KEY, newVersion))
.thenThrow(ClassCastException::class.java)
whenever(preferences.getInt(DeckPicker.UPGRADE_VERSION_KEY, 20900203))
.thenReturn(prevVersion)
val editor = mock(SharedPreferences.Editor::class.java)
whenever(preferences.edit()).thenReturn(editor)
val updated = mock(SharedPreferences.Editor::class.java)
whenever(editor.remove(DeckPicker.UPGRADE_VERSION_KEY)).thenReturn(updated)
ActivityScenario.launch(DeckPicker::class.java).use { scenario ->
scenario.onActivity { deckPicker: DeckPicker ->
val previousVersion = deckPicker.getPreviousVersion(preferences, newVersion)
assertEquals(prevVersion.toLong(), previousVersion)
}
}
verify(editor, times(1)).remove(DeckPicker.UPGRADE_VERSION_KEY)
verify(updated, times(1)).apply()
}
@Test
fun getPreviousVersionUpgradeFrom291to292() {
val prevVersion: Long = 20900301 // 2.9.1
val newVersion: Long = 20900302 // 2.9.2
val preferences = mock(SharedPreferences::class.java)
whenever(preferences.getLong(DeckPicker.UPGRADE_VERSION_KEY, newVersion))
.thenReturn(prevVersion)
val editor = mock(SharedPreferences.Editor::class.java)
whenever(preferences.edit()).thenReturn(editor)
ActivityScenario.launch(DeckPicker::class.java).use { scenario ->
scenario.onActivity { deckPicker: DeckPicker ->
val previousVersion = deckPicker.getPreviousVersion(preferences, newVersion)
assertEquals(prevVersion, previousVersion)
}
}
verify(editor, never()).remove(DeckPicker.UPGRADE_VERSION_KEY)
}
@Test
fun limitAppliedAfterReview() {
val sched = col.sched
val dconf = col.decks.getConfig(1)
assertNotNull(dconf)
dconf.new.perDay = 10
col.decks.save(dconf)
for (i in 0..10) {
addBasicNote("Which card is this ?", i.toString())
}
// This set a card as current card
sched.card
ensureCollectionLoadIsSynchronous()
val deckPicker =
super.startActivityNormallyOpenCollectionWithIntent(
DeckPicker::class.java,
Intent(),
)
assertEquals(
10,
deckPicker.dueTree!!
.children[0]
.newCount
.toLong(),
)
}
@Test
fun confirmDeckDeletionDeletesEmptyDeck() =
runTest {
val did = addDeck("Hello World")
assertThat("Deck was added", col.decks.count(), equalTo(2))
val deckPicker =
startActivityNormallyOpenCollectionWithIntent(
DeckPicker::class.java,
Intent(),
)
deckPicker.viewModel.deleteDeck(did).join()
assertThat("deck was deleted", col.decks.count(), equalTo(1))
}
@Test
fun databaseLockedTest() {
// don't call .onCreate
val deckPicker = Robolectric.buildActivity(DeckPickerEx::class.java, Intent()).get()
deckPicker.handleStartupFailure(InitialActivity.StartupFailure.DatabaseLocked)
assertThat(
deckPicker.databaseErrorDialog,
equalTo(DatabaseErrorDialogType.DIALOG_DB_LOCKED),
)
}
@Test
fun databaseLockedWithPermissionIntegrationTest() {
AnkiDroidApp.sentExceptionReportHack = false
try {
BackendEmulatingOpenConflict.enable()
InitialActivityWithConflictTest.setupForDatabaseConflict()
val d =
super.startActivityNormallyOpenCollectionWithIntent(
DeckPickerEx::class.java,
Intent(),
)
assertThat(
"A specific dialog for a conflict should be shown",
d.databaseErrorDialog,
equalTo(DatabaseErrorDialogType.DIALOG_DB_LOCKED),
)
assertThat(
"No exception reports should be thrown",
AnkiDroidApp.sentExceptionReportHack,
equalTo(false),
)
} finally {
BackendEmulatingOpenConflict.disable()
InitialActivityWithConflictTest.setupForDefault()
}
}
@Test
@RunInBackground
@Ignore("Flaky. Try to unflak when AsyncTask is entirely removed.")
fun databaseLockedNoPermissionIntegrationTest() {
// no permissions -> grant permissions -> db locked
try {
InitialActivityWithConflictTest.setupForDefault()
BackendEmulatingOpenConflict.enable()
val d =
super.startActivityNormallyOpenCollectionWithIntent(
DeckPickerEx::class.java,
Intent(),
)
// grant permissions
InitialActivityWithConflictTest.setupForDatabaseConflict()
d.onStoragePermissionGranted()
assertThat(
"A specific dialog for a conflict should be shown",
d.databaseErrorDialog,
equalTo(DatabaseErrorDialogType.DIALOG_DB_LOCKED),
)
} finally {
BackendEmulatingOpenConflict.disable()
InitialActivityWithConflictTest.setupForDefault()
}
}
@Test
fun deckPickerOpensWithHelpMakeAnkiDroidBetterDialog() {
// Refactor: It would be much better to use a spy - see if we can get this into Robolectric
try {
grantWritePermissions()
BackupManagerTestUtilities.setupSpaceForBackup(targetContext)
// We don't show it if the user is new.
targetContext
.sharedPrefs()
.edit { putString("lastVersion", "0.1") }
val d =
super.startActivityNormallyOpenCollectionWithIntent(
DeckPickerEx::class.java,
Intent(),
)
assertThat(
"Analytics opt-in should be displayed",
d.displayedAnalyticsOptIn,
equalTo(true),
)
} finally {
revokeWritePermissions()
BackupManagerTestUtilities.reset()
}
}
@Test
@RunInBackground
fun doNotShowOptionsMenuWhenCollectionInaccessible() =
runTest {
try {
enableNullCollection()
val d =
super.startActivityNormallyOpenCollectionWithIntent(
DeckPickerEx::class.java,
Intent(),
)
d.updateMenuState()
assertThat(
"Options menu not displayed when collection is inaccessible",
d.optionsMenuState,
equalTo(null),
)
} finally {
disableNullCollection()
}
}
@Test
fun showOptionsMenuWhenCollectionAccessible() =
runTest {
try {
grantWritePermissions()
val d =
super.startActivityNormallyOpenCollectionWithIntent(
DeckPickerEx::class.java,
Intent(),
)
d.updateMenuState()
assertThat(
"Options menu displayed when collection is accessible",
d.optionsMenuState,
notNullValue(),
)
} finally {
revokeWritePermissions()
}
}
@Test
@RunInBackground
fun onResumeLoadCollectionFailureWithInaccessibleCollection() {
try {
revokeWritePermissions()
enableNullCollection()
val d =
super.startActivityNormallyOpenCollectionWithIntent(
DeckPickerEx::class.java,
Intent(),
)
// Neither collection, not its models will be initialized without storage permission
// assert: Lazy Collection initialization CollectionTask.LoadCollectionComplete fails
assertFailsWith<Exception> { d.getColUnsafe }
} finally {
disableNullCollection()
}
}
@Test
fun onResumeLoadCollectionSuccessWithAccessibleCollection() {
try {
grantWritePermissions()
val d =
super.startActivityNormallyOpenCollectionWithIntent(
DeckPickerEx::class.java,
Intent(),
)
assertThat(
"Collection initialization ensured by CollectionTask.LoadCollectionComplete",
d.getColUnsafe,
notNullValue(),
)
assertThat(
"Collection Models Loaded",
d.getColUnsafe.notetypes,
notNullValue(),
)
} finally {
revokeWritePermissions()
}
}
@Test
fun `ContextMenu starts expected dialogs when specific options are selected`() =
runTest {
startActivityNormallyOpenCollectionWithIntent(DeckPicker::class.java, Intent()).run {
val didA = addDeck("Deck 1")
supportFragmentManager.selectContextMenuOption(DeckPickerContextMenuOption.RENAME_DECK, didA)
assertDialogTitleEquals("Rename deck")
dismissAllDialogFragments()
supportFragmentManager.selectContextMenuOption(DeckPickerContextMenuOption.CREATE_SUBDECK, didA)
assertDialogTitleEquals("Create subdeck")
dismissAllDialogFragments()
supportFragmentManager.selectContextMenuOption(DeckPickerContextMenuOption.CUSTOM_STUDY, didA)
assertDialogTitleEquals("Custom study")
dismissAllDialogFragments()
// TODO test code enters in a recursion in BasicItemSelectedListener inside ExportDialog
// supportFragmentManager.selectContextMenuOption(DeckPickerContextMenuOption.EXPORT_DECK, didA)
// assertAlertDialogTitleEquals("Export")
// dismissAllDialogFragments()
}
}
/** Simulates a selection in the context menu by setting the specific result in FragmentManager */
private fun FragmentManager.selectContextMenuOption(
option: DeckPickerContextMenuOption,
deckId: DeckId,
) {
val arguments =
Bundle().apply {
putLong(DeckPickerContextMenu.CONTEXT_MENU_DECK_ID, deckId)
putSerializable(DeckPickerContextMenu.CONTEXT_MENU_DECK_OPTION, option)
}
setFragmentResult(DeckPickerContextMenu.REQUEST_KEY_CONTEXT_MENU, arguments)
}
private fun assertDialogTitleEquals(expectedTitle: String) {
val actualTitle = (ShadowDialog.getLatestDialog() as AlertDialog).title
Timber.d("titles = \"$actualTitle\", \"$expectedTitle\"")
assertEquals(expectedTitle, actualTitle)
}
@Test
fun `ContextMenu starts expected activities when specific options are selected`() =
runTest {
suspend fun DeckPicker.selectContextMenuOptionForActivity(
option: DeckPickerContextMenuOption,
deckId: DeckId,
): Intent {
var result: Destination? = null
viewModel.flowOfDestination.test(1.seconds) {
supportFragmentManager.selectContextMenuOption(option, deckId)
result = awaitItem()
}
return result!!.toIntent(this)
}
startActivityNormallyOpenCollectionWithIntent(DeckPicker::class.java, Intent()).run {
val didA = addDeck("Deck 1")
val didDynamicA = addDynamicDeck("Deck Dynamic 1")
val noteEditor = selectContextMenuOptionForActivity(DeckPickerContextMenuOption.ADD_CARD, didA)
assertEquals("com.ichi2.anki.SingleFragmentActivity", noteEditor.component!!.className)
onBackPressedDispatcher.onBackPressed()
val browser = selectContextMenuOptionForActivity(DeckPickerContextMenuOption.BROWSE_CARDS, didA)
assertEquals("com.ichi2.anki.CardBrowser", browser.component!!.className)
onBackPressedDispatcher.onBackPressed()
// select deck options for a normal deck
val deckOptionsNormal = selectContextMenuOptionForActivity(DeckPickerContextMenuOption.DECK_OPTIONS, didA)
assertEquals("com.ichi2.anki.SingleFragmentActivity", deckOptionsNormal.component!!.className)
onBackPressedDispatcher.onBackPressed()
// select deck options for a dynamic deck
val deckOptionsDynamic = selectContextMenuOptionForActivity(DeckPickerContextMenuOption.DECK_OPTIONS, didDynamicA)
assertEquals("com.ichi2.anki.FilteredDeckOptions", deckOptionsDynamic.component!!.className)
onBackPressedDispatcher.onBackPressed()
Prefs.newReviewRemindersEnabled = true
val scheduleReminders = selectContextMenuOptionForActivity(DeckPickerContextMenuOption.SCHEDULE_REMINDERS, didA)
assertEquals("com.ichi2.anki.SingleFragmentActivity", scheduleReminders.component!!.className)
onBackPressedDispatcher.onBackPressed()
}
}
@Test
fun `ContextMenu deletes deck when selecting DELETE_DECK`() =
runTest {
startActivityNormallyOpenCollectionWithIntent(DeckPicker::class.java, Intent()).run {
val didA = addDeck("Deck 1")
supportFragmentManager.selectContextMenuOption(DeckPickerContextMenuOption.DELETE_DECK, didA)
assertThat(getColUnsafe.decks.allNamesAndIds().map { it.id }, not(containsInAnyOrder(didA)))
}
}
@Test
fun `ContextMenu creates deck shortcut when selecting CREATE_SHORTCUT`() =
runTest {
startActivityNormallyOpenCollectionWithIntent(DeckPicker::class.java, Intent()).run {
val didA = addDeck("Deck 1")
supportFragmentManager.selectContextMenuOption(DeckPickerContextMenuOption.CREATE_SHORTCUT, didA)
assertEquals(
"Deck 1",
ShortcutManagerCompat.getShortcuts(this, ShortcutManagerCompat.FLAG_MATCH_PINNED).first().shortLabel,
)
}
}
@Test
@Flaky(OS.WINDOWS)
fun `ContextMenu unburied cards when selecting UNBURY`() =
runTest {
startActivityNormallyOpenCollectionWithIntent(DeckPicker::class.java, Intent()).run {
TimeManager.reset()
// stop 'next day' code running, which calls 'unbury'
updateDeckList()
val deckId = addDeck("Deck 1")
getColUnsafe.decks.select(deckId)
getColUnsafe.notetypes.byName("Basic")!!.did = deckId
val card = addBasicNote("front", "back").firstCard()
getColUnsafe.sched.buryCards(listOf(card.id))
updateDeckList()
advanceRobolectricLooper()
assertEquals(1, visibleDeckCount)
assertTrue(getColUnsafe.sched.haveBuried(), "Deck should have buried cards")
supportFragmentManager.selectContextMenuOption(DeckPickerContextMenuOption.UNBURY, deckId)
kotlin.test.assertFalse(getColUnsafe.sched.haveBuried())
}
}
@Test
fun `ContextMenu testDynRebuildAndEmpty`() =
runTest {
startActivityNormallyOpenCollectionWithIntent(DeckPicker::class.java, Intent()).run {
val cardIds =
(0..3)
.map { addBasicNote("$it", "").firstCard().id }
assertTrue(allCardsInSameDeck(cardIds, 1))
val deckId = addDynamicDeck("Deck 1")
getColUnsafe.sched.rebuildDyn(deckId)
assertTrue(allCardsInSameDeck(cardIds, deckId))
updateDeckList()
assertEquals(1, visibleDeckCount)
supportFragmentManager.selectContextMenuOption(DeckPickerContextMenuOption.CUSTOM_STUDY_EMPTY, deckId) // Empty
assertTrue(allCardsInSameDeck(cardIds, 1))
supportFragmentManager.selectContextMenuOption(DeckPickerContextMenuOption.CUSTOM_STUDY_REBUILD, deckId) // Rebuild
assertTrue(allCardsInSameDeck(cardIds, deckId))
}
}
private fun allCardsInSameDeck(
cardIds: List<Long>,
deckId: DeckId,
): Boolean = cardIds.all { col.getCard(it).did == deckId }
@Test
@RunInBackground
@Flaky(OS.WINDOWS)
fun version16CollectionOpens() {
try {
setupColV16()
InitialActivityWithConflictTest.setupForValid(targetContext)
val deckPicker: DeckPicker =
super.startActivityNormallyOpenCollectionWithIntent(
DeckPickerEx::class.java,
Intent(),
)
waitForAsyncTasksToComplete()
assertThat(
"Collection should now be open",
CollectionManager.isOpenUnsafe(),
)
assertThat(
CollectionType.SCHEMA_V_16.isCollection(
col,
),
equalTo(true),
)
assertThat(
"Decks should be visible",
deckPicker.visibleDeckCount,
equalTo(1),
)
} finally {
InitialActivityWithConflictTest.setupForDefault()
}
}
@Ignore("needs refactoring")
@Test
fun corruptVersion16CollectionShowsDatabaseError() {
try {
setupColV16()
// corrupt col
DbUtils.performQuery(targetContext, "drop table decks")
InitialActivityWithConflictTest.setupForValid(targetContext)
val deckPicker =
super.startActivityNormallyOpenCollectionWithIntent(
DeckPickerEx::class.java,
Intent(),
)
waitForAsyncTasksToComplete()
assertThat(
"Collection should not be open",
!CollectionManager.isOpenUnsafe(),
)
assertThat(
"An error dialog should be displayed",
deckPicker.databaseErrorDialog,
equalTo(DatabaseErrorDialogType.DIALOG_LOAD_FAILED),
)
} finally {
InitialActivityWithConflictTest.setupForDefault()
}
}
@Test
fun futureSchemaShowsError() {
try {
setupColV250()
InitialActivityWithConflictTest.setupForValid(targetContext)
val deckPicker =
super.startActivityNormallyOpenCollectionWithIntent(
DeckPickerEx::class.java,
Intent(),
)
waitForAsyncTasksToComplete()
assertThat(
"Collection should not be open",
!CollectionManager.isOpenUnsafe(),
)
assertThat(
"An error dialog should be displayed",
deckPicker.databaseErrorDialog,
equalTo(DatabaseErrorDialogType.INCOMPATIBLE_DB_VERSION),
)
assertThat(
CollectionHelper.getDatabaseVersion(targetContext),
equalTo(250),
)
} catch (e: UnknownDatabaseVersionException) {
assertThat("no exception should be thrown", false, equalTo(true))
} finally {
InitialActivityWithConflictTest.setupForDefault()
}
}
@Test
fun checkDisplayOfStudyOptionsOnTablet() {
assumeTrue("We are running on a tablet", mQualifiers!!.contains("xlarge"))
val deckPickerEx =
super.startActivityNormallyOpenCollectionWithIntent(
DeckPickerEx::class.java,
Intent(),
)
val studyOptionsFragment =
deckPickerEx.supportFragmentManager.findFragmentById(R.id.studyoptions_fragment) as StudyOptionsFragment?
assertThat(
"Study options should show on start on tablet",
studyOptionsFragment,
notNullValue(),
)
}
@Test
fun checkIfReturnsTrueWhenAtLeastOneDeckIsDisplayed() {
addDeck("Hello World")
// Reason for using 2 as the number of decks -> This deck + Default deck
assertThat("Deck added", col.decks.count(), equalTo(2))
val deckPicker =
startActivityNormallyOpenCollectionWithIntent(
DeckPicker::class.java,
Intent(),
)
assertThat(
"Deck is being displayed",
deckPicker.hasAtLeastOneDeckBeingDisplayed(),
equalTo(true),
)
}
@Test
fun checkIfReturnsFalseWhenNoDeckIsDisplayed() {
// Only default deck would be there in the count, hence using the value as 1.
// Default deck does not get displayed in the DeckPicker if the default deck is empty.
assertThat("Contains only default deck", col.decks.count(), equalTo(1))
val deckPicker =
startActivityNormallyOpenCollectionWithIntent(
DeckPicker::class.java,
Intent(),
)
assertThat(
"No deck is being displayed",
deckPicker.hasAtLeastOneDeckBeingDisplayed(),
equalTo(false),
)
}
@Test
fun `unbury is usable - Issue 15050`() {
// We had an issue where 'Unbury' was not visible
// This was because the deck selection was not changed when a long press occurred
// one empty deck to be initially selected, one with cards to check 'unbury' status
val emptyDeck = addDeck("No Cards")
val deckWithCards = addDeck("With Cards")
updateDeckConfig(deckWithCards) { new.bury = true }
// Add a note with 2 cards in deck "With Cards", one of these cards is to be buried
col.notetypes.byName("Basic (and reversed card)")!!.also { noteType ->
col.notetypes.save(noteType.apply { did = deckWithCards })
}
addBasicAndReversedNote()
// Answer 'Easy' for one of the cards, burying the other
col.decks.select(deckWithCards)
col.sched.deckDueTree() // ? if not called, decks.select(toSelect) un-buries a card
col.sched.answerCard(col.sched.card!!, Ease.EASY)
assertThat("the other card is buried", col.sched.card, nullValue())
// select a deck with no cards
col.decks.select(emptyDeck)
assertThat("unbury is not visible: deck has no cards", !col.sched.haveBuried())
deckPicker {
assertThat("deck focus is set", viewModel.focusedDeck, equalTo(emptyDeck))
// ACT: open up the Deck Context Menu
val deckToClick =
recyclerView.children.single {
it.findViewById<TextView>(R.id.deckpicker_name).text == "With Cards"
}
deckToClick.performLongClick()
// ASSERT
assertThat("unbury is visible: one card is buried", col.sched.haveBuried())
assertThat("deck focus has changed", viewModel.focusedDeck, equalTo(deckWithCards))
}
}
@Test
@NeedsTest("possible bug: Moving the ops outside the deckPicker { } failed in tablet mode")
fun `undo menu item changes`() =
runTest {
fun DeckPicker.getUndoTitle() = menu().findItem(R.id.action_undo).title.toString()
fun waitForMenu() = ShadowLooper.runUiThreadTasksIncludingDelayedTasks()
suspend fun DeckPicker.undo() {
undoAndShowSnackbar()
waitForMenu()
}
deckPicker {
// enqueue two actions, neither of which affect the study queues
val note = addBasicNoteWithOp()
note.updateOp { this.fields[0] = "baz" }
waitForMenu()
assertThat(getUndoTitle(), containsString("Update Note"))
undo()
assertThat(getUndoTitle(), containsString("Add Note"))
}
}
private fun deckPicker(function: suspend DeckPicker.() -> Unit) =
runTest {
val deckPicker =
startActivityNormallyOpenCollectionWithIntent(
DeckPicker::class.java,
Intent(),
)
function(deckPicker)
}
private fun useCollection(collectionType: CollectionType) {
// load asset into temp
val path = ResourceLoader.getTempCollection(targetContext, collectionType.assetFile)
val p = File(path)
assertThat(p.isFile, equalTo(true))
val collectionDirectory = p.parent
// set collection path
targetContext.sharedPrefs().edit {
putString(CollectionHelper.PREF_COLLECTION_PATH, collectionDirectory)
}
// ensure collection not loaded yet
assertThat(
"collection should not be loaded",
CollectionManager.isOpenUnsafe(),
equalTo(false),
)
}
private fun setupColV16() {
Storage.setUseInMemory(false)
useCollection(CollectionType.SCHEMA_V_16)
}
private fun setupColV250() {
Storage.setUseInMemory(false)
useCollection(CollectionType.SCHEMA_V_250)
}
enum class CollectionType(
val assetFile: String,
private val deckName: String,
) {
SCHEMA_V_16("schema16.anki2", "ThisIsSchema16"),
SCHEMA_V_250(
"schema250.anki2",
"ThisIsSchema250",
),
;
fun isCollection(col: com.ichi2.anki.libanki.Collection): Boolean = col.decks.byName(deckName) != null
}
private class DeckPickerEx : DeckPicker() {
var databaseErrorDialog: DatabaseErrorDialogType? = null
var displayedAnalyticsOptIn = false
var optionsMenu: Menu? = null
override fun showDatabaseErrorDialog(
errorDialogType: DatabaseErrorDialogType,
exceptionData: DatabaseErrorDialog.CustomExceptionData?,
) {
databaseErrorDialog = errorDialogType
}
fun onStoragePermissionGranted() {
onRequestPermissionsResult(
REQUEST_STORAGE_PERMISSION,
arrayOf(""),
intArrayOf(PackageManager.PERMISSION_GRANTED),
)
}
override fun displayAnalyticsOptInDialog() {
displayedAnalyticsOptIn = true
super.displayAnalyticsOptInDialog()
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
optionsMenu = menu
return super.onPrepareOptionsMenu(menu)
}
}
}