forked from ankidroid/Anki-Android
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractFlashcardViewerTest.kt
More file actions
413 lines (352 loc) · 16.5 KB
/
AbstractFlashcardViewerTest.kt
File metadata and controls
413 lines (352 loc) · 16.5 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
//noinspection MissingCopyrightHeader #8659
package com.ichi2.anki
import android.content.Intent
import android.os.Build
import android.os.Parcelable
import android.webkit.RenderProcessGoneDetail
import androidx.annotation.CheckResult
import androidx.core.os.BundleCompat
import androidx.core.os.bundleOf
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SdkSuppress
import anki.config.ConfigKey
import com.ichi2.anim.ActivityTransitionAnimation
import com.ichi2.anim.ActivityTransitionAnimation.Direction
import com.ichi2.anki.AbstractFlashcardViewer.Companion.toAnimationTransition
import com.ichi2.anki.AbstractFlashcardViewer.Signal
import com.ichi2.anki.AbstractFlashcardViewer.Signal.Companion.toSignal
import com.ichi2.anki.AnkiActivity.Companion.FINISH_ANIMATION_EXTRA
import com.ichi2.anki.NoteEditorFragment.Companion.NoteEditorCaller
import com.ichi2.anki.cardviewer.Gesture
import com.ichi2.anki.cardviewer.ViewerCommand
import com.ichi2.anki.libanki.sched.Ease
import com.ichi2.anki.libanki.testutils.ext.addNote
import com.ichi2.anki.observability.undoableOp
import com.ichi2.anki.preferences.sharedPrefs
import com.ichi2.anki.reviewer.AutomaticAnswer
import com.ichi2.anki.reviewer.AutomaticAnswerAction
import com.ichi2.anki.reviewer.AutomaticAnswerSettings
import com.ichi2.anki.servicelayer.LanguageHintService
import com.ichi2.testutils.common.Flaky
import com.ichi2.testutils.common.OS
import com.ichi2.utils.createBasicTypingNoteType
import org.hamcrest.MatcherAssert.assertThat
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.Test
import org.junit.jupiter.api.assertDoesNotThrow
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import org.junit.runner.RunWith
import org.mockito.Mockito.mock
import org.robolectric.Robolectric
import org.robolectric.android.controller.ActivityController
import timber.log.Timber
import java.util.Locale
import java.util.stream.Stream
@Suppress("SameParameterValue")
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) // getImeHintLocales, toLanguageTags, onRenderProcessGone, RenderProcessGoneDetail
@RunWith(AndroidJUnit4::class)
class AbstractFlashcardViewerTest : RobolectricTest() {
class NonAbstractFlashcardViewer : AbstractFlashcardViewer() {
var answered: Ease? = null
private var lastTime = 0
override fun performReload() {
// intentionally blank
}
val typedInput get() = typedInputText
override fun answerCard(ease: Ease) {
super.answerCard(ease)
answered = ease
}
override val elapsedRealTime: Long
get() {
lastTime +=
baseContext
.sharedPrefs()
.getInt(DOUBLE_TAP_TIME_INTERVAL, DEFAULT_DOUBLE_TAP_TIME_INTERVAL)
return lastTime.toLong()
}
val hintLocale: String?
get() {
val imeHintLocales = answerField!!.imeHintLocales ?: return null
return imeHintLocales.toLanguageTags()
}
fun hasAutomaticAnswerQueued(): Boolean = automaticAnswer.timeoutHandler.hasMessages(0)
/**
* Fixes an issue with noAutomaticAnswerAfterRenderProcessGoneAndPaused_issue9632
* where [onMediaGroupCompleted] executed AFTER [executeCommand] completed
* this lead to an assertion which sometimes occurred before [onMediaGroupCompleted] had
* been called, which failed
*
* This is fine in real life, as we have media to play
*/
private var mediaGroupCompleted = false
override fun onMediaGroupCompleted() {
super.onMediaGroupCompleted()
mediaGroupCompleted = true
}
override fun executeCommand(
which: ViewerCommand,
fromGesture: Gesture?,
): Boolean {
mediaGroupCompleted = false
return super.executeCommand(which, fromGesture).also {
if (which != ViewerCommand.SHOW_ANSWER) return@also
Timber.v("waiting for onMediaGroupCompleted")
for (i in 0..100) {
if (mediaGroupCompleted) break
Thread.sleep(10)
}
require(mediaGroupCompleted) { "mediaGroupCompleted never occurred" }
}
}
}
@ParameterizedTest
@MethodSource("getSignalFromUrlTest_args")
fun getSignalFromUrlTest(
url: String,
signal: Signal,
) {
assertEquals(url.toSignal(), signal)
}
@Test
fun invalidEncodingDoesNotCrash() {
// #5944 - input came in as: 'typeblurtext:%'. We've fixed the encoding, but want to make sure there's no crash
// as JS can call this function with arbitrary data.
val url = "typeblurtext:%"
val viewer: NonAbstractFlashcardViewer = getViewer(true)
assertDoesNotThrow { viewer.handleUrlFromJavascript(url) }
}
@Test
fun validEncodingSetsAnswerCorrectly() {
// 你好%
val url = "typechangetext:%E4%BD%A0%E5%A5%BD%25"
val viewer: NonAbstractFlashcardViewer = getViewer(true)
viewer.handleUrlFromJavascript(url)
assertThat(viewer.typedInput, equalTo("你好%"))
}
@Test
fun testEditingCardChangesTypedAnswer() =
runTest {
// 7363
addBasicWithTypingNote("Hello", "World")
val viewer: NonAbstractFlashcardViewer = getViewer(true)
assertThat(viewer.correctTypedAnswer, equalTo("World"))
waitForAsyncTasksToComplete()
val note = viewer.currentCard!!.note()
note.setField(1, "David")
undoableOp { updateNote(note) }
waitForAsyncTasksToComplete()
assertThat(viewer.correctTypedAnswer, equalTo("David"))
}
@Test
fun testEditingCardChangesTypedAnswerOnDisplayAnswer() =
runTest {
// 7363
addBasicWithTypingNote("Hello", "World")
val viewer: NonAbstractFlashcardViewer = getViewer(true)
assertThat(viewer.correctTypedAnswer, equalTo("World"))
viewer.displayCardAnswer()
assertThat(viewer.cardContent, containsString("World"))
waitForAsyncTasksToComplete()
val note = viewer.currentCard!!.note()
note.setField(1, "David")
undoableOp { updateNote(note) }
waitForAsyncTasksToComplete()
assertThat(viewer.correctTypedAnswer, equalTo("David"))
assertThat(viewer.cardContent, not(containsString("World")))
// the saving will have caused the screen to switch back to question side
assertThat(viewer.cardContent, containsString("Hello"))
}
@Test
fun testEditCardProvidesInverseTransition() {
val viewer: NonAbstractFlashcardViewer = getViewer(true)
val gestures = listOf(Gesture.SWIPE_LEFT, Gesture.SWIPE_UP, Gesture.DOUBLE_TAP)
gestures.forEach { gesture ->
val expectedAnimation =
AbstractFlashcardViewer.getAnimationTransitionFromGesture(gesture)
val expectedInverseAnimation =
ActivityTransitionAnimation.getInverseTransition(expectedAnimation)
val animation = gesture.toAnimationTransition().invert()
val bundle =
bundleOf(
NoteEditorFragment.EXTRA_CALLER to NoteEditorCaller.EDIT.value,
NoteEditorFragment.EXTRA_CARD_ID to viewer.currentCard!!.id,
FINISH_ANIMATION_EXTRA to animation as Parcelable,
)
val noteEditor = NoteEditorTest().openNoteEditorWithArgs(bundle)
val actualInverseAnimation =
BundleCompat.getParcelable(
noteEditor.requireArguments(),
FINISH_ANIMATION_EXTRA,
Direction::class.java,
)
assertEquals(expectedInverseAnimation, actualInverseAnimation)
}
}
@Test
fun testCommandPerformsAnswerCard() {
// Regression for #8527/#8572
// Note: Couldn't get a spy working, so overriding the method
val viewer: NonAbstractFlashcardViewer = getViewer(true)
assertThat("Displaying question", viewer.isDisplayingAnswer, equalTo(false))
viewer.executeCommand(ViewerCommand.FLIP_OR_ANSWER_EASE4)
assertThat("Displaying answer", viewer.isDisplayingAnswer, equalTo(true))
viewer.executeCommand(ViewerCommand.FLIP_OR_ANSWER_EASE4)
assertThat(viewer.answered, notNullValue())
}
@Test
fun defaultLanguageIsNull() {
assertThat(viewer.hintLocale, nullValue())
}
@Test
@Flaky(OS.ALL, "executeCommand(FLIP_OR_ANSWER_EASE4) cannot be awaited")
fun typedLanguageIsSet() =
runTest {
val withLanguage = col.createBasicTypingNoteType("a")
val normal = col.createBasicTypingNoteType("b")
val typedField = 1 // BACK
LanguageHintService.setLanguageHintForField(col.notetypes, withLanguage, typedField, Locale("ja"))
addNoteUsingNoteTypeName(withLanguage.name, "ichi", "ni")
addNoteUsingNoteTypeName(normal.name, "one", "two")
val viewer = getViewer(false)
assertThat("A note type with a language hint (japanese) should use it", viewer.hintLocale, equalTo("ja"))
viewer.executeCommand(ViewerCommand.FLIP_OR_ANSWER_EASE4)
viewer.executeCommand(ViewerCommand.FLIP_OR_ANSWER_EASE4)
assertThat("A default note type should have no preference", viewer.hintLocale, nullValue())
}
@Test
fun automaticAnswerDisabledProperty() {
val controller = getViewerController(addCard = true, startedWithShortcut = false)
val viewer = controller.get()
viewer.automaticAnswer.enable()
assertThat("not disabled initially", viewer.automaticAnswer.isDisabled, equalTo(false))
controller.pause()
assertThat("disabled after pause", viewer.automaticAnswer.isDisabled, equalTo(true))
controller.resume()
assertThat("enabled after resume", viewer.automaticAnswer.isDisabled, equalTo(false))
}
@Test
fun noAutomaticAnswerAfterRenderProcessGoneAndPaused_issue9632() =
runTest {
val controller = getViewerController(addCard = true, startedWithShortcut = false)
val viewer = controller.get()
viewer.automaticAnswer = AutomaticAnswer(viewer, AutomaticAnswerSettings(AutomaticAnswerAction.BURY_CARD, 5.0, 5.0))
viewer.lifecycle.addObserver(viewer.automaticAnswer)
viewer.automaticAnswer.enable()
viewer.executeCommand(ViewerCommand.SHOW_ANSWER)
assertThat("messages after flipping card", viewer.hasAutomaticAnswerQueued(), equalTo(true))
controller.pause()
assertThat("disabled after pause", viewer.automaticAnswer.isDisabled, equalTo(true))
assertThat("no auto answer after pause", viewer.hasAutomaticAnswerQueued(), equalTo(false))
viewer.onRenderProcessGoneDelegate.onRenderProcessGone(viewer.webView!!, mock(RenderProcessGoneDetail::class.java))
assertThat("no auto answer after onRenderProcessGone when paused", viewer.hasAutomaticAnswerQueued(), equalTo(false))
}
@Test
fun `Show audio play buttons preference handling - sound`() =
runTest {
addBasicWithTypingNote("SOUND [sound:android_audiorec.3gp]", "back")
getViewerContent().let { content ->
assertThat("show audio preference default value: enabled", content, containsString("playsound:q:0"))
assertThat("show audio preference default value: enabled", content, containsString("SOUND"))
}
setHidePlayAudioButtons(true)
getViewerContent().let { content ->
assertThat("show audio preference disabled", content, not(containsString("playsound:q:0")))
assertThat("show audio preference disabled", content, containsString("SOUND"))
}
setHidePlayAudioButtons(false)
getViewerContent().let { content ->
assertThat("show audio preference enabled explicitly", content, containsString("playsound:q:0"))
assertThat("show audio preference enabled explicitly", content, containsString("SOUND"))
}
}
@Test
fun `Show audio play buttons preference handling - tts`() =
runTest {
addTextToSpeechNote("TTS", "BACK")
getViewerContent().let { content ->
assertThat("show audio preference default value: enabled", content, containsString("playsound:q:0"))
assertThat("show audio preference default value: enabled", content, containsString("TTS"))
}
setHidePlayAudioButtons(true)
getViewerContent().let { content ->
assertThat("show audio preference disabled", content, not(containsString("playsound:q:0")))
assertThat("show audio preference disabled", content, containsString("TTS"))
}
setHidePlayAudioButtons(false)
getViewerContent().let { content ->
assertThat("show audio preference enabled explicitly", content, containsString("playsound:q:0"))
assertThat("show audio preference enabled explicitly", content, containsString("TTS"))
}
}
private fun setHidePlayAudioButtons(value: Boolean) = col.config.setBool(ConfigKey.Bool.HIDE_AUDIO_PLAY_BUTTONS, value)
private fun getViewerContent(): String? {
// PERF: Optimise this to not create a new viewer each time
return getViewer(addCard = false).cardContent
}
@get:CheckResult
private val viewer: NonAbstractFlashcardViewer
get() = getViewer(true)
@CheckResult
private fun getViewer(addCard: Boolean): NonAbstractFlashcardViewer = getViewer(addCard, false)
@CheckResult
private fun getViewer(
addCard: Boolean,
startedWithShortcut: Boolean,
): NonAbstractFlashcardViewer = getViewerController(addCard, startedWithShortcut).get()
@CheckResult
private fun getViewerController(
addCard: Boolean,
startedWithShortcut: Boolean,
): ActivityController<NonAbstractFlashcardViewer> {
if (addCard) {
val n = col.newNote()
n.setField(0, "a")
col.addNote(n)
}
val intent = Intent()
if (startedWithShortcut) {
intent.putExtra(NavigationDrawerActivity.EXTRA_STARTED_WITH_SHORTCUT, true)
}
val multimediaController =
Robolectric
.buildActivity(NonAbstractFlashcardViewer::class.java, intent)
.create()
.start()
.resume()
.visible()
saveControllerForCleanup(multimediaController)
val viewer = multimediaController.get()
viewer.onCollectionLoaded(col)
viewer.loadInitialCard()
// Without this, AbstractFlashcardViewer.mCard is still null, and RobolectricTest.tearDown executes before
// AsyncTasks spawned by by loading the viewer finish. Is there a way to synchronize these things while under test?
advanceRobolectricLooperWithSleep()
advanceRobolectricLooperWithSleep()
return multimediaController
}
companion object {
@JvmStatic // required for @MethodSource
fun getSignalFromUrlTest_args() =
Stream.of(
Arguments.of("signal:show_answer", Signal.SHOW_ANSWER),
Arguments.of("signal:typefocus", Signal.TYPE_FOCUS),
Arguments.of("signal:relinquishFocus", Signal.RELINQUISH_FOCUS),
Arguments.of("signal:answer_ease1", Signal.ANSWER_ORDINAL_1),
Arguments.of("signal:answer_ease2", Signal.ANSWER_ORDINAL_2),
Arguments.of("signal:answer_ease3", Signal.ANSWER_ORDINAL_3),
Arguments.of("signal:answer_ease4", Signal.ANSWER_ORDINAL_4),
Arguments.of("signal:answer_ease0", Signal.SIGNAL_NOOP),
)
}
}
fun AbstractFlashcardViewer.loadInitialCard() = launchCatchingTask { updateCardAndRedraw() }
val AbstractFlashcardViewer.typedInputText get() = typeAnswer!!.input
val AbstractFlashcardViewer.correctTypedAnswer get() = typeAnswer!!.correct