-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_theme.py
More file actions
989 lines (928 loc) · 44.2 KB
/
Copy pathtest_theme.py
File metadata and controls
989 lines (928 loc) · 44.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
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
#!/usr/bin/env python3
"""End-to-end tests for the material3 Keycloak theme.
Runs against a Keycloak started with dev/docker-compose.dev.yml (or the CI
equivalent). Environment:
BASE_URL default http://localhost:8080
EXPECT_PASSKEY "1" if the server supports the passkeys conditional UI
(Keycloak >= 26.2 with KC_FEATURES=passkeys), else "0"
Usage: python3 dev/test_theme.py
"""
import os
import sys
from pathlib import Path
from playwright.sync_api import sync_playwright
BASE = os.environ.get("BASE_URL", "http://localhost:8080")
EXPECT_PASSKEY = os.environ.get("EXPECT_PASSKEY", "1") == "1"
THEME = Path(__file__).resolve().parent.parent / "theme" / "material3"
AUTH_URL = (
f"{BASE}/realms/demo/protocol/openid-connect/auth"
"?client_id=account-console"
f"&redirect_uri={BASE}/realms/demo/account/".replace(":", "%3A").replace("/", "%2F")
)
FAILURES = []
# The login theme and the Account Console each render their own "signing you
# in" overlay, and one hands over to the other across a document swap. Any
# difference in the spinner or label reads as a jolt at the seam, so the login
# side's measurements are captured here and compared against the console's.
OVERLAY_SPEC = {}
# What has to match for the handover to look like one continuous screen.
OVERLAY_KEYS = ("loaderWidth", "loaderHeight", "stroke", "gap", "labelFont", "labelColor", "background")
def measure_overlay(page, overlay_sel, loader_sel, label_sel):
return page.evaluate(
"""([overlaySel, loaderSel, labelSel]) => {
const ov = document.querySelector(overlaySel);
const ld = document.querySelector(loaderSel);
const lb = document.querySelector(labelSel);
if (!ov || !ld || !lb) return null;
const o = getComputedStyle(ov), l = getComputedStyle(ld), t = getComputedStyle(lb);
const c = getComputedStyle(ld.querySelector('circle'));
return {
// Computed, not getBoundingClientRect: the spinner is mid-rotation
// and a rect would report the rotated square's axis-aligned box
// (44px reads as anything up to ~62px depending on the angle).
loaderWidth: l.width,
loaderHeight: l.height,
stroke: c.stroke,
gap: o.rowGap,
labelFont: t.fontSize + '/' + t.fontWeight,
labelColor: t.color,
background: o.backgroundColor,
animation: l.animationName + ' ' + l.animationDuration,
};
}""",
[overlay_sel, loader_sel, label_sel],
)
def check(name, cond, detail=""):
status = "PASS" if cond else "FAIL"
print(f"[{status}] {name}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
FAILURES.append(name)
def login_url(locale):
return (
f"{BASE}/realms/demo/protocol/openid-connect/auth?client_id=account-console"
f"&redirect_uri={BASE.replace(':', '%3A').replace('/', '%2F')}%2Frealms%2Fdemo%2Faccount%2F"
"&response_type=code&scope=openid"
"&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256"
f"&ui_locales={locale}"
)
def test_messages_files():
ru = (THEME / "login" / "messages" / "messages_ru.properties").read_text(encoding="utf-8")
props = dict(
line.split("=", 1)
for line in ru.splitlines()
if "=" in line and not line.strip().startswith("#")
)
check(
"ru: webauthn-passwordless-display-name is not 'Пароль'",
props.get("webauthn-passwordless-display-name") == "Ключ доступа",
repr(props.get("webauthn-passwordless-display-name")),
)
check(
"ru: webauthn-login-title mentions passkey",
"passkey" in props.get("webauthn-login-title", "").lower(),
repr(props.get("webauthn-login-title")),
)
for key in ("webauthn-error-api-get", "webauthn-error-user-not-found", "passkey-autofill-select"):
val = props.get(key, "")
check(f"ru: {key} does not say 'пароль'", val != "" and "парол" not in val.lower(), repr(val))
# Compact m3Nav* labels exist in both account locales
nav_keys = {"m3NavPersonalInfo", "m3NavSigningIn", "m3NavDeviceActivity",
"m3NavLinkedAccounts", "m3NavApplications"}
for lang in ("en", "ru"):
txt = (THEME / "account" / "messages" / f"messages_{lang}.properties").read_text(encoding="utf-8")
keys = {line.split("=", 1)[0].strip() for line in txt.splitlines()
if "=" in line and not line.strip().startswith("#")}
check(f"account {lang}: compact m3Nav* labels present", nav_keys <= keys,
str(sorted(nav_keys - keys)))
def test_login_pages(browser):
for locale, btn_text, toggle_expected in (("en", "Sign in with a passkey", True), ("ru", "Войти с passkey", True)):
ctx = browser.new_context(viewport={"width": 1280, "height": 900}, locale=locale)
page = ctx.new_page()
page.goto(login_url(locale))
page.wait_for_selector("#kc-page-title", timeout=20000)
check(f"login[{locale}]: themed card", page.locator(".m3-card").count() == 1)
check(f"login[{locale}]: social buttons", page.locator(".m3-social-btn").count() == 4)
check(f"login[{locale}]: collapsed password form", page.locator("details.m3-pass-details").count() == 1)
check(f"login[{locale}]: theme toggle present", page.locator("#m3-theme-toggle").count() == 1)
check(
f"login[{locale}]: ID favicon",
"img/favicon.svg" in (page.get_attribute('link[rel="icon"]', "href") or ""),
)
if EXPECT_PASSKEY:
check(
f"login[{locale}]: passkey button text",
page.locator("#authenticateWebAuthnButton").count() == 1
and btn_text in page.locator("#authenticateWebAuthnButton").inner_text(),
page.locator("#authenticateWebAuthnButton").inner_text()
if page.locator("#authenticateWebAuthnButton").count()
else "button missing",
)
else:
check(f"login[{locale}]: passkey button absent", page.locator("#authenticateWebAuthnButton").count() == 0)
# Help dialog opens, shows onboarding text, closes.
check(f"login[{locale}]: help button present", page.locator("#m3-help-btn").count() == 1)
page.click("#m3-help-btn")
page.wait_for_timeout(200)
check(
f"login[{locale}]: help dialog opens",
page.evaluate("document.getElementById('m3-help')?.open === true"),
)
help_text = page.locator("#m3-help").inner_text()
needle = "passkey" if locale == "en" else "passkey"
check(f"login[{locale}]: help mentions passkey", needle in help_text.lower(), help_text[:120])
page.click("#m3-help-close")
page.wait_for_timeout(200)
check(
f"login[{locale}]: help dialog closes",
page.evaluate("document.getElementById('m3-help')?.open === false"),
)
# "Try another way" is hidden on the main login page.
check(
f"login[{locale}]: try-another-way hidden",
page.evaluate(
"(el => !el || getComputedStyle(el).display === 'none')(document.querySelector('.m3-try-another'))"
),
)
# Theme-mode menu: system / light / dark.
bg_system = page.evaluate("getComputedStyle(document.body).backgroundColor")
page.click("#m3-theme-toggle")
page.wait_for_timeout(250)
check(
f"login[{locale}]: theme menu opens with 3 modes",
page.evaluate("!document.getElementById('m3-theme-menu').hidden")
and page.locator("#m3-theme-menu [data-mode]").count() == 3,
)
page.click('#m3-theme-menu [data-mode="dark"]')
page.wait_for_timeout(250)
bg_dark = page.evaluate("getComputedStyle(document.body).backgroundColor")
check(f"login[{locale}]: dark mode applies", bg_dark != bg_system, f"{bg_system} -> {bg_dark}")
check(
f"login[{locale}]: dark mode stored",
page.evaluate("localStorage.getItem('m3-theme')") == "dark",
)
page.reload()
page.wait_for_selector("#kc-page-title", timeout=20000)
bg_reloaded = page.evaluate("getComputedStyle(document.body).backgroundColor")
check(f"login[{locale}]: dark mode persists", bg_reloaded == bg_dark, f"{bg_reloaded} != {bg_dark}")
# Back to "system": the stored key is cleared, the OS preference (light
# in this context) applies again.
page.click("#m3-theme-toggle")
page.wait_for_timeout(250)
page.click('#m3-theme-menu [data-mode="system"]')
page.wait_for_timeout(250)
check(
f"login[{locale}]: system mode clears the override",
page.evaluate("localStorage.getItem('m3-theme')") is None
and page.evaluate("getComputedStyle(document.body).backgroundColor") == bg_system,
)
ctx.close()
def test_oidc_bridge_overlay(browser):
"""The full round trip through an external IdP can't be driven in tests
(it needs a real provider), so this exercises the two halves of the
mechanism directly: clicking a provider button arms the flag, and a page
load that finds the flag set shows the bridge overlay and clears it."""
ctx = browser.new_context(viewport={"width": 1280, "height": 900})
page = ctx.new_page()
page.goto(login_url("en"))
page.wait_for_selector("#kc-page-title", timeout=20000)
check(
"oidc bridge: overlay absent on a normal load",
page.evaluate(
"(el => !el || getComputedStyle(el).display === 'none')"
"(document.getElementById('m3-oidc-overlay'))"
),
)
check("oidc bridge: no flag before any click", page.evaluate("sessionStorage.getItem('m3-authing')") is None)
# The handler navigates two animation frames after the click, so read the
# resulting state synchronously in one evaluate() — a round trip here would
# race the navigation and lose the window entirely.
departure = page.evaluate(
"""() => {
document.querySelector('.m3-social-btn').click();
const el = document.getElementById('m3-oidc-overlay');
const cs = getComputedStyle(el);
return {
flag: sessionStorage.getItem('m3-authing') !== null,
display: cs.display,
opacity: cs.opacity,
animation: cs.animationName,
duration: cs.animationDuration,
};
}"""
)
check("oidc bridge: clicking a provider arms the flag", departure["flag"])
check(
"oidc bridge: overlay covers the departure, not just the return",
departure["display"] == "flex",
repr(departure),
)
# Leaving is a fade over the card that's still on screen, not a hard cut,
# so opacity legitimately starts at 0 here — the navigation is already in
# flight and this document keeps rendering until the response commits.
check(
"oidc bridge: the departure fades in",
departure["animation"] == "m3-oidc-in" and departure["duration"] not in ("0s", "none"),
repr(departure),
)
ctx.close()
# …and that fade must actually land on a fully opaque overlay.
ctx = browser.new_context(viewport={"width": 1280, "height": 900})
page = ctx.new_page()
page.goto(login_url("en"))
page.wait_for_selector("#kc-page-title", timeout=20000)
page.evaluate("document.documentElement.classList.add('m3-authing', 'm3-authing-enter')")
page.wait_for_timeout(400)
check(
"oidc bridge: the fade settles fully opaque",
page.evaluate("getComputedStyle(document.getElementById('m3-oidc-overlay')).opacity") == "1",
)
ctx.close()
# Simulate the return trip: a fresh navigation that finds the flag set
# (as it would after the browser comes back from the external provider).
ctx = browser.new_context(viewport={"width": 1280, "height": 900})
page = ctx.new_page()
page.goto(login_url("en"))
page.wait_for_selector("#kc-page-title", timeout=20000)
page.evaluate("sessionStorage.setItem('m3-authing', String(Date.now()))")
page.goto(login_url("en"), wait_until="domcontentloaded")
check(
"oidc bridge: overlay shows immediately when the flag is set",
page.evaluate(
"(el => !!el && getComputedStyle(el).display === 'flex' && getComputedStyle(el).opacity === '1')"
"(document.getElementById('m3-oidc-overlay'))"
),
)
check(
"oidc bridge: overlay text present",
"Signing you in" in page.locator("#m3-oidc-overlay").inner_text(),
)
# Arriving is a cut, not a fade — the overlay is covering a blank here, so
# fading in would reintroduce exactly the flash it exists to hide.
check(
"oidc bridge: the arrival does not fade",
page.evaluate(
"getComputedStyle(document.getElementById('m3-oidc-overlay')).animationName"
) == "none",
)
# Captured for the handover-parity check in test_oidc_bridge_account_landing.
OVERLAY_SPEC.update(
measure_overlay(page, "#m3-oidc-overlay", "#m3-oidc-overlay .m3-loader", "#m3-oidc-overlay .m3-loader-label")
or {}
)
check("oidc bridge: login overlay measurable", bool(OVERLAY_SPEC))
page.wait_for_timeout(900)
check(
"oidc bridge: overlay clears itself and the flag",
page.evaluate("!document.getElementById('m3-oidc-overlay')")
and page.evaluate("sessionStorage.getItem('m3-authing')") is None,
)
ctx.close()
# A stale flag (older than the 60s window) must be ignored, not shown.
ctx = browser.new_context(viewport={"width": 1280, "height": 900})
page = ctx.new_page()
page.goto(login_url("en"))
page.wait_for_selector("#kc-page-title", timeout=20000)
page.evaluate("sessionStorage.setItem('m3-authing', String(Date.now() - 120000))")
page.goto(login_url("en"), wait_until="domcontentloaded")
check(
"oidc bridge: a stale flag is ignored",
page.evaluate(
"(el => !el || getComputedStyle(el).display === 'none')"
"(document.getElementById('m3-oidc-overlay'))"
),
)
ctx.close()
# Reduced motion still communicates loading (text) but doesn't spin.
ctx = browser.new_context(viewport={"width": 1280, "height": 900}, reduced_motion="reduce")
page = ctx.new_page()
page.goto(login_url("en"))
page.wait_for_selector("#kc-page-title", timeout=20000)
page.evaluate("sessionStorage.setItem('m3-authing', String(Date.now()))")
page.goto(login_url("en"), wait_until="domcontentloaded")
check(
"oidc bridge: reduced motion kills the spinner animation",
page.evaluate("getComputedStyle(document.querySelector('#m3-oidc-overlay .m3-loader')).animationName")
== "none",
)
ctx.close()
def test_oidc_bridge_account_landing(browser):
"""A linked identity provider can return the browser straight to the
account console, skipping the login theme entirely — the flag has to be
honored there too (see account/resources/js/material3.js initLoader)."""
ctx = browser.new_context(viewport={"width": 1440, "height": 900}, locale="en")
page = ctx.new_page()
page.goto(f"{BASE}/realms/demo/account/")
page.wait_for_selector("#kc-page-title", timeout=20000)
page.evaluate("document.querySelector('details.m3-pass-details').open = true")
page.fill("#username", "demo")
page.fill("#password", "demo1234")
page.click("#kc-login")
page.wait_for_selector(".m3-rail", timeout=25000)
page.evaluate("sessionStorage.setItem('m3-authing', String(Date.now()))")
page.goto(f"{BASE}/realms/demo/account/", wait_until="domcontentloaded")
check(
"oidc bridge (account landing): loader label shown",
page.evaluate(
"(el => !!el && el.textContent.includes('Signing you in'))"
"(document.querySelector('.m3-loader-label'))"
),
)
# The seam: this overlay replaces the login theme's one across a document
# swap, so every visible property has to match or the handover jolts.
console_spec = measure_overlay(page, ".m3-loader-overlay", ".m3-loader", ".m3-loader-label")
if not OVERLAY_SPEC or not console_spec:
check("oidc bridge: overlays match across the handover", False, "could not measure both overlays")
else:
diffs = [f"{k}: login={OVERLAY_SPEC[k]!r} console={console_spec[k]!r}"
for k in OVERLAY_KEYS if OVERLAY_SPEC.get(k) != console_spec.get(k)]
check("oidc bridge: overlays match across the handover", not diffs, "; ".join(diffs))
page.wait_for_selector(".m3-rail", timeout=25000)
page.wait_for_timeout(500)
check(
"oidc bridge (account landing): overlay and flag clear",
page.evaluate("!document.querySelector('.m3-loader-overlay')")
and page.evaluate("sessionStorage.getItem('m3-authing')") is None,
)
# The stock boot loader (static HTML, painted before any console JS) is
# the third wheel in the OIDC chain: login overlay → boot loader → console
# overlay. Recreate its markup and hold it to the same spec — a different
# mark or color there reads as a swap mid-wait.
boot = page.evaluate(
"""() => {
const d = document.createElement('div');
d.className = 'keycloak__loading-container';
d.innerHTML = '<svg class="pf-v5-c-spinner pf-m-xl" viewBox="0 0 100 100">'
+ '<circle class="pf-v5-c-spinner__path" cx="50" cy="50" r="45" fill="none"></circle></svg>'
+ '<div><p id="loading-text">Loading</p></div>';
document.body.appendChild(d);
const sp = getComputedStyle(d.querySelector('.pf-v5-c-spinner'));
const path = getComputedStyle(d.querySelector('.pf-v5-c-spinner__path'));
const txt = getComputedStyle(d.querySelector('#loading-text'));
const cont = getComputedStyle(d);
const out = {
loaderWidth: sp.width,
loaderHeight: sp.height,
stroke: path.stroke,
gap: cont.rowGap,
labelFont: txt.fontSize + '/' + txt.fontWeight,
labelColor: txt.color,
background: cont.backgroundColor,
linecap: path.strokeLinecap,
rot: sp.animationName + ' ' + sp.animationDuration,
dash: path.animationName + ' ' + path.animationDuration,
};
d.remove();
return out;
}"""
)
if not OVERLAY_SPEC or not boot:
check("oidc bridge: boot loader matches the overlays", False, "could not measure")
else:
diffs = [f"{k}: login={OVERLAY_SPEC[k]!r} boot={boot[k]!r}"
for k in OVERLAY_KEYS if OVERLAY_SPEC.get(k) != boot.get(k)]
if boot["linecap"] != "round":
diffs.append(f"linecap: {boot['linecap']!r}")
if boot["rot"] != "m3-rot 1.4s":
diffs.append(f"rot: {boot['rot']!r}")
if boot["dash"] != "m3-dash-100 1.3s":
diffs.append(f"dash: {boot['dash']!r}")
check("oidc bridge: boot loader matches the overlays", not diffs, "; ".join(diffs))
# A normal load (no flag) must not show any label.
page.goto(f"{BASE}/realms/demo/account/", wait_until="domcontentloaded")
check(
"oidc bridge (account landing): no label on an ordinary load",
page.evaluate("!document.querySelector('.m3-loader-label')"),
)
ctx.close()
def test_webauthn_error_message(browser):
"""Regression for upstream RU mistranslation: a failed passkey attempt must
not claim a *password* failure."""
if not EXPECT_PASSKEY:
print("[skip] webauthn error message (no passkeys support)")
return
ctx = browser.new_context(viewport={"width": 1280, "height": 900}, locale="ru")
page = ctx.new_page()
page.goto(login_url("ru"))
page.wait_for_selector("#webauth", timeout=20000, state="attached")
page.evaluate(
"""() => {
document.getElementById('error').value = 'test-cancelled';
document.getElementById('webauth').submit();
}"""
)
page.wait_for_selector("#kc-page-title", timeout=20000)
body = page.evaluate("document.body.innerText")
check("passkey error: no 'с помощью пароля'", "с помощью пароля" not in body, body[:300])
check("passkey error: mentions ключ/passkey", ("ключ" in body.lower()) or ("passkey" in body.lower()), body[:300])
ctx.close()
def test_register_page(browser):
ctx = browser.new_context(viewport={"width": 1280, "height": 900}, locale="en")
page = ctx.new_page()
page.goto(login_url("en"))
page.wait_for_selector("#kc-page-title", timeout=20000)
page.click("#kc-registration a")
page.wait_for_selector("#kc-register-form", timeout=20000)
check("register: themed inputs", page.locator(".m3-input").count() >= 4)
check(
"register: filled submit",
"m3-btn-filled" in (page.get_attribute("#kc-register-form input[type=submit]", "class") or ""),
)
ctx.close()
def test_account_console(browser):
ctx = browser.new_context(viewport={"width": 1440, "height": 900}, locale="en")
page = ctx.new_page()
page.goto(f"{BASE}/realms/demo/account/")
page.wait_for_selector("#kc-page-title", timeout=20000)
page.evaluate("document.querySelector('details.m3-pass-details').open = true")
page.fill("#username", "demo")
page.fill("#password", "demo1234")
page.click("#kc-login")
page.wait_for_selector(".m3-rail", timeout=25000)
check(
"account: theme css loaded",
page.evaluate("[...document.styleSheets].some(s => (s.href||'').includes('material3-account.css'))"),
)
rail_items = page.locator(".m3-rail-item").count()
check("account: rail has flattened destinations", rail_items >= 4, f"items={rail_items}")
# Compact m3Nav* labels replace the console's long nav strings (which
# double as page headings and must stay long there).
first_label = page.locator('.m3-rail-item[href$="/account/"] .m3-rail-label, .m3-rail-item[href*="personal-info"] .m3-rail-label').first.inner_text().strip()
check("account: rail uses compact nav labels", first_label == "Profile", repr(first_label))
page.wait_for_selector(".m3-brand-mark", timeout=10000)
check(
"account: brand shows realm name + ID badge",
page.locator(".m3-brand-name").inner_text() == "demo"
and page.locator(".m3-brand-badge").inner_text() == "ID",
)
check(
"account: brand links to the realm's account console",
"/realms/demo/account" in (page.get_attribute(".pf-v5-c-masthead__brand", "href") or ""),
page.get_attribute(".pf-v5-c-masthead__brand", "href"),
)
check(
"account: PF sidebar hidden",
page.evaluate(
"(el => !el || getComputedStyle(el).display === 'none')(document.querySelector('.pf-v5-c-page__sidebar'))"
),
)
# User button: M3 avatar circle with initials instead of PF's pill.
page.wait_for_selector(".m3-user-avatar", timeout=10000)
check(
"account: user button shows initials avatar",
page.evaluate("document.querySelector('[data-testid=\\'options-toggle\\'] .m3-user-avatar')?.textContent") == "DU",
page.evaluate("document.querySelector('.m3-user-avatar')?.textContent"),
)
check(
"account: PF pill text and caret hidden",
page.evaluate(
"""(() => {
const t = document.querySelector('[data-testid="options-toggle"] .pf-v5-c-menu-toggle__text');
const c = document.querySelector('[data-testid="options-toggle"] .pf-v5-c-menu-toggle__controls');
return t && getComputedStyle(t).display === 'none'
&& c && getComputedStyle(c).display === 'none';
})()"""
),
)
check(
"account: stock gray avatar hidden",
page.evaluate(
"""(el => !el || getComputedStyle(el.closest('.pf-v5-c-toolbar__item') || el).display === 'none')
(document.querySelector('.pf-v5-c-masthead svg.pf-v5-c-avatar'))"""
),
)
page.click('[data-testid="options-toggle"]')
page.wait_for_timeout(400)
check(
"account: avatar button opens the user menu",
page.locator(".pf-v5-c-menu").count() > 0
and page.locator(".pf-v5-c-menu").first.is_visible(),
)
# PF paints the menu <li> with its own opaque square background; in dark
# it's a lighter box with 0 radius poking out of the rounded menu (in
# light it merely hides inside a near-identical shade — check both ways).
check(
"account: menu list item paints no square background",
page.evaluate(
"getComputedStyle(document.querySelector('.pf-v5-c-menu__list-item')).backgroundColor"
) == "rgba(0, 0, 0, 0)",
)
check(
"account: expanded toggle stays an avatar (no pill text)",
page.evaluate(
"""(() => {
const t = document.querySelector('[data-testid="options-toggle"] .pf-v5-c-menu-toggle__text');
return document.querySelector('[data-testid="options-toggle"] .m3-user-avatar')
&& (!t || getComputedStyle(t).display === 'none');
})()"""
),
)
page.keyboard.press("Escape")
page.wait_for_timeout(300)
check(
"account: avatar survives menu collapse (PF re-render)",
page.evaluate("!!document.querySelector('[data-testid=\\'options-toggle\\'] .m3-user-avatar')"),
)
# Form fields: PF's rectangular pseudo-element frames must be gone, the
# focus indicator is a single rounded ring, and the locale dropdown looks
# like the text fields next to it.
check(
"account: no rectangular pseudo frames on inputs",
page.evaluate(
"""(() => {
const w = document.querySelector('input[name="email"], #email').parentElement;
const b = getComputedStyle(w, '::before'), a = getComputedStyle(w, '::after');
return [b.borderTopWidth, b.borderRightWidth, b.borderBottomWidth, b.borderLeftWidth,
a.borderTopWidth, a.borderRightWidth, a.borderBottomWidth, a.borderLeftWidth]
.every(x => x === '0px');
})()"""
),
)
page.click('input[name="email"], #email')
page.wait_for_timeout(200)
check(
"account: focus = one rounded ring, no inner browser outline",
page.evaluate(
"""(() => {
const w = document.querySelector('input[name="email"], #email').parentElement;
const cs = getComputedStyle(w);
return cs.outlineStyle === 'solid' && parseFloat(cs.borderRadius) >= 8
&& getComputedStyle(document.activeElement).outlineStyle === 'none';
})()"""
),
)
check(
"account: locale dropdown styled like the text fields",
page.evaluate(
"""(() => {
const t = document.querySelector('.pf-v5-c-form__group .pf-v5-c-menu-toggle.pf-m-full-width');
if (!t) return false;
const w = document.querySelector('input[name="email"], #email').parentElement;
const a = getComputedStyle(t), b = getComputedStyle(w);
return a.backgroundColor === b.backgroundColor && a.borderRadius === b.borderRadius
&& a.borderTopWidth === '0px';
})()"""
),
)
# Rail navigation works.
page.click('.m3-rail-item[href*="signing-in"]')
page.wait_for_timeout(1500)
check("account: rail navigates", "signing-in" in page.url)
check(
"account: rail active state follows",
page.evaluate(
"document.querySelector('.m3-rail-item[data-active]')?.getAttribute('href')?.includes('signing-in')"
),
)
check(
"account: page transition animation runs",
page.evaluate("document.querySelector('.pf-v5-c-page__main').classList.contains('m3-page-in')"),
)
page.click('.m3-rail-item[href*="linked-accounts"]')
page.wait_for_selector(".pf-v5-c-text-input-group", timeout=15000)
check(
"account: filter field wide enough",
page.evaluate("document.querySelector('.pf-v5-c-text-input-group').getBoundingClientRect().width >= 260"),
)
placeholder = page.evaluate(
"document.querySelector('.pf-v5-c-text-input-group__text-input')?.placeholder || ''"
)
check(
"account: filter placeholder has no ellipsis",
placeholder != "" and not placeholder.rstrip().endswith(("...", "…")),
placeholder,
)
check(
"account: no divider line between filter field and its button",
page.evaluate(
"""[...document.querySelectorAll('.pf-v5-c-input-group__item')]
.every(it => {
const cs = getComputedStyle(it);
return [cs.borderLeftWidth, cs.borderRightWidth, cs.borderTopWidth, cs.borderBottomWidth]
.every(w => w === '0px');
})"""
),
)
check(
"account: search arrow centered in its round button",
page.evaluate(
"""(() => {
const b = document.querySelector('.pf-v5-c-button.pf-m-control');
const i = b && b.querySelector('svg');
if (!b || !i) return false;
const br = b.getBoundingClientRect(), ir = i.getBoundingClientRect();
return Math.abs((br.left + br.right) / 2 - (ir.left + ir.right) / 2) < 1.5
&& Math.abs((br.top + br.bottom) / 2 - (ir.top + ir.bottom) / 2) < 1.5;
})()"""
),
)
check(
"account: ID favicon injected",
page.evaluate(
"(document.querySelector('link[rel=\\'icon\\']')?.href || '').includes('account/material3/img/favicon.svg')"
),
page.evaluate("document.querySelector('link[rel=\\'icon\\']')?.href"),
)
# Theme-mode menu: system / light / dark.
page.click("#m3-theme-toggle")
page.wait_for_timeout(300)
check(
"account: theme menu opens with 3 modes",
page.evaluate("!document.querySelector('.m3-theme-menu').hidden")
and page.locator(".m3-theme-menu [data-mode]").count() == 3,
)
check(
"account: theme menu labels localized",
page.evaluate("document.querySelector('.m3-theme-menu [data-mode=\\'system\\'] span')?.textContent") == "System",
)
page.click('.m3-theme-menu [data-mode="dark"]')
page.wait_for_timeout(300)
check(
"account: dark mode applies",
page.evaluate("document.documentElement.classList.contains('pf-v5-theme-dark')"),
)
page.reload()
page.wait_for_selector(".m3-rail", timeout=25000)
check(
"account: dark mode persists",
page.evaluate("document.documentElement.classList.contains('pf-v5-theme-dark')"),
)
page.click("#m3-theme-toggle")
page.wait_for_timeout(300)
page.click('.m3-theme-menu [data-mode="system"]')
page.wait_for_timeout(300)
check(
"account: system mode clears the override and follows the OS",
page.evaluate("localStorage.getItem('m3-theme')") is None
and not page.evaluate("document.documentElement.classList.contains('pf-v5-theme-dark')"),
)
# Fonts from m3.material.io (Google Sans) actually loaded.
page.wait_for_timeout(500)
check(
"account: Google Sans loaded",
page.evaluate("document.fonts.check('16px \"Google Sans\"') || document.fonts.check('16px \"Google Sans Text\"')"),
)
# Medium screens (768–1099): rail hides, hamburger + drawer appear.
med = browser.new_context(viewport={"width": 1000, "height": 800}, locale="en")
dpage = med.new_page()
dpage.goto(f"{BASE}/realms/demo/account/")
dpage.wait_for_selector("#kc-page-title", timeout=20000)
dpage.evaluate("document.querySelector('details.m3-pass-details').open = true")
dpage.fill("#username", "demo")
dpage.fill("#password", "demo1234")
dpage.click("#kc-login")
dpage.wait_for_selector(".m3-rail", timeout=25000, state="attached")
check(
"account[medium]: rail hidden",
dpage.evaluate("getComputedStyle(document.querySelector('.m3-rail')).display === 'none'"),
)
check(
"account[medium]: hamburger visible",
dpage.evaluate("getComputedStyle(document.querySelector('.m3-menu-btn')).display !== 'none'"),
)
dpage.click(".m3-menu-btn")
dpage.wait_for_timeout(500)
check(
"account[medium]: drawer opens",
dpage.evaluate("!document.querySelector('.m3-drawer').hidden && document.querySelector('.m3-drawer').classList.contains('m3-open')"),
)
check(
"account[medium]: drawer has items",
dpage.locator(".m3-drawer-item").count() >= 4,
)
dpage.click('.m3-drawer-item[href*="signing-in"]')
dpage.wait_for_timeout(1200)
check("account[medium]: drawer navigates", "signing-in" in dpage.url)
check(
"account[medium]: drawer closed after navigation",
dpage.evaluate("document.querySelector('.m3-drawer').hidden === true"),
)
med.close()
# Mobile: the rail becomes a bottom navigation bar.
mob = browser.new_context(viewport={"width": 390, "height": 844}, locale="en", is_mobile=True)
mpage = mob.new_page()
mpage.goto(f"{BASE}/realms/demo/account/")
mpage.wait_for_selector("#kc-page-title", timeout=20000)
mpage.evaluate("document.querySelector('details.m3-pass-details').open = true")
mpage.fill("#username", "demo")
mpage.fill("#password", "demo1234")
mpage.click("#kc-login")
mpage.wait_for_selector(".m3-rail", timeout=25000)
check(
"account[mobile]: bottom navigation bar",
mpage.evaluate(
"""() => {
const el = document.querySelector('.m3-rail');
const cs = getComputedStyle(el);
const rect = el.getBoundingClientRect();
return cs.flexDirection === 'row' && Math.abs(rect.bottom - innerHeight) < 2 && rect.width >= innerWidth - 2;
}"""
),
)
check(
"account[mobile]: bottom bar labels fit without truncation",
mpage.evaluate(
"""[...document.querySelectorAll('.m3-rail-label')]
.every(l => l.scrollWidth <= l.clientWidth)"""
),
mpage.evaluate(
"""[...document.querySelectorAll('.m3-rail-label')]
.filter(l => l.scrollWidth > l.clientWidth).map(l => l.textContent).join(', ')"""
),
)
check(
"account[mobile]: user-menu kebab pinned to the right edge",
mpage.evaluate(
"""(() => {
const b = document.querySelector('[data-testid="options-kebab-toggle"]');
if (!b) return false;
const r = b.getBoundingClientRect();
return r.height > 0 && innerWidth - r.right < 72;
})()"""
),
mpage.evaluate(
"JSON.stringify(document.querySelector('[data-testid=\\'options-kebab-toggle\\']')?.getBoundingClientRect())"
),
)
check(
"account[mobile]: kebab drawn as a round icon button",
mpage.evaluate(
"""(() => {
const b = document.querySelector('[data-testid="options-kebab-toggle"]');
if (!b) return false;
const cs = getComputedStyle(b);
const r = b.getBoundingClientRect();
return cs.borderRadius.includes('50%') && Math.abs(r.width - r.height) < 2;
})()"""
),
)
mob.close()
# Russian nav labels are the longest strings — verify the compact set fits.
mobru = browser.new_context(viewport={"width": 390, "height": 844}, locale="ru-RU", is_mobile=True)
rpage = mobru.new_page()
rpage.goto(f"{BASE}/realms/demo/account/")
rpage.wait_for_selector("#kc-page-title", timeout=20000)
rpage.evaluate("document.querySelector('details.m3-pass-details').open = true")
rpage.fill("#username", "demo")
rpage.fill("#password", "demo1234")
rpage.click("#kc-login")
rpage.wait_for_selector(".m3-rail", timeout=25000)
ru_first = rpage.locator('.m3-rail-item[href$="/account/"] .m3-rail-label, .m3-rail-item[href*="personal-info"] .m3-rail-label').first.inner_text().strip()
check("account[mobile,ru]: compact Russian labels", ru_first == "Профиль", repr(ru_first))
check(
"account[mobile,ru]: theme menu labels in Russian",
rpage.evaluate("document.querySelector('.m3-theme-menu [data-mode=\\'system\\'] span')?.textContent") == "Системная",
)
check(
"account[mobile,ru]: bottom bar labels fit without truncation",
rpage.evaluate(
"""[...document.querySelectorAll('.m3-rail-label')]
.every(l => l.scrollWidth <= l.clientWidth)"""
),
rpage.evaluate(
"""[...document.querySelectorAll('.m3-rail-label')]
.filter(l => l.scrollWidth > l.clientWidth).map(l => l.textContent).join(', ')"""
),
)
mobru.close()
ctx.close()
def _dur(page, sel, prop="transition-duration", pseudo=None):
"""Longest duration (s) of a computed transition/animation on `sel`."""
return page.evaluate(
"""([sel, prop, pseudo]) => {
const el = document.querySelector(sel);
if (!el) return -1;
const v = getComputedStyle(el, pseudo || undefined).getPropertyValue(prop);
return Math.max(...v.split(',').map(s => parseFloat(s) || 0));
}""",
[sel, prop, pseudo],
)
def test_motion(browser):
"""Every user-facing interaction must be animated (M3 'expressive motion'):
non-zero durations, M3 standard easing on big moves, and everything off
under prefers-reduced-motion."""
ctx = browser.new_context(viewport={"width": 1280, "height": 900}, locale="en")
page = ctx.new_page()
page.goto(login_url("en"))
page.wait_for_selector("#kc-page-title", timeout=20000)
check("motion[login]: card entrance animation",
page.evaluate("getComputedStyle(document.querySelector('.m3-card')).animationName") == "m3-card-in"
and _dur(page, ".m3-card", "animation-duration") > 0)
page.evaluate("document.body.classList.add('m3-exit')")
check("motion[login]: card exit animation",
page.evaluate("getComputedStyle(document.querySelector('.m3-card')).animationName") == "m3-card-out")
page.evaluate("document.body.classList.remove('m3-exit')")
check("motion[login]: brand panel slides on breakpoint",
_dur(page, ".m3-brand") > 0
and "flex-basis" in page.evaluate(
"getComputedStyle(document.querySelector('.m3-brand')).transitionProperty"))
check("motion[login]: password details animates",
_dur(page, ".m3-pass-details", pseudo="::details-content") > 0)
check("motion[login]: details uses M3 standard easing",
"0.2, 0, 0, 1" in page.evaluate(
"getComputedStyle(document.querySelector('.m3-pass-details'), '::details-content').transitionTimingFunction"))
for sel, name in ((".m3-social-btn", "social button"),
("#m3-theme-toggle", "theme toggle"),
("#m3-help-btn", "help button"),
(".m3-pass-details summary", "password summary"),
("#kc-current-locale-link", "locale button")):
if page.locator(sel).count():
check(f"motion[login]: {name} hover is animated", _dur(page, sel) > 0)
if EXPECT_PASSKEY:
check("motion[login]: passkey button animated", _dur(page, "#authenticateWebAuthnButton") > 0)
check("motion[login]: theme menu uses M3 easing",
_dur(page, "#m3-theme-menu") > 0
and "0.2, 0, 0, 1" in page.evaluate(
"getComputedStyle(document.getElementById('m3-theme-menu')).transitionTimingFunction"))
# Brand panel actually collapses (smoothly) when the window narrows.
w_before = page.evaluate("document.querySelector('.m3-brand').getBoundingClientRect().width")
page.set_viewport_size({"width": 800, "height": 900})
page.wait_for_timeout(600)
w_after = page.evaluate("document.querySelector('.m3-brand').getBoundingClientRect().width")
check("motion[login]: brand panel collapses below 940px",
w_before > 300 and w_after < 2, f"{w_before} -> {w_after}")
ctx.close()
# Reduced motion: all of it must switch off.
rm = browser.new_context(viewport={"width": 1280, "height": 900}, locale="en",
reduced_motion="reduce")
rpage = rm.new_page()
rpage.goto(login_url("en"))
rpage.wait_for_selector("#kc-page-title", timeout=20000)
check("motion[login]: reduced-motion kills animations",
rpage.evaluate("getComputedStyle(document.querySelector('.m3-card')).animationName") == "none"
and _dur(rpage, ".m3-pass-details summary") == 0)
rm.close()
# Account console.
ctx = browser.new_context(viewport={"width": 1440, "height": 900}, locale="en")
page = ctx.new_page()
page.goto(f"{BASE}/realms/demo/account/")
page.wait_for_selector("#kc-page-title", timeout=20000)
page.evaluate("document.querySelector('details.m3-pass-details').open = true")
page.fill("#username", "demo")
page.fill("#password", "demo1234")
page.click("#kc-login")
page.wait_for_selector(".m3-rail", timeout=25000)
check("motion[account]: rail pill hover animated", _dur(page, ".m3-rail-ind") > 0)
check("motion[account]: theme toggle animated", _dur(page, "#m3-theme-toggle") > 0)
check("motion[account]: theme menu uses M3 easing",
_dur(page, ".m3-theme-menu") > 0
and "0.2, 0, 0, 1" in page.evaluate(
"getComputedStyle(document.querySelector('.m3-theme-menu')).transitionTimingFunction"))
check("motion[account]: buttons animated", _dur(page, ".pf-v5-c-button") > 0)
check("motion[account]: drawer panel uses M3 easing",
_dur(page, ".m3-drawer-panel") > 0
and "0.2, 0, 0, 1" in page.evaluate(
"getComputedStyle(document.querySelector('.m3-drawer-panel')).transitionTimingFunction"))
check("motion[account]: page transition keyframes defined",
page.evaluate(
"""[...document.styleSheets].some(s => {
try { return [...s.cssRules].some(r => r.name === 'm3-page-in-kf' || (r.cssText||'').includes('m3-page')); }
catch (e) { return false; }
})"""))
ctx.close()
def test_forced_light_on_dark_system(browser):
"""System prefers dark but the user forced light: text must stay readable
(regression: UA canvastext painted headings white on the light ground)."""
ctx = browser.new_context(viewport={"width": 1440, "height": 900}, color_scheme="dark", locale="en-US")
page = ctx.new_page()
page.add_init_script("try { localStorage.setItem('m3-theme', 'light'); } catch (e) {}")
page.goto(f"{BASE}/realms/demo/account/")
page.wait_for_selector("#kc-page-title", timeout=20000)
page.evaluate("document.querySelector('details.m3-pass-details').open = true")
page.fill("#username", "demo")
page.fill("#password", "demo1234")
page.click("#kc-login")
page.wait_for_selector(".m3-rail", timeout=25000)
page.click('.m3-rail-item[href*="signing-in"]')
page.wait_for_timeout(2000)
res = page.evaluate(
"""() => {
const t = [...document.querySelectorAll('.pf-v5-c-title')].find(e => /auth|Password|Passkey/i.test(e.textContent));
const bg = getComputedStyle(document.body).backgroundColor;
const c = t ? getComputedStyle(t).color : null;
return { bg, c };
}"""
)
check(
"mixed: forced-light headings readable",
res["c"] is not None and res["c"] != "rgb(255, 255, 255)",
str(res),
)
page.evaluate("localStorage.removeItem('m3-theme')")
ctx.close()
def main():
test_messages_files()
with sync_playwright() as p:
browser = p.chromium.launch()
test_login_pages(browser)
test_oidc_bridge_overlay(browser)
test_webauthn_error_message(browser)
test_register_page(browser)
test_account_console(browser)
test_oidc_bridge_account_landing(browser)
test_motion(browser)
test_forced_light_on_dark_system(browser)
browser.close()
print(f"\n{len(FAILURES)} failure(s)" if FAILURES else "\nAll tests passed")
sys.exit(1 if FAILURES else 0)
if __name__ == "__main__":
main()