forked from ankidroid/Anki-Android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContentProviderTest.kt
More file actions
1577 lines (1493 loc) · 60.4 KB
/
ContentProviderTest.kt
File metadata and controls
1577 lines (1493 loc) · 60.4 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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************************
* *
* Copyright (c) 2015 Frank Oltmanns <frank.oltmanns@gmail.com> *
* Copyright (c) 2015 Timothy Rae <timothy.rae@gmail.com> *
* Copyright (c) 2016 Mark Carter <mark@marcardar.com> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki.tests
import android.content.ContentResolver
import android.content.ContentUris
import android.content.ContentValues
import android.database.Cursor
import android.database.CursorWindow
import android.net.Uri
import anki.notetypes.StockNotetype
import com.ichi2.anki.CollectionManager
import com.ichi2.anki.Ease
import com.ichi2.anki.FlashCardsContract
import com.ichi2.anki.common.utils.annotation.KotlinCleanup
import com.ichi2.anki.provider.pureAnswer
import com.ichi2.anki.testutil.DatabaseUtils.cursorFillWindow
import com.ichi2.anki.testutil.GrantStoragePermission.storagePermission
import com.ichi2.anki.testutil.addNote
import com.ichi2.anki.testutil.grantPermissions
import com.ichi2.libanki.Card
import com.ichi2.libanki.DeckId
import com.ichi2.libanki.Decks
import com.ichi2.libanki.Note
import com.ichi2.libanki.NoteTypeId
import com.ichi2.libanki.NotetypeJson
import com.ichi2.libanki.Notetypes
import com.ichi2.libanki.QueueType
import com.ichi2.libanki.Utils
import com.ichi2.libanki.addNotetypeLegacy
import com.ichi2.libanki.backend.BackendUtils
import com.ichi2.libanki.exception.ConfirmModSchemaException
import com.ichi2.libanki.getStockNotetype
import com.ichi2.libanki.sched.Scheduler
import com.ichi2.testutils.common.assertThrows
import com.ichi2.utils.emptyStringArray
import kotlinx.serialization.json.Json
import net.ankiweb.rsdroid.exceptions.BackendNotFoundException
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.allOf
import org.hamcrest.Matchers.containsString
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.greaterThan
import org.hamcrest.Matchers.greaterThanOrEqualTo
import org.hamcrest.Matchers.hasItem
import org.json.JSONObject.NULL
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Assume.assumeTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import timber.log.Timber
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlin.test.junit.JUnitAsserter.assertNotNull
/**
* Test cases for [com.ichi2.anki.provider.CardContentProvider].
*
*
* These tests should cover all supported operations for each URI.
*/
class ContentProviderTest : InstrumentedTest() {
@get:Rule
var runtimePermissionRule = grantPermissions(storagePermission, FlashCardsContract.READ_WRITE_PERMISSION)
// Whether tear down should be executed. I.e. if set up was not cancelled.
private var tearDown = false
private var numDecksBeforeTest = 0
/* initialCapacity set to expected value when the test is written.
* Should create no problem if we forget to change it when more tests are added.
*/
private val testDeckIds: MutableList<Long> = ArrayList(TEST_DECKS.size + 1)
private lateinit var createdNotes: ArrayList<Uri>
private var noteTypeId: NoteTypeId = 0L
private var dummyFields = emptyStringArray(1)
/**
* Initially create one note for each note type.
*/
@Before
fun setUp() {
Timber.i("setUp()")
createdNotes = ArrayList()
tearDown = true
// Add a new basic note type that we use for testing purposes (existing note types could potentially be corrupted)
val noteType = createBasicNoteType()
noteTypeId = noteType.id
val fields = noteType.fieldsNames
// Use the names of the fields as test values for the notes which will be added
dummyFields = fields.toTypedArray()
// create test decks and add one note for every deck
numDecksBeforeTest = col.decks.count()
for (fullName in TEST_DECKS) {
val path = Decks.path(fullName)
var partialName: String? = ""
/* Looping over all parents of full name. Adding them to
* mTestDeckIds ensures the deck parents decks get deleted
* too at tear-down.
*/
for (s in path) {
partialName += s
/* If parent already exists, don't add the deck, so
* that we are sure it won't get deleted at
* set-down, */
val did = col.decks.byName(partialName!!)?.id ?: col.decks.id(partialName)
testDeckIds.add(did)
createdNotes.add(setupNewNote(col, noteTypeId, did, dummyFields, TEST_TAG))
partialName += "::"
}
}
// Add a note to the default deck as well so that testQueryNextCard() works
createdNotes.add(setupNewNote(col, noteTypeId, 1, dummyFields, TEST_TAG))
}
private fun createBasicNoteType(name: String = BASIC_NOTE_TYPE_NAME): NotetypeJson {
val noteType =
col
.getStockNotetype(StockNotetype.Kind.KIND_BASIC)
.also { it.name = name }
col.addNotetypeLegacy(BackendUtils.toJsonBytes(noteType))
return col.notetypes.byName(name)!!
}
/**
* Remove the notes and decks created in setUp().
*/
@After
@Throws(Exception::class)
fun tearDown() {
Timber.i("tearDown()")
if (!tearDown) {
return
}
// Delete all notes
val remnantNotes = col.findNotes("tag:$TEST_TAG")
if (remnantNotes.isNotEmpty()) {
col.removeNotes(nids = remnantNotes)
assertEquals(
"Check that remnant notes have been deleted",
0,
col.findNotes("tag:$TEST_TAG").size,
)
}
// delete test decks
col.decks.remove(testDeckIds)
assertEquals(
"Check that all created decks have been deleted",
numDecksBeforeTest,
col.decks.count(),
)
// Delete test note type
col.modSchemaNoCheck()
removeAllNoteTypesByName(col, BASIC_NOTE_TYPE_NAME)
removeAllNoteTypesByName(col, TEST_NOTE_TYPE_NAME)
}
@Throws(Exception::class)
private fun removeAllNoteTypesByName(
col: com.ichi2.libanki.Collection,
name: String,
) {
var testNoteType = col.notetypes.byName(name)
while (testNoteType != null) {
col.notetypes.rem(testNoteType)
testNoteType = col.notetypes.byName(name)
}
}
@Test
fun testDatabaseUtilsInvocationWorks() {
// called by android.database.CursorToBulkCursorAdapter
// This is called by API clients implicitly, but isn't done by this test class
val firstNote = getFirstCardFromScheduler(col)
val noteProjection =
arrayOf(
FlashCardsContract.Note._ID,
FlashCardsContract.Note.FLDS,
FlashCardsContract.Note.TAGS,
)
val resolver = contentResolver
val cursor =
resolver.query(
FlashCardsContract.Note.CONTENT_URI_V2,
noteProjection,
"id=" + firstNote!!.nid,
null,
null,
)
assertNotNull(cursor)
val window = CursorWindow("test")
// Note: We duplicated the code as it did not appear to be accessible via reflection
val initialPosition = cursor.position
cursorFillWindow(cursor, 0, window)
assertThat("position should not change", cursor.position, equalTo(initialPosition))
assertThat("Count should be copied", window.numRows, equalTo(cursor.count))
}
/**
* Check that inserting and removing a note into default deck works as expected
*/
@Test
fun testInsertAndRemoveNote() {
// Get required objects for test
val cr = contentResolver
// Add the note
val values =
ContentValues().apply {
put(FlashCardsContract.Note.MID, noteTypeId)
put(FlashCardsContract.Note.FLDS, Utils.joinFields(TEST_NOTE_FIELDS))
put(FlashCardsContract.Note.TAGS, TEST_TAG)
}
val newNoteUri = cr.insert(FlashCardsContract.Note.CONTENT_URI, values)
assertNotNull("Check that URI returned from addNewNote is not null", newNoteUri)
val col = reopenCol() // test that the changes are physically saved to the DB
// Check that it looks as expected
assertNotNull("check note URI path", newNoteUri!!.lastPathSegment)
val addedNote = Note(col, newNoteUri.lastPathSegment!!.toLong())
addedNote.load(col)
assertEquals(
"Check that fields were set correctly",
addedNote.fields,
TEST_NOTE_FIELDS.toMutableList(),
)
assertEquals("Check that tag was set correctly", TEST_TAG, addedNote.tags[0])
val noteType: NotetypeJson? = col.notetypes.get(noteTypeId)
assertNotNull("Check note type", noteType)
val expectedNumCards = noteType!!.templates.length()
assertEquals("Check that correct number of cards generated", expectedNumCards, addedNote.numberOfCards(col))
// Now delete the note
cr.delete(newNoteUri, null, null)
assertThrows<RuntimeException>("RuntimeException is thrown when deleting note") {
addedNote.load(col)
}
}
/**
* Check that inserting a note with an invalid noteTypeId returns a reasonable exception
*/
@Test
fun testInsertNoteWithBadNoteTypeId() {
val invalidNoteTypeId = 12
val values =
ContentValues().apply {
put(FlashCardsContract.Note.MID, invalidNoteTypeId)
put(FlashCardsContract.Note.FLDS, Utils.joinFields(TEST_NOTE_FIELDS))
put(FlashCardsContract.Note.TAGS, TEST_TAG)
}
assertThrows<BackendNotFoundException> {
contentResolver.insert(FlashCardsContract.Note.CONTENT_URI, values)
}
}
/**
* Check that inserting and removing a note into default deck works as expected
*/
@Test
@Throws(Exception::class)
fun testInsertTemplate() {
// Get required objects for test
val cr = contentResolver
var col = col
// Add a new basic note type that we use for testing purposes (existing note types could potentially be corrupted)
var noteType: NotetypeJson? = createBasicNoteType()
val noteTypeId = noteType!!.id
// Add the note
val noteTypeUri = ContentUris.withAppendedId(FlashCardsContract.Model.CONTENT_URI, noteTypeId)
val testIndex =
TEST_NOTE_TYPE_CARDS.size - 1 // choose the last one because not the same as the basic note type template
val expectedOrd = noteType.templates.length()
val cv =
ContentValues().apply {
put(FlashCardsContract.CardTemplate.NAME, TEST_NOTE_TYPE_CARDS[testIndex])
put(FlashCardsContract.CardTemplate.QUESTION_FORMAT, TEST_NOTE_TYPE_QFMT[testIndex])
put(FlashCardsContract.CardTemplate.ANSWER_FORMAT, TEST_NOTE_TYPE_AFMT[testIndex])
put(FlashCardsContract.CardTemplate.BROWSER_QUESTION_FORMAT, TEST_NOTE_TYPE_QFMT[testIndex])
put(FlashCardsContract.CardTemplate.BROWSER_ANSWER_FORMAT, TEST_NOTE_TYPE_AFMT[testIndex])
}
val templatesUri = Uri.withAppendedPath(noteTypeUri, "templates")
val templateUri = cr.insert(templatesUri, cv)
col = reopenCol() // test that the changes are physically saved to the DB
assertNotNull("Check template uri", templateUri)
assertEquals(
"Check template uri ord",
expectedOrd.toLong(),
ContentUris.parseId(
templateUri!!,
),
)
noteType = col.notetypes.get(noteTypeId)
assertNotNull("Check note type", noteType)
val template = noteType!!.templates[expectedOrd]
assertEquals(
"Check template JSONObject ord",
expectedOrd,
template.ord,
)
assertEquals(
"Check template name",
TEST_NOTE_TYPE_CARDS[testIndex],
template.name,
)
assertEquals("Check qfmt", TEST_NOTE_TYPE_QFMT[testIndex], template.qfmt)
assertEquals("Check afmt", TEST_NOTE_TYPE_AFMT[testIndex], template.afmt)
assertEquals("Check bqfmt", TEST_NOTE_TYPE_QFMT[testIndex], template.bqfmt)
assertEquals("Check bafmt", TEST_NOTE_TYPE_AFMT[testIndex], template.bafmt)
col.notetypes.rem(noteType)
}
/**
* Check that inserting and removing a note into default deck works as expected
*/
@Test
@Throws(Exception::class)
fun testInsertField() {
// Get required objects for test
val cr = contentResolver
var col = col
var noteType: NotetypeJson? = createBasicNoteType()
val noteTypeId = noteType!!.id
val initialFieldsArr = noteType.fields
val initialFieldCount = initialFieldsArr.length()
val noteTypeUri = ContentUris.withAppendedId(FlashCardsContract.Model.CONTENT_URI, noteTypeId)
val insertFieldValues = ContentValues()
insertFieldValues.put(FlashCardsContract.Model.FIELD_NAME, TEST_FIELD_NAME)
val fieldUri = cr.insert(Uri.withAppendedPath(noteTypeUri, "fields"), insertFieldValues)
assertNotNull("Check field uri", fieldUri)
// Ensure that the changes are physically saved to the DB
col = reopenCol()
noteType = col.notetypes.get(noteTypeId)
// Test the field is as expected
val fieldId = ContentUris.parseId(fieldUri!!)
assertEquals("Check field id", initialFieldCount.toLong(), fieldId)
assertNotNull("Check note type", noteType)
val fldsArr = noteType!!.fields
assertEquals(
"Check fields length",
(initialFieldCount + 1),
fldsArr.length(),
)
assertEquals(
"Check last field name",
TEST_FIELD_NAME,
fldsArr.last().name,
)
col.notetypes.rem(noteType)
}
/**
* Test queries to notes table using direct SQL URI
*/
@Test
fun testQueryDirectSqlQuery() {
// search for correct mid
val cr = contentResolver
cr
.query(
FlashCardsContract.Note.CONTENT_URI_V2,
null,
"mid=$noteTypeId",
null,
null,
).use { cursor ->
assertNotNull(cursor)
assertEquals(
"Check number of results",
createdNotes.size,
cursor.count,
)
}
// search for bogus mid
cr.query(FlashCardsContract.Note.CONTENT_URI_V2, null, "mid=0", null, null).use { cursor ->
assertNotNull(cursor)
assertEquals("Check number of results", 0, cursor.count)
}
// check usage of selection args
cr.query(FlashCardsContract.Note.CONTENT_URI_V2, null, "mid=?", arrayOf("0"), null).use { cursor ->
assertNotNull(cursor)
}
}
/**
* Test that a query for all the notes added in setup() looks correct
*/
@Test
fun testQueryNoteIds() {
val cr = contentResolver
// Query all available notes
val allNotesCursor =
cr.query(FlashCardsContract.Note.CONTENT_URI, null, "tag:$TEST_TAG", null, null)
assertNotNull(allNotesCursor)
allNotesCursor.use {
assertEquals(
"Check number of results",
createdNotes.size,
it.count,
)
while (it.moveToNext()) {
// Check that it's possible to leave out columns from the projection
for (i in FlashCardsContract.Note.DEFAULT_PROJECTION.indices) {
val projection =
removeFromProjection(FlashCardsContract.Note.DEFAULT_PROJECTION, i)
val noteId =
it.getString(it.getColumnIndex(FlashCardsContract.Note._ID))
val noteUri = Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, noteId)
cr.query(noteUri, projection, null, null, null).use { singleNoteCursor ->
assertNotNull(
"Check that there is a valid cursor for detail data",
singleNoteCursor,
)
assertEquals(
"Check that there is exactly one result",
1,
singleNoteCursor!!.count,
)
assertTrue(
"Move to beginning of cursor after querying for detail data",
singleNoteCursor.moveToFirst(),
)
// Check columns
assertEquals(
"Check column count",
projection.size,
singleNoteCursor.columnCount,
)
for (j in projection.indices) {
assertEquals(
"Check column name $j",
projection[j],
singleNoteCursor.getColumnName(j),
)
}
}
}
}
}
}
/**
* Check that a valid Cursor is returned when querying notes table with non-default projections
*/
@Test
fun testQueryNotesProjection() {
val cr = contentResolver
// Query all available notes
for (i in FlashCardsContract.Note.DEFAULT_PROJECTION.indices) {
val projection = removeFromProjection(FlashCardsContract.Note.DEFAULT_PROJECTION, i)
cr
.query(
FlashCardsContract.Note.CONTENT_URI,
projection,
"tag:$TEST_TAG",
null,
null,
).use { allNotesCursor ->
assertNotNull("Check that there is a valid cursor", allNotesCursor)
assertEquals(
"Check number of results",
createdNotes.size,
allNotesCursor!!.count,
)
// Check columns
assertEquals(
"Check column count",
projection.size,
allNotesCursor.columnCount,
)
for (j in projection.indices) {
assertEquals(
"Check column name $j",
projection[j],
allNotesCursor.getColumnName(j),
)
}
}
}
}
@Suppress("SameParameterValue")
private fun removeFromProjection(
inputProjection: Array<String>,
idx: Int,
): Array<String?> {
val outputProjection = arrayOfNulls<String>(inputProjection.size - 1)
if (idx >= 0) {
System.arraycopy(inputProjection, 0, outputProjection, 0, idx)
}
for (i in idx + 1 until inputProjection.size) {
outputProjection[i - 1] = inputProjection[i]
}
return outputProjection
}
/**
* Check that updating the flds column works as expected
* FIXME hanging sometimes. API30? API29?
*/
@Test
fun testUpdateNoteFields() {
val cr = contentResolver
val cv = ContentValues()
// Change the fields so that the first field is now "newTestValue"
val dummyFields2 = dummyFields.clone()
dummyFields2[0] = TEST_FIELD_VALUE
for (uri in createdNotes) {
// Update the flds
cv.put(FlashCardsContract.Note.FLDS, Utils.joinFields(dummyFields2))
cr.update(uri, cv, null, null)
cr
.query(uri, FlashCardsContract.Note.DEFAULT_PROJECTION, null, null, null)
.use { noteCursor ->
assertNotNull(
"Check that there is a valid cursor for detail data after update",
noteCursor,
)
assertEquals(
"Check that there is one and only one entry after update",
1,
noteCursor!!.count,
)
assertTrue("Move to first item in cursor", noteCursor.moveToFirst())
val newFields =
Utils.splitFields(
noteCursor.getString(noteCursor.getColumnIndex(FlashCardsContract.Note.FLDS)),
)
assertEquals(
"Check that the flds have been updated correctly",
newFields,
dummyFields2.toMutableList(),
)
}
}
}
/**
* Check that inserting a new note type works as expected
*/
@Test
fun testInsertAndUpdateNoteType() {
val cr = contentResolver
var cv =
ContentValues().apply {
// Insert a new note type
put(FlashCardsContract.Model.NAME, TEST_NOTE_TYPE_NAME)
put(FlashCardsContract.Model.FIELD_NAMES, Utils.joinFields(TEST_NOTE_TYPE_FIELDS))
put(FlashCardsContract.Model.NUM_CARDS, TEST_NOTE_TYPE_CARDS.size)
}
val noteTypeUri = cr.insert(FlashCardsContract.Model.CONTENT_URI, cv)
assertNotNull("Check inserted note type isn't null", noteTypeUri)
assertNotNull("Check last path segment exists", noteTypeUri!!.lastPathSegment)
val noteTypeId = noteTypeUri.lastPathSegment!!.toLong()
var col = reopenCol()
try {
var noteType = col.notetypes.get(noteTypeId)
assertNotNull("Check note type", noteType)
assertEquals("Check note type name", TEST_NOTE_TYPE_NAME, noteType!!.name)
assertEquals(
"Check templates length",
TEST_NOTE_TYPE_CARDS.size,
noteType.templates.length(),
)
assertEquals(
"Check field length",
TEST_NOTE_TYPE_FIELDS.size,
noteType.fields.length(),
)
val fields = noteType.fields
for (i in 0 until fields.length()) {
assertEquals(
"Check name of fields",
TEST_NOTE_TYPE_FIELDS[i],
fields[i].name,
)
}
// Test updating the note type CSS (to test updating NOTE_TYPES_ID Uri)
cv = ContentValues()
cv.put(FlashCardsContract.Model.CSS, TEST_NOTE_TYPE_CSS)
assertThat(
cr.update(noteTypeUri, cv, null, null),
greaterThan(0),
)
col = reopenCol()
noteType = col.notetypes.get(noteTypeId)
assertNotNull("Check note type", noteType)
assertEquals("Check css", TEST_NOTE_TYPE_CSS, noteType!!.css)
// Update each of the templates in note type (to test updating NOTE_TYPES_ID_TEMPLATES_ID Uri)
for (i in TEST_NOTE_TYPE_CARDS.indices) {
cv =
ContentValues().apply {
put(FlashCardsContract.CardTemplate.NAME, TEST_NOTE_TYPE_CARDS[i])
put(FlashCardsContract.CardTemplate.QUESTION_FORMAT, TEST_NOTE_TYPE_QFMT[i])
put(FlashCardsContract.CardTemplate.ANSWER_FORMAT, TEST_NOTE_TYPE_AFMT[i])
put(FlashCardsContract.CardTemplate.BROWSER_QUESTION_FORMAT, TEST_NOTE_TYPE_QFMT[i])
put(FlashCardsContract.CardTemplate.BROWSER_ANSWER_FORMAT, TEST_NOTE_TYPE_AFMT[i])
}
val tmplUri =
Uri.withAppendedPath(
Uri.withAppendedPath(noteTypeUri, "templates"),
i.toString(),
)
assertThat(
"Update rows",
cr.update(tmplUri, cv, null, null),
greaterThan(0),
)
col = reopenCol()
noteType = col.notetypes.get(noteTypeId)
assertNotNull("Check note type", noteType)
val template = noteType!!.templates[i]
assertEquals(
"Check template name",
TEST_NOTE_TYPE_CARDS[i],
template.name,
)
assertEquals("Check qfmt", TEST_NOTE_TYPE_QFMT[i], template.qfmt)
assertEquals("Check afmt", TEST_NOTE_TYPE_AFMT[i], template.afmt)
assertEquals("Check bqfmt", TEST_NOTE_TYPE_QFMT[i], template.bqfmt)
assertEquals("Check bafmt", TEST_NOTE_TYPE_AFMT[i], template.bafmt)
}
} finally {
// Delete the note type (this will force a full-sync)
col.modSchemaNoCheck()
try {
val noteType = col.notetypes.get(noteTypeId)
assertNotNull("Check note type", noteType)
col.notetypes.rem(noteType!!)
} catch (e: ConfirmModSchemaException) {
// This will never happen
}
}
}
/**
* Query .../models URI
*/
@Test
fun testQueryAllNoteType() {
val cr = contentResolver
// Query all available note types
val allNoteTypes = cr.query(FlashCardsContract.Model.CONTENT_URI, null, null, null, null)
assertNotNull(allNoteTypes)
allNoteTypes.use {
assertThat(
"Check that there is at least one result",
allNoteTypes.count,
greaterThan(0),
)
while (allNoteTypes.moveToNext()) {
val noteTypeId =
allNoteTypes.getLong(allNoteTypes.getColumnIndex(FlashCardsContract.Model._ID))
val noteTypeUri =
Uri.withAppendedPath(
FlashCardsContract.Model.CONTENT_URI,
noteTypeId.toString(),
)
val singleNoteType = cr.query(noteTypeUri, null, null, null, null)
assertNotNull(singleNoteType)
singleNoteType.use {
assertEquals(
"Check that there is exactly one result",
1,
it.count,
)
assertTrue("Move to beginning of cursor", it.moveToFirst())
val nameFromNoteTypes =
allNoteTypes.getString(allNoteTypes.getColumnIndex(FlashCardsContract.Model.NAME))
val nameFromNoteType =
it.getString(allNoteTypes.getColumnIndex(FlashCardsContract.Model.NAME))
assertEquals(
"Check that note type names are the same",
nameFromNoteType,
nameFromNoteTypes,
)
val flds =
allNoteTypes.getString(allNoteTypes.getColumnIndex(FlashCardsContract.Model.FIELD_NAMES))
assertThat(
"Check that valid number of fields",
Utils.splitFields(flds).size,
greaterThanOrEqualTo(1),
)
val numCards =
allNoteTypes.getInt(allNoteTypes.getColumnIndex(FlashCardsContract.Model.NUM_CARDS))
assertThat(
"Check that valid number of cards",
numCards,
greaterThanOrEqualTo(1),
)
}
}
}
}
/**
* Move all the cards from their old decks to the first deck that was added in setup()
*/
@Test
fun testMoveCardsToOtherDeck() {
val cr = contentResolver
// Query all available notes
val allNotesCursor =
cr.query(FlashCardsContract.Note.CONTENT_URI, null, "tag:$TEST_TAG", null, null)
assertNotNull(allNotesCursor)
allNotesCursor.use {
assertEquals(
"Check number of results",
createdNotes.size,
it.count,
)
while (it.moveToNext()) {
// Now iterate over all cursors
val cardsUri =
Uri.withAppendedPath(
Uri.withAppendedPath(
FlashCardsContract.Note.CONTENT_URI,
it.getString(it.getColumnIndex(FlashCardsContract.Note._ID)),
),
"cards",
)
cr.query(cardsUri, null, null, null, null).use { cardsCursor ->
assertNotNull(
"Check that there is a valid cursor after query for cards",
cardsCursor,
)
assertThat(
"Check that there is at least one result for cards",
cardsCursor!!.count,
greaterThan(0),
)
while (cardsCursor.moveToNext()) {
val targetDid = testDeckIds[0]
// Move to test deck (to test NOTES_ID_CARDS_ORD Uri)
val values = ContentValues()
values.put(FlashCardsContract.Card.DECK_ID, targetDid)
val cardUri =
Uri.withAppendedPath(
cardsUri,
cardsCursor.getString(cardsCursor.getColumnIndex(FlashCardsContract.Card.CARD_ORD)),
)
cr.update(cardUri, values, null, null)
reopenCol()
val movedCardCur = cr.query(cardUri, null, null, null, null)
assertNotNull(
"Check that there is a valid cursor after moving card",
movedCardCur,
)
assertTrue(
"Move to beginning of cursor after moving card",
movedCardCur!!.moveToFirst(),
)
val did =
movedCardCur.getLong(movedCardCur.getColumnIndex(FlashCardsContract.Card.DECK_ID))
assertEquals("Make sure that card is in new deck", targetDid, did)
}
}
}
}
}
/**
* Check that querying the current note type gives a valid result
*/
@Test
fun testQueryCurrentNoteType() {
val cr = contentResolver
val uri =
Uri.withAppendedPath(
FlashCardsContract.Model.CONTENT_URI,
FlashCardsContract.Model.CURRENT_MODEL_ID,
)
val noteTypeCursor = cr.query(uri, null, null, null, null)
assertNotNull(noteTypeCursor)
noteTypeCursor.use {
assertEquals(
"Check that there is exactly one result",
1,
it.count,
)
assertTrue("Move to beginning of cursor", it.moveToFirst())
assertNotNull(
"Check non-empty field names",
it.getString(it.getColumnIndex(FlashCardsContract.Model.FIELD_NAMES)),
)
assertTrue(
"Check at least one template",
it.getInt(it.getColumnIndex(FlashCardsContract.Model.NUM_CARDS)) > 0,
)
}
}
/**
* Check that an Exception is thrown when unsupported operations are performed
*/
@Test
fun testUnsupportedOperations() {
val cr = contentResolver
val dummyValues = ContentValues()
// Can't update most tables in bulk -- only via ID
val updateUris =
arrayOf(
FlashCardsContract.Note.CONTENT_URI,
FlashCardsContract.Model.CONTENT_URI,
FlashCardsContract.Deck.CONTENT_ALL_URI,
FlashCardsContract.Note.CONTENT_URI
.buildUpon()
.appendPath("1234")
.appendPath("cards")
.build(),
)
for (uri in updateUris) {
try {
cr.update(uri, dummyValues, null, null)
fail("Update on $uri was supposed to throw exception")
} catch (_: UnsupportedOperationException) {
// This was expected ...
} catch (_: IllegalArgumentException) {
// ... or this.
}
}
// Only note/<id> is supported
val deleteUris =
arrayOf(
FlashCardsContract.Note.CONTENT_URI,
FlashCardsContract.Note.CONTENT_URI
.buildUpon()
.appendPath("1234")
.appendPath("cards")
.build(),
FlashCardsContract.Note.CONTENT_URI
.buildUpon()
.appendPath("1234")
.appendPath("cards")
.appendPath("2345")
.build(),
FlashCardsContract.Model.CONTENT_URI,
FlashCardsContract.Model.CONTENT_URI
.buildUpon()
.appendPath("1234")
.build(),
)
for (uri in deleteUris) {
assertThrows<UnsupportedOperationException>("Delete on $uri was supposed to throw exception") {
cr.delete(uri, null, null)
}
}
// Can't do an insert with specific ID on the following tables
val insertUris =
arrayOf(
FlashCardsContract.Note.CONTENT_URI
.buildUpon()
.appendPath("1234")
.build(),
FlashCardsContract.Note.CONTENT_URI
.buildUpon()
.appendPath("1234")
.appendPath("cards")
.build(),
FlashCardsContract.Note.CONTENT_URI
.buildUpon()
.appendPath("1234")
.appendPath("cards")
.appendPath("2345")
.build(),
FlashCardsContract.Model.CONTENT_URI
.buildUpon()
.appendPath("1234")
.build(),
)
for (uri in insertUris) {
try {
cr.insert(uri, dummyValues)
fail("Insert on $uri was supposed to throw exception")
} catch (_: UnsupportedOperationException) {
// This was expected ...
} catch (_: IllegalArgumentException) {
// ... or this.
}
}
}
/**
* Test query to decks table
*/
@Test
fun testQueryAllDecks() {
val decks = col.decks
val decksCursor =
contentResolver
.query(
FlashCardsContract.Deck.CONTENT_ALL_URI,
FlashCardsContract.Deck.DEFAULT_PROJECTION,
null,
null,
null,
)
assertNotNull(decksCursor)
decksCursor.use {
assertEquals(
"Check number of results",
decks.count(),
it.count,
)
while (it.moveToNext()) {
val deckID =
it.getLong(it.getColumnIndex(FlashCardsContract.Deck.DECK_ID))
val deckName =
it.getString(it.getColumnIndex(FlashCardsContract.Deck.DECK_NAME))
val deck = decks.get(deckID)!!
assertNotNull("Check that the deck we received actually exists", deck)
assertEquals(
"Check that the received deck has the correct name",
deck.getString("name"),
deckName,
)
}
}
}
/**
* Test query to specific deck ID
*/
@Test
fun testQueryCertainDeck() {
val deckId = testDeckIds[0]
val deckUri =
Uri.withAppendedPath(
FlashCardsContract.Deck.CONTENT_ALL_URI,
deckId.toString(),
)
contentResolver.query(deckUri, null, null, null, null).use { decksCursor ->
if (decksCursor == null || !decksCursor.moveToFirst()) {
fail("No deck received. Should have delivered deck with id $deckId")
} else {
val returnedDeckID =
decksCursor.getLong(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_ID))
val returnedDeckName =
decksCursor.getString(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_NAME))
val realDeck = col.decks.get(deckId)!!
assertEquals(
"Check that received deck ID equals real deck ID",
deckId,
returnedDeckID,
)
assertEquals(
"Check that received deck name equals real deck name",
realDeck.getString("name"),
returnedDeckName,
)
}
}
}
/**
* Test that query for the next card in the schedule returns a valid result without any deck selector
*/
@Test
fun testQueryNextCard() {
val sched = col.sched
val reviewInfoCursor =
contentResolver.query(
FlashCardsContract.ReviewInfo.CONTENT_URI,
null,
null,
null,
null,
)
assertNotNull(reviewInfoCursor)
assertEquals("Check that we actually received one card", 1, reviewInfoCursor.count)
reviewInfoCursor.moveToFirst()
val cardOrd =
reviewInfoCursor.getInt(reviewInfoCursor.getColumnIndex(FlashCardsContract.ReviewInfo.CARD_ORD))
val noteID =
reviewInfoCursor.getLong(reviewInfoCursor.getColumnIndex(FlashCardsContract.ReviewInfo.NOTE_ID))
var nextCard: Card? = null
for (i in 0..9) { // minimizing fails, when sched.reset() randomly chooses between multiple cards
nextCard = sched.card