-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathSampleAppLiveFireTests.cs
More file actions
726 lines (595 loc) · 31.2 KB
/
Copy pathSampleAppLiveFireTests.cs
File metadata and controls
726 lines (595 loc) · 31.2 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
#nullable enable
using System;
using System.Collections;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;
using UnityEngine.UIElements;
namespace Immutable.Audience.Samples.SampleApp.Tests
{
[TestFixture]
internal class SampleAppLiveFireTests
{
// Cached allocations for fixed-delay yields (SDK needs time to flush
// rather than "wait up to N seconds for a condition"). Static readonly
// so the WaitForSecondsRealtime instance is created once per class load.
private static readonly WaitForSecondsRealtime _twoSeconds = new(2f);
private VisualElement? _root;
private string _key = "";
[SetUp]
public void SetUp()
{
// ImmutableAudience is a static; tests must reset between runs.
// ResetState is internal — reached via reflection (BindingFlags.NonPublic
// bypasses C# access checks; no InternalsVisibleTo required).
var t = typeof(ImmutableAudience);
var m = t.GetMethod("ResetState",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
m?.Invoke(null, null);
// ResetState only clears in-memory state. The SDK persists consent
// (and identity/queue) to disk under <persistentDataPath>/imtbl_audience.
// Without wiping it, a SetConsent(None) from a prior test leaks into
// the next test's Init via ConsentStore.Load.
var sdkDir = System.IO.Path.Combine(Application.persistentDataPath, SampleAppUi.SdkPersistedDirName);
if (System.IO.Directory.Exists(sdkDir))
System.IO.Directory.Delete(sdkDir, recursive: true);
// Unity's bundled Mono runtime ships a curated root-CA set that
// does not include the chain api.sandbox.immutable.com presents,
// so HttpClient under Mono2x raises "SSL connection could not be
// established" on every Flush. The cert is valid; only Mono's
// verification fails. IL2CPP uses the OS CA store and is fine.
//
// Bypass cert validation IN THE TEST PROCESS ONLY so the same
// suite exercises both backends. Production SDK code is
// untouched. Acceptable risk: this test process talks only to
// sandbox; live-fire payloads carry no real user data.
System.Net.ServicePointManager.ServerCertificateValidationCallback =
(_, _, _, _) => true;
_root = null;
}
// ---- Helpers shared by every test ----
// Loads the SampleApp scene, types the env-var key into publishable-key,
// optionally sets initial-consent (defaults to Anonymous via dropdown),
// runs the configure callback for any extra setup (base-url, flush-size,
// debug toggle, etc.), clicks btn-init, and waits for the INIT@Ok row.
// Stashes the root VisualElement on _root so callers can drive
// subsequent buttons.
private IEnumerator LoadAndInit(string? initialConsent = null, Action<VisualElement>? configure = null)
{
yield return LoadSceneOnly();
_root!.Q<TextField>(SampleAppUi.Setup.PublishableKey).value = _key;
if (!string.IsNullOrEmpty(initialConsent))
_root.Q<DropdownField>(SampleAppUi.Setup.InitialConsent).value = initialConsent;
configure?.Invoke(_root);
_root.Q<Button>(SampleAppUi.Buttons.Init).Click();
yield return SampleAppTestHelpers.WaitForLogEntry(_root, SampleAppUi.LogLabels.Init, LogLevels.Ok, 5f);
}
// Scene load + AudienceSample lookup + root capture, without clicking
// btn-init. Useful for tests that need to inspect pre-init UI state
// (e.g. prod-warning visibility for non-test keys).
private IEnumerator LoadSceneOnly()
{
_key = Environment.GetEnvironmentVariable(SampleAppUi.EnvKey) ?? "";
Assume.That(_key, Is.Not.Null.And.Not.Empty,
$"{SampleAppUi.EnvKey} must be set for live-fire tests. Skipping.");
yield return SceneManager.LoadSceneAsync(SampleAppUi.SceneName, LoadSceneMode.Single);
yield return null; // one extra frame for Awake/InitializeUi
#if UNITY_2022_2_OR_NEWER
var sample = UnityEngine.Object.FindFirstObjectByType<AudienceSample>(FindObjectsInactive.Include);
#else
var sample = UnityEngine.Object.FindObjectOfType<AudienceSample>(includeInactive: true);
#endif
Assume.That(sample, Is.Not.Null, "AudienceSample MonoBehaviour expected in scene");
_root = sample!.GetComponent<UIDocument>().rootVisualElement;
}
// Clicks btn-flush, waits for the flush() Ok row, then asserts the log
// pane has zero Err entries. label (optional) prefixes the assertion
// message so failures point at which test step misbehaved.
private IEnumerator FlushAndAssertNoErrors(string label = "")
{
_root!.Q<Button>(SampleAppUi.Buttons.Flush).Click();
yield return SampleAppTestHelpers.WaitForLogEntry(_root, SampleAppUi.LogLabels.Flush, LogLevels.Ok, 30f);
AssertNoErrors(label);
}
private void AssertNoErrors(string label = "")
{
var errors = SampleAppTestHelpers.CountLogEntriesAtLevel(_root!, LogLevels.Err);
var prefix = string.IsNullOrEmpty(label) ? "" : $"{label}: ";
Assert.Zero(errors,
$"{prefix}expected no error log entries; got {errors}. " +
$"Entries: {SampleAppTestHelpers.DescribeLogEntries(_root!)}");
}
// Clicks one of btn-consent-{none|anon|full} and waits for the
// setConsent() Ok row to confirm the SDK applied the transition.
private IEnumerator SetConsentVia(string consentButtonName)
{
_root!.Q<Button>(consentButtonName).Click();
yield return SampleAppTestHelpers.WaitForLogEntry(_root, SampleAppUi.LogLabels.SetConsent, LogLevels.Ok, 5f);
}
// ---- Tests ----
[UnityTest]
public IEnumerator InitTrackFlush_AgainstSandbox_FlushReportsOk()
{
yield return LoadAndInit();
// Page-view track via btn-page; the test doesn't wait on its row.
_root!.Q<Button>(SampleAppUi.Buttons.Page).Click();
yield return null;
yield return FlushAndAssertNoErrors();
}
[UnityTest]
public IEnumerator Event_Progression_FlushReportsOk()
{
// Progression's only required field is `status` (enum, defaults to "start").
yield return DriveTypedEventAndFlush(SampleAppUi.Buttons.TypedEvent("progression"));
}
[UnityTest]
public IEnumerator TypedEvent_Resource_FlushReportsOk()
{
yield return DriveTypedEventAndFlush(SampleAppUi.Buttons.TypedEvent("resource"), root =>
{
root.Q<TextField>(SampleAppUi.TypedEventField("resource", "currency")).value = "GOLD";
root.Q<TextField>(SampleAppUi.TypedEventField("resource", "amount")).value = "100";
});
}
[UnityTest]
public IEnumerator TypedEvent_Purchase_FlushReportsOk()
{
yield return DriveTypedEventAndFlush(SampleAppUi.Buttons.TypedEvent("purchase"), root =>
{
root.Q<TextField>(SampleAppUi.TypedEventField("purchase", "currency")).value = "USD";
root.Q<TextField>(SampleAppUi.TypedEventField("purchase", "value")).value = "9.99";
});
}
[UnityTest]
public IEnumerator TypedEvent_MilestoneReached_FlushReportsOk()
{
yield return DriveTypedEventAndFlush(SampleAppUi.Buttons.TypedEvent("milestone_reached"), root =>
{
root.Q<TextField>(SampleAppUi.TypedEventField("milestone_reached", "name")).value = "il2cpp_smoke";
});
}
// Shared driver: Init → fill required fields → click typed-event Send → Flush →
// assert no error rows. fillFields is null when the event has no required fields
// beyond defaults.
private IEnumerator DriveTypedEventAndFlush(
string typedButtonName, Action<VisualElement>? fillFields = null)
{
yield return LoadAndInit();
fillFields?.Invoke(_root!);
yield return null;
var btn = _root!.Q<Button>(typedButtonName);
Assert.IsNotNull(btn, $"expected button {typedButtonName} to exist after PopulateTypedEventAccordions");
btn.Click();
yield return null;
yield return FlushAndAssertNoErrors($"typed event {typedButtonName}");
}
[UnityTest]
public IEnumerator Identify_AndFlush_FlushReportsOk()
{
// Identify requires consent ≥ Full — set it on the initial-consent
// dropdown before Init rather than upgrading mid-test.
yield return LoadAndInit(initialConsent: SampleAppUi.Consent.Full);
_root!.Q<TextField>(SampleAppUi.IdentityFields.Id).value = "il2cpp-test-user-" + DateTime.UtcNow.Ticks;
_root.Q<Button>(SampleAppUi.Buttons.Identify).Click();
yield return null;
yield return FlushAndAssertNoErrors();
}
[UnityTest]
public IEnumerator Alias_AndFlush_FlushReportsOk()
{
yield return LoadAndInit(initialConsent: SampleAppUi.Consent.Full);
_root!.Q<TextField>(SampleAppUi.IdentityFields.AliasFromId).value = "anon-" + DateTime.UtcNow.Ticks;
_root.Q<TextField>(SampleAppUi.IdentityFields.AliasToId).value = "user-" + DateTime.UtcNow.Ticks;
_root.Q<Button>(SampleAppUi.Buttons.Alias).Click();
yield return null;
yield return FlushAndAssertNoErrors();
}
[UnityTest]
public IEnumerator SetConsent_None_PurgesQueueAndPersists()
{
// Init at default Anonymous; enqueue an event; revoke; flush — no errors.
yield return LoadAndInit();
_root!.Q<Button>(SampleAppUi.Buttons.Page).Click();
yield return null;
yield return SetConsentVia(SampleAppUi.Buttons.ConsentNone);
// Flushing after revocation should be a no-op (queue purged) — no error.
_root.Q<Button>(SampleAppUi.Buttons.Flush).Click();
yield return _twoSeconds;
AssertNoErrors();
}
[UnityTest]
public IEnumerator SetConsent_FullAfterAnonymous_AcceptsIdentify()
{
// Init at default Anonymous, then upgrade to Full so Identify is accepted.
yield return LoadAndInit();
yield return SetConsentVia(SampleAppUi.Buttons.ConsentFull);
_root!.Q<TextField>(SampleAppUi.IdentityFields.Id).value = "consent-test-" + DateTime.UtcNow.Ticks;
_root.Q<Button>(SampleAppUi.Buttons.Identify).Click();
yield return null;
yield return FlushAndAssertNoErrors();
}
[UnityTest]
public IEnumerator CustomTrack_WithDictionaryProps_FlushReportsOk()
{
yield return LoadAndInit();
// Custom event name + JSON props (the sample app parses props as JSON
// and forwards them as Dictionary<string, object> to ImmutableAudience.Track).
_root!.Q<TextField>(SampleAppUi.CustomEvent.Name).value = "il2cpp_smoke";
_root.Q<TextField>(SampleAppUi.CustomEvent.Props).value =
"{\"int_field\":42,\"str_field\":\"hello\",\"bool_field\":true,\"nested\":{\"a\":1}}";
_root.Q<Button>(SampleAppUi.Buttons.CustomEvent).Click();
yield return null;
yield return FlushAndAssertNoErrors();
}
// ---- Lifecycle / control-plane tests ----
[UnityTest]
public IEnumerator Shutdown_AfterTrack_NoErrors()
{
// Shutdown drains pending events to disk, joins the background drain
// thread, and disposes timers + HttpClient. IL2CPP can strip any of
// those if their types/methods aren't reachable from a root assembly.
yield return LoadAndInit();
_root!.Q<Button>(SampleAppUi.Buttons.Page).Click();
yield return null;
_root.Q<Button>(SampleAppUi.Buttons.Shutdown).Click();
yield return SampleAppTestHelpers.WaitForLogEntry(_root, SampleAppUi.LogLabels.Shutdown, LogLevels.Ok, 5f);
AssertNoErrors();
}
[UnityTest]
public IEnumerator Reset_RegeneratesAnonymousIdAndAcceptsTrack()
{
// Reset clears identity + queue and rolls a new anonymousId. A
// following Track must serialise with the new anonymousId and
// round-trip to sandbox without errors.
yield return LoadAndInit();
_root!.Q<Button>(SampleAppUi.Buttons.Page).Click();
yield return null;
_root.Q<Button>(SampleAppUi.Buttons.Reset).Click();
yield return SampleAppTestHelpers.WaitForLogEntry(_root, SampleAppUi.LogLabels.Reset, LogLevels.Ok, 5f);
_root.Q<Button>(SampleAppUi.Buttons.Page).Click();
yield return null;
yield return FlushAndAssertNoErrors();
}
[UnityTest]
public IEnumerator DeleteData_AcknowledgesFromBackend()
{
// DeleteData hits the control-plane HTTP endpoint, distinct from
// the event-batch POST. Catches IL2CPP strips on the control HttpClient
// path that the regular Flush tests don't exercise.
yield return LoadAndInit();
_root!.Q<Button>(SampleAppUi.Buttons.DeleteData).Click();
yield return SampleAppTestHelpers.WaitForLogEntry(_root, SampleAppUi.LogLabels.DeleteData, LogLevels.Ok, 30f);
AssertNoErrors();
}
[UnityTest]
public IEnumerator ReInit_AfterShutdown_AcceptsTrack()
{
// Shutdown clears _initialised; the same player must accept a
// second Init using the same publishable-key and resume Track.
// Catches IL2CPP strips on the lazy-init paths that only fire
// on second Init (e.g. timer recycling, HttpClient re-creation).
yield return LoadAndInit();
_root!.Q<Button>(SampleAppUi.Buttons.Shutdown).Click();
yield return SampleAppTestHelpers.WaitForLogEntry(_root, SampleAppUi.LogLabels.Shutdown, LogLevels.Ok, 5f);
_root.Q<Button>(SampleAppUi.Buttons.Init).Click();
// Two INIT@Ok rows now; WaitForLogEntry returns on the first
// match it sees, but the original is already in the log so poll
// by count until the second Ok row appears or the deadline elapses.
yield return null;
yield return SampleAppTestHelpers.WaitForCondition(
() => SampleAppTestHelpers.CountLogEntriesAtLevel(_root, LogLevels.Ok) > 1,
2f, "second INIT@Ok row after re-init");
Assert.Greater(SampleAppTestHelpers.CountLogEntriesAtLevel(_root, LogLevels.Ok), 1,
"expected a second INIT@Ok row after re-init");
_root.Q<Button>(SampleAppUi.Buttons.Page).Click();
yield return null;
yield return FlushAndAssertNoErrors();
}
[UnityTest]
public IEnumerator SetConsent_AnonymousFromFull_StripsUserIdFromTrack()
{
// Init at Full so Identify is allowed, then downgrade to Anonymous.
// Subsequent Track calls must succeed with the userId stripped from
// the wire payload (SDK behaviour); test asserts no Err entries
// appear, which means the strip path is intact under IL2CPP.
yield return LoadAndInit(initialConsent: SampleAppUi.Consent.Full);
_root!.Q<TextField>(SampleAppUi.IdentityFields.Id).value = "downgrade-user-" + DateTime.UtcNow.Ticks;
_root.Q<Button>(SampleAppUi.Buttons.Identify).Click();
yield return SampleAppTestHelpers.WaitForLogEntry(_root, SampleAppUi.LogLabels.Identify, LogLevels.Ok, 5f);
yield return SetConsentVia(SampleAppUi.Buttons.ConsentAnon);
_root.Q<Button>(SampleAppUi.Buttons.Page).Click();
yield return null;
yield return FlushAndAssertNoErrors();
}
[UnityTest]
public IEnumerator IdentifyTraits_AfterIdentify_FlushReportsOk()
{
// Identify(traits) requires an active identity (Identify first) and
// exercises the identity overload that takes a traits Dictionary —
// a different reflection/serialiser path than Identify(id) alone.
yield return LoadAndInit(initialConsent: SampleAppUi.Consent.Full);
_root!.Q<TextField>(SampleAppUi.IdentityFields.Id).value = "traits-user-" + DateTime.UtcNow.Ticks;
_root.Q<Button>(SampleAppUi.Buttons.Identify).Click();
yield return SampleAppTestHelpers.WaitForLogEntry(_root, SampleAppUi.LogLabels.Identify, LogLevels.Ok, 5f);
// traits-update is the post-Identify traits field (id-traits is the
// initial Identify path). btn-identify-traits reads traits-update.
_root.Q<TextField>(SampleAppUi.IdentityFields.TraitsUpdate).value = "{\"plan\":\"premium\",\"level\":42}";
_root.Q<Button>(SampleAppUi.Buttons.IdentifyTraits).Click();
yield return SampleAppTestHelpers.WaitForLogEntry(_root, SampleAppUi.LogLabels.IdentifyTraits, LogLevels.Ok, 5f);
yield return FlushAndAssertNoErrors();
}
// The remaining catalogue events have no typed factory in BuildTypedEvent
// and fall through to ImmutableAudience.Track(string, props). Worth
// exercising end-to-end so the catalogue UI's null-fallback path is
// covered under IL2CPP.
[UnityTest]
public IEnumerator TypedEvent_SignUp_FlushReportsOk()
{
yield return DriveTypedEventAndFlush(SampleAppUi.Buttons.TypedEvent("sign_up"));
}
[UnityTest]
public IEnumerator TypedEvent_SignIn_FlushReportsOk()
{
yield return DriveTypedEventAndFlush(SampleAppUi.Buttons.TypedEvent("sign_in"));
}
[UnityTest]
public IEnumerator TypedEvent_EmailAcquired_FlushReportsOk()
{
yield return DriveTypedEventAndFlush(SampleAppUi.Buttons.TypedEvent("email_acquired"));
}
[UnityTest]
public IEnumerator TypedEvent_WishlistAdd_FlushReportsOk()
{
yield return DriveTypedEventAndFlush(SampleAppUi.Buttons.TypedEvent("wishlist_add"), root =>
{
root.Q<TextField>(SampleAppUi.TypedEventField("wishlist_add", "gameId")).value = "il2cpp_game_1";
});
}
[UnityTest]
public IEnumerator TypedEvent_WishlistRemove_FlushReportsOk()
{
yield return DriveTypedEventAndFlush(SampleAppUi.Buttons.TypedEvent("wishlist_remove"), root =>
{
root.Q<TextField>(SampleAppUi.TypedEventField("wishlist_remove", "gameId")).value = "il2cpp_game_1";
});
}
[UnityTest]
public IEnumerator TypedEvent_GamePageViewed_FlushReportsOk()
{
yield return DriveTypedEventAndFlush(SampleAppUi.Buttons.TypedEvent("game_page_viewed"), root =>
{
root.Q<TextField>(SampleAppUi.TypedEventField("game_page_viewed", "gameId")).value = "il2cpp_game_1";
});
}
[UnityTest]
public IEnumerator TypedEvent_LinkClicked_FlushReportsOk()
{
yield return DriveTypedEventAndFlush(SampleAppUi.Buttons.TypedEvent("link_clicked"), root =>
{
root.Q<TextField>(SampleAppUi.TypedEventField("link_clicked", "url")).value = "https://example.com/il2cpp";
});
}
// ---- Init-config code paths ----
[UnityTest]
public IEnumerator Init_WithBaseUrlOverride_FlushReportsOk()
{
// Explicit BaseUrl skips the publishable-key prefix routing in
// Constants. Same target endpoint here, but the override branch is
// a different config setup path that IL2CPP could strip independently.
yield return LoadAndInit(configure: root =>
{
root.Q<TextField>(SampleAppUi.Setup.BaseUrl).value = SampleAppUi.SandboxBaseUrl;
});
_root!.Q<Button>(SampleAppUi.Buttons.Page).Click();
yield return null;
yield return FlushAndAssertNoErrors();
}
[UnityTest]
public IEnumerator Init_WithSubSecondFlushInterval_EmitsClampWarn()
{
// BuildAudienceConfig emits a Warn row when flushInterval < 1000ms,
// then clamps to 1s and continues. Verifies both the Warn-level log
// path and the clamp.
yield return LoadAndInit(configure: root =>
{
root.Q<TextField>(SampleAppUi.Setup.FlushInterval).value = "500";
});
var warns = SampleAppTestHelpers.CountLogEntriesAtLevel(_root!, LogLevels.Warn);
Assert.Greater(warns, 0,
"expected at least one Warn row for sub-second flushInterval. " +
$"Entries: {SampleAppTestHelpers.DescribeLogEntries(_root!)}");
AssertNoErrors();
}
[UnityTest]
public IEnumerator Init_WithCustomFlushSize_FlushReportsOk()
{
yield return LoadAndInit(configure: root =>
{
root.Q<TextField>(SampleAppUi.Setup.FlushSize).value = "5";
});
_root!.Q<Button>(SampleAppUi.Buttons.Page).Click();
yield return null;
yield return FlushAndAssertNoErrors();
}
[UnityTest]
public IEnumerator Init_WithDebugDisabled_FlushReportsOk()
{
// Debug toggle controls the SDK's Log.Enabled. Off path is the
// production default; verify it still functions end-to-end.
yield return LoadAndInit(configure: root =>
{
root.Q<Toggle>(SampleAppUi.Setup.Debug).value = false;
});
_root!.Q<Button>(SampleAppUi.Buttons.Page).Click();
yield return null;
yield return FlushAndAssertNoErrors();
}
[UnityTest]
public IEnumerator MultiEvent_SingleFlush_NoErrors()
{
// Five page Tracks queued up, single Flush. Exercises queue
// batching + gzip + multi-event payload serialisation under IL2CPP.
yield return LoadAndInit();
for (var i = 0; i < 5; i++)
{
_root!.Q<Button>(SampleAppUi.Buttons.Page).Click();
yield return null;
}
yield return FlushAndAssertNoErrors();
}
[UnityTest]
public IEnumerator Flush_EmptyQueue_NoErrors()
{
// Flush with nothing queued. The batch path must short-circuit
// cleanly without dispatching an HTTP request.
yield return LoadAndInit();
yield return FlushAndAssertNoErrors();
}
[UnityTest]
public IEnumerator PersistedConsent_OverridesDropdownOnReInit()
{
// After SetConsent(Full), Shutdown, and a second Init at the
// dropdown's default (Anonymous), the SDK must re-load Full from
// disk. Init's log body echoes config (always reads dropdown), so
// assert against the status-consent label which reflects the
// SDK's runtime CurrentConsent.
yield return LoadAndInit();
yield return SetConsentVia(SampleAppUi.Buttons.ConsentFull);
_root!.Q<Button>(SampleAppUi.Buttons.Shutdown).Click();
yield return SampleAppTestHelpers.WaitForLogEntry(_root, SampleAppUi.LogLabels.Shutdown, LogLevels.Ok, 5f);
// Dropdown is still at default Anonymous; re-Init must read disk.
_root.Q<Button>(SampleAppUi.Buttons.Init).Click();
// Poll until OnSdkStateChanged + RefreshStatusBar has run and the
// label reflects the re-loaded consent level.
yield return SampleAppTestHelpers.WaitForCondition(
() => _root.Q<Label>(SampleAppUi.StatusBar.Consent).text == SampleAppUi.Consent.Full,
2f, "status-consent label to show Full after re-Init from persisted consent");
var statusConsent = _root.Q<Label>(SampleAppUi.StatusBar.Consent).text;
Assert.AreEqual(SampleAppUi.Consent.Full, statusConsent,
$"expected re-Init to restore Full consent from disk; status-consent shows '{statusConsent}'. " +
$"Entries: {SampleAppTestHelpers.DescribeLogEntries(_root)}");
AssertNoErrors();
}
// ---- Sample-app UI plumbing ----
// These verify the SAMPLE APP's reactivity, not SDK code paths. They
// catch sample-app regressions that would mask real SDK issues
// (e.g. status bar showing stale state) — also exercise the
// RefreshStatusBar / RefreshConsentPills / RefreshIdentityPanel paths
// under IL2CPP.
[UnityTest]
public IEnumerator StatusBar_ReflectsConsentAfterInit()
{
yield return LoadAndInit(initialConsent: SampleAppUi.Consent.Full);
yield return null; // OnSdkStateChanged → RefreshStatusBar
Assert.AreEqual(SampleAppUi.Consent.Full, _root!.Q<Label>(SampleAppUi.StatusBar.Consent).text);
}
[UnityTest]
public IEnumerator StatusBar_PopulatesAnonymousIdAfterInit()
{
yield return LoadAndInit();
yield return null;
var anon = _root!.Q<Label>(SampleAppUi.StatusBar.Anon).text;
Assert.AreNotEqual(SampleAppUi.StatusBar.EmptyText, anon,
"status-anon should contain a non-empty anonymousId after Init");
Assert.IsNotEmpty(anon);
}
[UnityTest]
public IEnumerator StatusBar_QueueSizeIncrementsAfterTrack()
{
// Init auto-fires session_start + game_launch so the queue is
// already non-zero by the time the status label paints. Capture
// the baseline and assert btn-page bumps it by at least one.
yield return LoadAndInit();
yield return null;
var queueLabel = _root!.Q<Label>(SampleAppUi.StatusBar.Queue);
int.TryParse(queueLabel.text, out var baseline);
_root.Q<Button>(SampleAppUi.Buttons.Page).Click();
yield return null;
var deadline = Time.realtimeSinceStartup + 2f;
while (Time.realtimeSinceStartup < deadline)
{
if (int.TryParse(queueLabel.text, out var current) && current > baseline)
yield break;
yield return null;
}
int.TryParse(queueLabel.text, out var finalCount);
Assert.Greater(finalCount, baseline,
$"queue should grow past baseline {baseline} after btn-page Track; got {finalCount}");
}
[UnityTest]
public IEnumerator ClearLog_RemovesAllRows()
{
yield return LoadAndInit();
var logView = _root!.Q<ScrollView>(SampleAppUi.LogScrollView);
Assert.Greater(logView.contentContainer.childCount, 0,
"log should contain READY + INIT rows after LoadAndInit");
_root.Q<Button>(SampleAppUi.Buttons.ClearLog).Click();
yield return null;
Assert.AreEqual(0, logView.contentContainer.childCount,
"btn-clear-log should remove all rows");
}
[UnityTest]
public IEnumerator TabNav_ClickingTabConsent_ActivatesPanel()
{
yield return LoadSceneOnly();
// panel-setup is active by default; tab-consent should swap to panel-consent.
_root!.Q<Button>(SampleAppUi.Tabs.Consent).Click();
yield return null;
Assert.IsTrue(_root.Q<VisualElement>(SampleAppUi.Panels.Consent).ClassListContains(SampleAppUi.ActiveClass),
"panel-consent should have 'active' class after clicking tab-consent");
Assert.IsFalse(_root.Q<VisualElement>(SampleAppUi.Panels.Setup).ClassListContains(SampleAppUi.ActiveClass),
"panel-setup should lose 'active' when switching away");
}
[UnityTest]
public IEnumerator ConsentPill_ActiveStateMirrorsSdkLevel()
{
yield return LoadAndInit();
yield return null;
var anonPill = _root!.Q<Button>(SampleAppUi.Buttons.ConsentAnon);
var fullPill = _root.Q<Button>(SampleAppUi.Buttons.ConsentFull);
Assert.IsTrue(anonPill.ClassListContains(SampleAppUi.ActiveClass),
"anon pill should be active right after Init at default Anonymous");
Assert.IsFalse(fullPill.ClassListContains(SampleAppUi.ActiveClass));
yield return SetConsentVia(SampleAppUi.Buttons.ConsentFull);
yield return null;
Assert.IsTrue(fullPill.ClassListContains(SampleAppUi.ActiveClass),
"full pill should be active after switching consent to Full");
Assert.IsFalse(anonPill.ClassListContains(SampleAppUi.ActiveClass));
}
[UnityTest]
public IEnumerator IdentityPanel_PopulatesUserIdAfterIdentify()
{
yield return LoadAndInit(initialConsent: SampleAppUi.Consent.Full);
var userId = "panel-user-" + DateTime.UtcNow.Ticks;
_root!.Q<TextField>(SampleAppUi.IdentityFields.Id).value = userId;
_root.Q<Button>(SampleAppUi.Buttons.Identify).Click();
yield return SampleAppTestHelpers.WaitForLogEntry(_root, SampleAppUi.LogLabels.Identify, LogLevels.Ok, 5f);
yield return null; // RefreshIdentityPanel
Assert.AreEqual(userId, _root.Q<Label>(SampleAppUi.IdentityPanel.UserId).text,
"identity-user-id label should reflect ImmutableAudience.UserId after Identify");
}
[UnityTest]
public IEnumerator ProdWarning_HiddenForTestKey()
{
// The default env-var key is a test key (pk_imapik-test-…). The
// prod-warning banner should stay hidden after RefreshStatusBar.
yield return LoadSceneOnly();
_root!.Q<TextField>(SampleAppUi.Setup.PublishableKey).value = _key;
yield return null;
Assert.IsTrue(_root.Q<Label>(SampleAppUi.ProdWarning).ClassListContains(SampleAppUi.HiddenClass),
"prod-warning should be hidden when the publishable-key is a test key");
}
[UnityTest]
public IEnumerator ProdWarning_VisibleForNonTestKey()
{
// A key without the "test-" segment looks production. Don't actually
// Init so we don't live-fire to prod; just verify the warning UI.
yield return LoadSceneOnly();
_root!.Q<TextField>(SampleAppUi.Setup.PublishableKey).value = "pk_imapik-fakeprod-zzzz";
yield return null;
Assert.IsFalse(_root.Q<Label>(SampleAppUi.ProdWarning).ClassListContains(SampleAppUi.HiddenClass),
"prod-warning should be visible when the publishable-key looks like a prod key");
}
}
}