-
Notifications
You must be signed in to change notification settings - Fork 219
/
NimbusTests.kt
722 lines (631 loc) · 28.4 KB
/
NimbusTests.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
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.experiments.nimbus
import android.content.Context
import android.util.Log
import androidx.test.core.app.ApplicationProvider
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import mozilla.telemetry.glean.BuildInfo
import mozilla.telemetry.glean.Glean
import mozilla.telemetry.glean.config.Configuration
import mozilla.telemetry.glean.net.HttpStatus
import mozilla.telemetry.glean.net.PingUploader
import mozilla.telemetry.glean.testing.GleanTestRule
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import org.mozilla.experiments.nimbus.GleanMetrics.NimbusEvents
import org.mozilla.experiments.nimbus.GleanMetrics.NimbusHealth
import org.mozilla.experiments.nimbus.internal.EnrollmentChangeEvent
import org.mozilla.experiments.nimbus.internal.EnrollmentChangeEventType
import org.robolectric.RobolectricTestRunner
import java.util.Calendar
import java.util.concurrent.Executors
@RunWith(RobolectricTestRunner::class)
class NimbusTests {
private val context: Context
get() = ApplicationProvider.getApplicationContext()
private val appInfo = NimbusAppInfo(
appName = "NimbusUnitTest",
channel = "test",
)
private val deviceInfo = NimbusDeviceInfo(
localeTag = "en-GB",
)
private val packageName = context.packageName
private val nimbusDelegate = NimbusDelegate(
dbScope = CoroutineScope(Executors.newSingleThreadExecutor().asCoroutineDispatcher()),
fetchScope = CoroutineScope(Executors.newSingleThreadExecutor().asCoroutineDispatcher()),
updateScope = null,
logger = { Log.i("NimbusTest", it) },
errorReporter = { message, e -> Log.e("NimbusTest", message, e) },
)
private val nimbus = createNimbus()
private fun createNimbus(coenrollingFeatureIds: List<String> = listOf()) = Nimbus(
context = context,
appInfo = appInfo,
coenrollingFeatureIds = coenrollingFeatureIds,
server = null,
deviceInfo = deviceInfo,
observer = null,
delegate = nimbusDelegate,
)
@get:Rule
val gleanRule = GleanTestRule(context)
@Before
fun setupGlean() {
val buildInfo = BuildInfo(versionCode = "0.0.1", versionName = "0.0.1", buildDate = Calendar.getInstance())
// Glean needs to be initialized for the experiments API to accept enrollment events, so we
// init it with a mock client so we don't upload anything.
val mockClient: PingUploader = mock()
`when`(mockClient.upload(any(), any(), any())).thenReturn(
HttpStatus(200),
)
Glean.initialize(
context,
true,
Configuration(
httpClient = mockClient,
),
buildInfo,
)
}
@Test
fun `recordExperimentTelemetry correctly records the experiment and branch`() {
// Create a list of experiments to test the telemetry enrollment recording
val enrolledExperiments = listOf(
EnrolledExperiment(
slug = "test-experiment",
featureIds = listOf(),
branchSlug = "test-branch",
userFacingDescription = "A test experiment for testing experiments",
userFacingName = "Test Experiment",
),
)
nimbus.recordExperimentTelemetry(experiments = enrolledExperiments)
assertTrue(Glean.testIsExperimentActive("test-experiment"))
val experimentData = Glean.testGetExperimentData("test-experiment")
assertEquals("test-branch", experimentData.branch)
}
@Test
fun `recordExperimentTelemetryEvents records telemetry`() {
// Create a bespoke list of events to record, one of each type, all with the same parameters
val events = listOf(
EnrollmentChangeEvent(
experimentSlug = "test-experiment",
branchSlug = "test-branch",
reason = "test-reason",
change = EnrollmentChangeEventType.ENROLLMENT,
),
EnrollmentChangeEvent(
experimentSlug = "test-experiment",
branchSlug = "test-branch",
reason = "test-reason",
change = EnrollmentChangeEventType.UNENROLLMENT,
),
EnrollmentChangeEvent(
experimentSlug = "test-experiment",
branchSlug = "test-branch",
reason = "test-reason",
change = EnrollmentChangeEventType.DISQUALIFICATION,
),
)
// Record the experiments in Glean
nimbus.recordExperimentTelemetryEvents(events)
// Use the Glean test API to check the recorded metrics
// Enrollment
assertNotNull("Event must have a value", NimbusEvents.enrollment.testGetValue())
val enrollmentEvents = NimbusEvents.enrollment.testGetValue()!!
assertEquals("Event count must match", enrollmentEvents.count(), 1)
val enrollmentEventExtras = enrollmentEvents.first().extra!!
assertEquals(
"Experiment slug must match",
"test-experiment",
enrollmentEventExtras["experiment"],
)
assertEquals("Experiment branch must match", "test-branch", enrollmentEventExtras["branch"])
// Unenrollment
assertNotNull("Event must have a value", NimbusEvents.unenrollment.testGetValue())
val unenrollmentEvents = NimbusEvents.unenrollment.testGetValue()!!
assertEquals("Event count must match", unenrollmentEvents.count(), 1)
val unenrollmentEventExtras = unenrollmentEvents.first().extra!!
assertEquals(
"Experiment slug must match",
"test-experiment",
unenrollmentEventExtras["experiment"],
)
assertEquals(
"Experiment branch must match",
"test-branch",
unenrollmentEventExtras["branch"],
)
// Disqualification
assertNotNull("Event must have a value", NimbusEvents.disqualification.testGetValue())
val disqualificationEvents = NimbusEvents.disqualification.testGetValue()!!
assertEquals("Event count must match", disqualificationEvents.count(), 1)
val disqualificationEventExtras = disqualificationEvents.first().extra!!
assertEquals(
"Experiment slug must match",
"test-experiment",
disqualificationEventExtras["experiment"],
)
assertEquals(
"Experiment branch must match",
"test-branch",
disqualificationEventExtras["branch"],
)
}
@Ignore // until the activation event is enabled by default.
@Test
fun `getFeatureVariables records activation telemetry`() {
// Load the experiment in nimbus so and optIn so that it will be active. This is necessary
// because recordExposure checks for active experiments before recording.
nimbus.setUpTestExperiments(packageName, appInfo)
// Assert that there are no events to start with
assertNull(
"There must not be any pre-existing events",
NimbusEvents.activation.testGetValue(),
)
nimbus.getVariables("missing_feature", recordExposureEvent = false)
// Missing feature does not call activation event
assertNull(
"There must not be any events for missing_features",
NimbusEvents.activation.testGetValue(),
)
nimbus.getVariables("about_welcome", recordExposureEvent = false)
// Existing feature does call activation event
val events = NimbusEvents.activation.testGetValue()
assertNotNull(
"There must be an activation event for a feature under experiment",
events,
)
assertEquals("Exactly one activation event", events!!.size, 1)
val extras = events.first().extra!!
assertEquals("test-branch", extras["branch"])
assertEquals("test-experiment", extras["experiment"])
assertEquals("about_welcome", extras["feature_id"])
}
@Test
fun `getFeatureVariables for coenrolling feature does not record activation telemetry`() {
// Load the experiment in nimbus so and optIn so that it will be active. This is necessary
// because recordExposure checks for active experiments before recording.
val nimbus = createNimbus(coenrollingFeatureIds = listOf("about_welcome"))
nimbus.setUpTestExperiments(packageName, appInfo)
// Assert that there are no events to start with
assertNull(
"There must not be any pre-existing events",
NimbusEvents.activation.testGetValue(),
)
nimbus.getVariables("missing_feature", recordExposureEvent = false)
// Missing feature does not call activation event
assertNull(
"There must not be any events for missing_features",
NimbusEvents.activation.testGetValue(),
)
nimbus.getVariables("about_welcome", recordExposureEvent = false)
// Coenrolling feature does not call activation event
assertNull(
"There must not be any events for coenrolling feature",
NimbusEvents.activation.testGetValue(),
)
}
@Test
fun `recordExposure from feature records telemetry`() {
// Load the experiment in nimbus so and optIn so that it will be active. This is necessary
// because recordExposure checks for active experiments before recording.
nimbus.setUpTestExperiments(packageName, appInfo)
// Assert that there are no events to start with
assertNull(
"There must not be any pre-existing events",
NimbusEvents.exposure.testGetValue(),
)
// Record a valid exposure event in Glean that matches the featureId from the test experiment
nimbus.recordExposureOnThisThread("about_welcome", null)
// Use the Glean test API to check that the valid event is present
assertNotNull("Event must have a value", NimbusEvents.exposure.testGetValue())
val exposureEvents = NimbusEvents.exposure.testGetValue()!!
assertEquals("Event count must match", exposureEvents.count(), 1)
val exposureEventExtras = exposureEvents.first().extra!!
assertEquals(
"Experiment slug must match",
"test-experiment",
exposureEventExtras["experiment"],
)
assertEquals("Experiment branch must match", "test-branch", exposureEventExtras["branch"])
// Attempt to record an event for a non-existent or feature we are not enrolled in an
// experiment in to ensure nothing is recorded.
nimbus.recordExposureOnThisThread("not-a-feature", null)
// Verify the invalid event was ignored by checking again that the valid event is still the only
// event, and that it hasn't changed any of its extra properties.
assertNotNull("Event must have a value", NimbusEvents.exposure.testGetValue())
val exposureEventsTryTwo = NimbusEvents.exposure.testGetValue()!!
assertEquals("Event count must match", exposureEventsTryTwo.count(), 1)
val exposureEventExtrasTryTwo = exposureEventsTryTwo.first().extra!!
assertEquals(
"Experiment slug must match",
"test-experiment",
exposureEventExtrasTryTwo["experiment"],
)
assertEquals(
"Experiment branch must match",
"test-branch",
exposureEventExtrasTryTwo["branch"],
)
}
@Test
fun `recordExposure from experiment slug records telemetry`() {
// Load the experiment in nimbus so and optIn so that it will be active. This is necessary
// because recordExposure checks for active experiments before recording.
nimbus.setUpTestExperiments(packageName, appInfo)
// Assert that there are no events to start with
assertNull(
"There must not be any pre-existing events",
NimbusEvents.exposure.testGetValue(),
)
// Record a valid exposure event in Glean that matches the featureId from the test experiment
nimbus.recordExposureOnThisThread("about_welcome", "test-experiment")
// Use the Glean test API to check that the valid event is present
assertNotNull("Event must have a value", NimbusEvents.exposure.testGetValue())
val exposureEvents = NimbusEvents.exposure.testGetValue()!!
assertEquals("Event count must match", exposureEvents.count(), 1)
val exposureEventExtras = exposureEvents.first().extra!!
assertEquals(
"Experiment slug must match",
"test-experiment",
exposureEventExtras["experiment"],
)
assertEquals("Experiment branch must match", "test-branch", exposureEventExtras["branch"])
// Attempt to record an event for a non-existent or feature we are not enrolled in an
// experiment in to ensure nothing is recorded.
nimbus.recordExposureOnThisThread("about_welcome", "not-an-experiment")
// Verify the invalid event was ignored by checking again that the valid event is still the only
// event, and that it hasn't changed any of its extra properties.
assertNotNull("Event must have a value", NimbusEvents.exposure.testGetValue())
val exposureEventsTryTwo = NimbusEvents.exposure.testGetValue()!!
assertEquals("Event count must match", exposureEventsTryTwo.count(), 1)
val exposureEventExtrasTryTwo = exposureEventsTryTwo.first().extra!!
assertEquals(
"Experiment slug must match",
"test-experiment",
exposureEventExtrasTryTwo["experiment"],
)
assertEquals(
"Experiment branch must match",
"test-branch",
exposureEventExtrasTryTwo["branch"],
)
}
@Test
fun `recordMalformedConfiguration records telemetry`() {
// Load the experiment in nimbus so and optIn so that it will be active. This is necessary
// because recordExposure checks for active experiments before recording.
nimbus.setUpTestExperiments(packageName, appInfo)
// Assert that there are no events to start with
assertNull(
"There must not be any pre-existing events",
NimbusEvents.malformedFeature.testGetValue(),
)
// Record a valid exposure event in Glean that matches the featureId from the test experiment
nimbus.recordMalformedConfigurationOnThisThread("about_welcome", "detail")
// Use the Glean test API to check that the valid event is present
assertNotNull("Event must have a value", NimbusEvents.malformedFeature.testGetValue())
val events = NimbusEvents.malformedFeature.testGetValue()!!
assertEquals("Event count must match", events.count(), 1)
val extras = events.first().extra!!
assertEquals(
"Experiment slug must match",
"test-experiment",
extras["experiment"],
)
assertEquals("Experiment branch must match", "test-branch", extras["branch"])
assertEquals("Feature Id must match", "about_welcome", extras["feature_id"])
assertEquals("Part Id must match", "detail", extras["part_id"])
}
@Test
fun `opting out generates the correct Glean event`() {
// Load the experiment in nimbus so and optIn so that it will be active. This is necessary
// because recordExposure checks for active experiments before recording.
nimbus.setUpTestExperiments(packageName, appInfo)
// Assert that there are no events to start with
assertNull(
"There must not be any pre-existing events",
NimbusEvents.disqualification.testGetValue(),
)
// Opt out of the specific experiment
nimbus.optOutOnThisThread("test-experiment")
// Use the Glean test API to check that the valid event is present
assertNotNull("Event must have a value", NimbusEvents.disqualification.testGetValue())
val disqualificationEvents = NimbusEvents.disqualification.testGetValue()!!
assertEquals("Event count must match", disqualificationEvents.count(), 1)
val enrollmentEventExtras = disqualificationEvents.first().extra!!
assertEquals(
"Experiment slug must match",
"test-experiment",
enrollmentEventExtras["experiment"],
)
assertEquals("Experiment branch must match", "test-branch", enrollmentEventExtras["branch"])
}
@Test
fun `toggling the global opt out generates the correct Glean event`() {
// Load the experiment in nimbus so and optIn so that it will be active. This is necessary
// because recordExposure checks for active experiments before recording.
nimbus.setUpTestExperiments(packageName, appInfo)
// Assert that there are no events to start with
assertNull(
"There must not be any pre-existing events",
NimbusEvents.disqualification.testGetValue(),
)
// Opt out of all experiments
nimbus.setGlobalUserParticipationOnThisThread(false)
// Use the Glean test API to check that the valid event is present
assertNotNull("Event must have a value", NimbusEvents.disqualification.testGetValue())
val disqualificationEvents = NimbusEvents.disqualification.testGetValue()!!
assertEquals("Event count must match", disqualificationEvents.count(), 1)
val enrollmentEventExtras = disqualificationEvents.first().extra!!
assertEquals(
"Experiment slug must match",
"test-experiment",
enrollmentEventExtras["experiment"],
)
assertEquals("Experiment branch must match", "test-branch", enrollmentEventExtras["branch"])
}
private fun Nimbus.setUpTestExperiments(appId: String, appInfo: NimbusAppInfo) {
this.setExperimentsLocallyOnThisThread(
testExperimentsJsonString(appInfo, appId),
)
this.applyPendingExperimentsOnThisThread()
}
private fun testExperimentsJsonString(
appInfo: NimbusAppInfo,
appId: String,
) = """
{"data": [{
"schemaVersion": "1.0.0",
"slug": "test-experiment",
"endDate": null,
"featureIds": ["about_welcome"],
"branches": [
{
"slug": "test-branch",
"ratio": 1,
"feature": {
"featureId": "about_welcome",
"enabled": false,
"value": {
"text": "OK then",
"number": 42
}
}
}
],
"probeSets": [],
"startDate": null,
"appName": "${appInfo.appName}",
"appId": "$appId",
"channel": "${appInfo.channel}",
"bucketConfig": {
"count": 10000,
"start": 0,
"total": 10000,
"namespace": "test-experiment",
"randomizationUnit": "nimbus_id"
},
"userFacingName": "Diagnostic test experiment",
"referenceBranch": "test-branch",
"isEnrollmentPaused": false,
"proposedEnrollment": 7,
"userFacingDescription": "This is a test experiment for diagnostic purposes.",
"id": "test-experiment",
"last_modified": 1602197324372
}]}
""".trimIndent()
@Test
fun `buildExperimentContext returns a valid context`() {
val expContext = nimbus.buildExperimentContext(context, appInfo, deviceInfo)
assertEquals(packageName, expContext.appId)
assertEquals(appInfo.appName, expContext.appName)
assertEquals(appInfo.channel, expContext.channel)
// If we could control more of the context here we might be able to better test it
}
@Test
fun `Smoke test receiving JSON features`() {
nimbus.setUpTestExperiments(packageName, appInfo)
// The test experiment has exactly one branch with 100% enrollment
// We should be able to get feature variables for the feature in this
// experiment.
val json = nimbus.getFeatureConfigVariablesJson("about_welcome")
assertNotNull(json)
assertEquals(42, json!!["number"])
assertEquals("OK then", json["text"])
val json2 = nimbus.getFeatureConfigVariablesJson("non-existent-feature")
assertNull(json2)
}
@Test
fun `getAvailableExperiments returns experiments for this appName even if the channel and appId don't match`() {
val appName = "TestApp"
val targetedAppInfo = NimbusAppInfo(appName = appName, channel = "production")
val developmentAppInfo = NimbusAppInfo(appName = appName, channel = "developer")
val nimbus = Nimbus(
context = context,
appInfo = developmentAppInfo,
coenrollingFeatureIds = listOf(),
server = null,
deviceInfo = deviceInfo,
delegate = nimbusDelegate,
)
nimbus.setUpTestExperiments("$packageName.nightly", targetedAppInfo)
val available: List<AvailableExperiment> = nimbus.getAvailableExperiments()
assertEquals(1, available.size)
assertEquals("test-experiment", available.first().slug)
}
@Test
fun `getAvailableExperiments does not return experiments that don't match the appName`() {
val targetedAppInfo = NimbusAppInfo(appName = "ThisApp", channel = "production")
val developmentAppInfo = NimbusAppInfo(appName = "ThatApp", channel = "production")
val nimbus = Nimbus(
context = context,
appInfo = developmentAppInfo,
coenrollingFeatureIds = listOf(),
server = null,
deviceInfo = deviceInfo,
delegate = nimbusDelegate,
)
nimbus.setUpTestExperiments(packageName, targetedAppInfo)
val available = nimbus.getAvailableExperiments()
assertTrue(available.isEmpty())
}
@Test
fun `applyLocalExperiments calls setLocalExperiments and applyPendingExperiments`() {
var completed = false
suspend fun getString(): String {
completed = true
return testExperimentsJsonString(appInfo, packageName)
}
val job = nimbus.applyLocalExperiments(::getString)
runBlocking {
job.join()
}
assertTrue(completed)
assertEquals(1, nimbus.getAvailableExperiments().size)
}
@Test
@Ignore
fun `in memory cache not ready logs an event`() {
// we haven't initialized nimbus at all, it should not log any error, but it should log an
// event
assertNull(nimbus.getFeatureConfigVariablesJson("dummy-experiment"))
assertNotNull(NimbusHealth.cacheNotReadyForFeature.testGetValue())
}
@Test
fun `applyLocalExperiments is cancellable`() {
var completed = false
suspend fun getString(): String =
throw CancellationException()
val job = nimbus.applyLocalExperiments(::getString)
runBlocking {
job.cancelAndJoin()
}
assertFalse(completed)
assertEquals(0, nimbus.getAvailableExperiments().size)
// this should not throw a DatabaseNotReadyException.
assertNull(nimbus.getFeatureConfigVariablesJson("dummy-experiment"))
assertNull(NimbusHealth.cacheNotReadyForFeature.testGetValue())
}
@Test
fun `applyLocalExperiments is cancellable with timeout`() {
var completed = false
suspend fun getString(): String {
delay(1000)
completed = true
return testExperimentsJsonString(appInfo, packageName)
}
val job = nimbus.applyLocalExperiments(::getString)
runBlocking {
job.joinOrTimeout(250L)
}
assertFalse(completed)
assertEquals(0, nimbus.getAvailableExperiments().size)
// this should not throw a DatabaseNotReadyException.
assertNull(nimbus.getFeatureConfigVariablesJson("dummy-experiment"))
assertNull(NimbusHealth.cacheNotReadyForFeature.testGetValue())
}
@Test
fun `test observers are not cancelled`() {
var observed = false
val observer = object : NimbusInterface.Observer {
override fun onUpdatesApplied(updated: List<org.mozilla.experiments.nimbus.internal.EnrolledExperiment>) {
runBlocking {
delay(250)
observed = true
}
}
}
val nimbus = Nimbus(
context = context,
appInfo = appInfo,
coenrollingFeatureIds = listOf(),
server = null,
deviceInfo = deviceInfo,
observer = observer,
delegate = nimbusDelegate,
)
suspend fun getString() = testExperimentsJsonString(appInfo, packageName)
val job = nimbus.applyLocalExperiments(::getString)
runBlocking {
job.joinOrTimeout(100)
}
assertTrue(observed)
}
@Test
fun `test observers are not cancelled even if loading is cancelled`() {
var observed = false
val observer = object : NimbusInterface.Observer {
override fun onUpdatesApplied(updated: List<org.mozilla.experiments.nimbus.internal.EnrolledExperiment>) {
runBlocking {
delay(250)
observed = true
}
}
}
val nimbus = Nimbus(
context = context,
appInfo = appInfo,
coenrollingFeatureIds = listOf(),
server = null,
deviceInfo = deviceInfo,
observer = observer,
delegate = nimbusDelegate,
)
suspend fun getString(): String = throw CancellationException()
val job = nimbus.applyLocalExperiments(::getString)
runBlocking {
job.joinOrTimeout(100)
}
assertTrue(observed)
}
@Test
@Ignore
fun `Nimbus records EnrollmentStatus metrics`() {
suspend fun getString(): String {
return testExperimentsJsonString(appInfo, packageName)
}
val job = nimbus.applyLocalExperiments(::getString)
runBlocking {
job.join()
}
assertEquals(1, nimbus.getAvailableExperiments().size)
assertNotNull("Event must have a value", NimbusEvents.enrollmentStatus.testGetValue())
val enrollmentStatusEvents = NimbusEvents.enrollmentStatus.testGetValue()!!
assertEquals("Event count must match", enrollmentStatusEvents.count(), 1)
val enrolledExtra = enrollmentStatusEvents[0].extra!!
assertEquals("branch must match", "test-branch", enrolledExtra["branch"])
assertEquals("slug must match", "test-experiment", enrolledExtra["slug"])
assertEquals("status must match", "Enrolled", enrolledExtra["status"])
assertEquals("reason must match", "Qualified", enrolledExtra["reason"])
assertEquals("errorString must match", null, enrolledExtra["error_string"])
assertEquals("conflictSlug must match", null, enrolledExtra["conflict_slug"])
}
}
// Mocking utilities, from mozilla.components.support.test
fun <T> any(): T {
Mockito.any<T>()
return uninitialized()
}
@Suppress("UNCHECKED_CAST")
fun <T> uninitialized(): T = null as T
inline fun <reified T : Any> mock(): T = Mockito.mock(T::class.java)