/
TestRunner.kt
584 lines (514 loc) · 19.1 KB
/
TestRunner.kt
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
package com.frybits.harmony.app.test
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Handler
import android.os.Looper
import android.os.Messenger
import android.os.SystemClock
import android.util.Log
import androidx.core.content.edit
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
import com.frybits.harmony.app.ACK_EVENT
import com.frybits.harmony.app.ITERATIONS_KEY
import com.frybits.harmony.app.LOG_EVENT
import com.frybits.harmony.app.LOG_KEY
import com.frybits.harmony.app.PREFS_NAME_KEY
import com.frybits.harmony.app.REMOTE_MESSENGER_KEY
import com.frybits.harmony.app.RESULTS_EVENT
import com.frybits.harmony.app.RESULTS_KEY
import com.frybits.harmony.app.USE_ENCRYPTION_KEY
import com.frybits.harmony.getHarmonySharedPreferences
import com.frybits.harmony.secure.getEncryptedHarmonySharedPreferences
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import net.grandcentrix.tray.TrayPreferences
import java.util.UUID
import kotlin.system.measureNanoTime
/*
* Copyright 2021 Pablo Baxter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Created by Pablo Baxter (Github: pablobaxter)
* https://github.com/pablobaxter/Harmony
*/
sealed class TestRunner(
protected val testRunnerId: UUID = UUID.randomUUID(),
private val iterations: Int,
private val isAsync: Boolean,
private val isEncrypted: Boolean
) {
private val runTestMutex = Mutex()
private val _logFlow = MutableSharedFlow<LogEvent>()
val logFlow = _logFlow.asSharedFlow()
protected val testData = arrayListOf<TestData>()
abstract val source: String
protected abstract suspend fun awaitUntilReady()
suspend fun runTest() {
runTestMutex.withLock {
logEvent(Log.INFO, LOG_TAG, "resetting test")
reset()
withTimeout(3000) {
awaitUntilReady()
}
withContext(Dispatchers.Default) {
val testKeyArray = Array(iterations) { it.toString() }
runWriteTests(testKeyArray)
runReadTests(testKeyArray)
}
awaitResults()
}
}
protected abstract suspend fun reset()
protected abstract suspend fun awaitResults()
protected abstract fun write(key: String, value: String, isAsync: Boolean)
protected abstract fun read(key: String)
suspend fun getTestResults(parentId: UUID): TestEntityWithData {
awaitResults()
return withContext(Dispatchers.Main) {
return@withContext TestEntityWithData(
entity = TestRun(
testEntityId = testRunnerId,
parentTestSuiteId = parentId,
numIterations = iterations,
isAsync = isAsync,
isEncrypted = isEncrypted,
source = source
),
testDataList = testData
)
}
}
private suspend fun runWriteTests(testKeyArray: Array<String>) {
logEvent(Log.INFO, LOG_TAG, "starting write tests")
withContext(Dispatchers.Default) {
val writeLongArray = LongArray(iterations)
// Begin write tests
repeat(iterations) { testNum ->
ensureActive()
val value = SystemClock.elapsedRealtimeNanos().toString()
val writeTime = measureNanoTime { write(testKeyArray[testNum], value, isAsync) }
writeLongArray[testNum] = writeTime
}
// Set write data
withContext(Dispatchers.Main) {
testData.add(
WriteTestData(
parentTestEntityId = testRunnerId,
results = writeLongArray
)
)
}
logEvent(Log.INFO, LOG_TAG, "avg write: ${writeLongArray.average() / 1_000_000} ms")
}
logEvent(Log.INFO, LOG_TAG, "ending write tests")
}
private suspend fun runReadTests(testKeyArray: Array<String>) {
logEvent(Log.INFO, LOG_TAG, "starting read tests")
withContext(Dispatchers.Default) {
val readLongArray = LongArray(iterations)
// Begin read tests
repeat(iterations) { testNum ->
ensureActive()
val readTime =
measureNanoTime { read(testKeyArray[testNum]) }
readLongArray[testNum] = readTime
}
// Set read data
withContext(Dispatchers.Main) {
testData.add(
ReadTestData(
parentTestEntityId = testRunnerId,
results = readLongArray
)
)
}
logEvent(Log.INFO, LOG_TAG, "avg read: ${readLongArray.average() / 1_000_000} ms")
}
logEvent(Log.INFO, LOG_TAG, "ending write tests")
}
protected suspend fun logEvent(priority: Int, tag: String, message: String) {
logEvent(
LogEvent(
priority = priority,
tag = tag,
message = message
)
)
}
protected suspend fun logEvent(logEvent: LogEvent) {
_logFlow.emit(logEvent)
}
companion object {
private const val LOG_TAG = "TestRunner"
}
}
abstract class SharedPreferencesTestRunner(
iterations: Int,
isAsync: Boolean,
isEncrypted: Boolean
) : TestRunner(iterations = iterations, isAsync = isAsync, isEncrypted = isEncrypted) {
protected abstract val sharedPreferences: SharedPreferences
protected abstract val editor: SharedPreferences.Editor
override fun write(key: String, value: String, isAsync: Boolean) {
editor.putString(key, value)
if (isAsync) {
editor.apply()
} else {
editor.commit()
}
}
override fun read(key: String) {
sharedPreferences.getString(key, null)
}
}
class VanillaSharedPreferencesTestRunner(
context: Context,
prefsName: String,
iterations: Int,
isAsync: Boolean,
isEncrypted: Boolean
) : SharedPreferencesTestRunner(iterations, isAsync, isEncrypted) {
override val sharedPreferences: SharedPreferences = if (isEncrypted) {
EncryptedSharedPreferences.create(
"$prefsName-encrypted",
MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
} else {
context.getSharedPreferences(prefsName, Context.MODE_PRIVATE)
}
override val editor: SharedPreferences.Editor = sharedPreferences.edit()
override val source: String = TestSource.SHARED_PREFS
override suspend fun awaitUntilReady() {
return
}
override suspend fun reset() {
withContext(Dispatchers.IO) {
editor.clear().commit()
}
}
override suspend fun awaitResults() {
return
}
}
class HarmonyTestRunner(
private val context: Context,
private val prefsName: String,
private val iterations: Int,
isAsync: Boolean,
private val isEncrypted: Boolean
) : SharedPreferencesTestRunner(iterations, isAsync, isEncrypted) {
private val isReadyIndicator = Mutex(true)
private val gotResultsIndicator = Mutex(true)
private val incomingMessenger = Messenger(Handler(Looper.getMainLooper()) { msg ->
when (msg.what) {
ACK_EVENT -> isReadyIndicator.unlock()
LOG_EVENT -> {
val log = msg.data.let {
it.classLoader = LogEvent::class.java.classLoader
return@let it.getParcelable<LogEvent>(LOG_KEY) ?: return@Handler true
}
runBlocking { logEvent(log) }
}
RESULTS_EVENT -> {
val ipcLongArray = msg.data.getLongArray(RESULTS_KEY)
?: throw IllegalArgumentException("No results available")
if (ipcLongArray.any { it == -1L }) {
runBlocking {
logEvent(Log.ERROR, LOG_TAG, "IPC did not set all data")
}
}
testData.add(
IpcTestData(
parentTestEntityId = testRunnerId,
results = ipcLongArray
)
)
runBlocking {
logEvent(
LogEvent(
priority = Log.INFO,
tag = LOG_TAG,
message = "avg ipc: ${ipcLongArray.average() / 1_000_000} ms"
)
)
}
gotResultsIndicator.unlock()
}
}
return@Handler true
})
override val sharedPreferences: SharedPreferences = if (isEncrypted) {
context.getEncryptedHarmonySharedPreferences(
"$prefsName-encrypted",
MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
} else {
context.getHarmonySharedPreferences(prefsName)
}
override val editor: SharedPreferences.Editor = sharedPreferences.edit()
override val source: String = TestSource.HARMONY
override suspend fun awaitUntilReady() {
delay(1000) // Prevent thrashing of the service
context.startService(Intent(context, HarmonyRemoteTestRunnerService::class.java).apply {
putExtra(PREFS_NAME_KEY, prefsName)
putExtra(USE_ENCRYPTION_KEY, isEncrypted)
putExtra(ITERATIONS_KEY, iterations)
putExtra(REMOTE_MESSENGER_KEY, incomingMessenger)
})
isReadyIndicator.withLock {
logEvent(Log.INFO, LOG_TAG, "harmony is ready")
}
}
override suspend fun reset() {
try {
isReadyIndicator.unlock()
} catch (e: IllegalStateException) {
} finally {
isReadyIndicator.lock()
}
try {
gotResultsIndicator.unlock()
} catch (e: IllegalStateException) {
} finally {
gotResultsIndicator.lock()
}
withContext(Dispatchers.IO) {
sharedPreferences.edit(true) { clear() }
}
}
override suspend fun awaitResults() {
delay(3000) // Give time for results to populate on other process
context.stopService(Intent(context, HarmonyRemoteTestRunnerService::class.java))
gotResultsIndicator.withLock {
logEvent(Log.INFO, LOG_TAG, "got all harmony results")
}
}
companion object {
private const val LOG_TAG = "HarmonyTestRunner"
}
}
class MMKVTestRunner(
private val context: Context,
private val prefsName: String,
private val iterations: Int,
isAsync: Boolean,
private val isEncrypted: Boolean
) : TestRunner(iterations = iterations, isAsync = isAsync, isEncrypted = isEncrypted) {
override val source: String = TestSource.MMKV
init {
MMKV.initialize(context)
}
private val mmkv = if (isEncrypted) {
requireNotNull(MMKV.mmkvWithID("$prefsName-encrypted", MMKV.MULTI_PROCESS_MODE, MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)))
} else {
requireNotNull(MMKV.mmkvWithID(prefsName, MMKV.MULTI_PROCESS_MODE))
}
private val isReadyIndicator = Mutex(true)
private val gotResultsIndicator = Mutex(true)
private val incomingMessenger = Messenger(Handler(Looper.getMainLooper()) { msg ->
when (msg.what) {
ACK_EVENT -> isReadyIndicator.unlock()
LOG_EVENT -> {
val log = msg.data.let {
it.classLoader = LogEvent::class.java.classLoader
return@let it.getParcelable<LogEvent>(LOG_KEY) ?: return@Handler true
}
runBlocking { logEvent(log) }
}
RESULTS_EVENT -> {
val ipcLongArray = msg.data.getLongArray(RESULTS_KEY)
?: throw IllegalArgumentException("No results available")
if (ipcLongArray.any { it == -1L }) {
runBlocking {
logEvent(Log.ERROR, LOG_TAG, "IPC did not set all data")
}
}
testData.add(
IpcTestData(
parentTestEntityId = testRunnerId,
results = ipcLongArray
)
)
runBlocking {
logEvent(
LogEvent(
priority = Log.INFO,
tag = LOG_TAG,
message = "avg ipc: ${ipcLongArray.average() / 1_000_000} ms"
)
)
}
gotResultsIndicator.unlock()
}
}
return@Handler true
})
override suspend fun awaitUntilReady() {
delay(1000) // Prevent thrashing of the service
context.startService(Intent(context, MMKVRemoteTestRunnerService::class.java).apply {
putExtra(PREFS_NAME_KEY, prefsName)
putExtra(USE_ENCRYPTION_KEY, isEncrypted)
putExtra(ITERATIONS_KEY, iterations)
putExtra(REMOTE_MESSENGER_KEY, incomingMessenger)
})
isReadyIndicator.withLock {
logEvent(Log.INFO, LOG_TAG, "mmkv is ready")
}
}
override suspend fun reset() {
try {
isReadyIndicator.unlock()
} catch (e: IllegalStateException) {
} finally {
isReadyIndicator.lock()
}
try {
gotResultsIndicator.unlock()
} catch (e: IllegalStateException) {
} finally {
gotResultsIndicator.lock()
}
withContext(Dispatchers.IO) {
mmkv.clearAll()
}
}
override suspend fun awaitResults() {
delay(3000) // Give time for results to populate on other process
context.stopService(Intent(context, MMKVRemoteTestRunnerService::class.java))
gotResultsIndicator.withLock {
logEvent(Log.INFO, LOG_TAG, "got all mmkv results")
}
}
override fun write(key: String, value: String, isAsync: Boolean) {
mmkv.encode(key, value)
}
override fun read(key: String) {
mmkv.decodeString(key)
}
companion object {
private const val LOG_TAG = "MMKVTestRunner"
}
}
class TraySharedPrefsRunner(
private val context: Context,
private val prefsName: String,
private val iterations: Int,
isAsync: Boolean,
private val isEncrypted: Boolean
) : TestRunner(iterations = iterations, isAsync = isAsync, isEncrypted = isEncrypted) {
private val trayPreferences = AppPreferences(context, prefsName)
private val isReadyIndicator = Mutex(true)
private val gotResultsIndicator = Mutex(true)
private val incomingMessenger = Messenger(Handler(Looper.getMainLooper()) { msg ->
when (msg.what) {
ACK_EVENT -> isReadyIndicator.unlock()
LOG_EVENT -> {
val log = msg.data.let {
it.classLoader = LogEvent::class.java.classLoader
return@let it.getParcelable<LogEvent>(LOG_KEY) ?: return@Handler true
}
runBlocking { logEvent(log) }
}
RESULTS_EVENT -> {
val ipcLongArray = msg.data.getLongArray(RESULTS_KEY)
?: throw IllegalArgumentException("No results available")
if (ipcLongArray.any { it == -1L }) {
runBlocking {
logEvent(Log.ERROR, LOG_TAG, "IPC did not set all data")
}
}
testData.add(
IpcTestData(
parentTestEntityId = testRunnerId,
results = ipcLongArray
)
)
runBlocking {
logEvent(
LogEvent(
priority = Log.INFO,
tag = LOG_TAG,
message = "avg ipc: ${ipcLongArray.average() / 1_000_000} ms"
)
)
}
gotResultsIndicator.unlock()
}
}
return@Handler true
})
override val source: String = TestSource.TRAY
override suspend fun awaitUntilReady() {
delay(1000) // Prevent thrashing of the service
context.startService(Intent(context, TrayRemoteTestRunnerService::class.java).apply {
putExtra(PREFS_NAME_KEY, prefsName)
putExtra(USE_ENCRYPTION_KEY, isEncrypted)
putExtra(ITERATIONS_KEY, iterations)
putExtra(REMOTE_MESSENGER_KEY, incomingMessenger)
})
isReadyIndicator.withLock {
logEvent(Log.INFO, LOG_TAG, "tray is ready")
}
}
override suspend fun reset() {
try {
isReadyIndicator.unlock()
} catch (e: IllegalStateException) {
} finally {
isReadyIndicator.lock()
}
try {
gotResultsIndicator.unlock()
} catch (e: IllegalStateException) {
} finally {
gotResultsIndicator.lock()
}
withContext(Dispatchers.IO) {
trayPreferences.clear()
}
}
override suspend fun awaitResults() {
delay(3000) // Give time for results to populate on other process
context.stopService(Intent(context, TrayRemoteTestRunnerService::class.java))
gotResultsIndicator.withLock {
logEvent(Log.INFO, LOG_TAG, "got all tray results")
}
}
override fun write(key: String, value: String, isAsync: Boolean) {
trayPreferences.put(key, value)
}
override fun read(key: String) {
trayPreferences.getString(key)
}
companion object {
private const val LOG_TAG = "TraySharedPrefsRunner"
}
}
class AppPreferences(context: Context, module: String) : TrayPreferences(context, module, 1)