File size: 29,149 Bytes
3fbbdd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""AX computation tests for massCode — Developer Tools calculators + editor/status computations."""
import json
import os
import re
import subprocess
import time

import pytest
import rb_testgen_kit as kit

RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__)))


def screenshot_assert(test_name, description, results_dir=None):
    results_dir = results_dir or RESULTS_DIR
    ss_dir = os.path.join(results_dir, "screenshots")
    os.makedirs(ss_dir, exist_ok=True)
    ss_path = os.path.join(ss_dir, f"{test_name}.png")
    try:
        subprocess.run(["screencapture", "-x", ss_path], timeout=5)
    except Exception:
        pass
    assertions_file = os.path.join(ss_dir, "assertions.json")
    assertions = {}
    if os.path.exists(assertions_file):
        try:
            with open(assertions_file) as f:
                assertions = json.load(f)
        except Exception:
            assertions = {}
    assertions[f"{test_name}.png"] = description
    with open(assertions_file, "w") as f:
        json.dump(assertions, f, indent=2)


def _enable_web_ax(ax, timeout=10.0):
    """Chromium/Electron builds its web-content AX tree only once an AT announces itself."""
    from ApplicationServices import AXUIElementSetAttributeValue
    try:
        AXUIElementSetAttributeValue(ax._app_ref, "AXEnhancedUserInterface", True)
    except Exception:
        pass
    deadline = time.time() + timeout
    while time.time() < deadline:
        if ax.find(role="label", max_results=1, max_depth=16):
            return True
        time.sleep(0.25)
    return False


def app_ready(ax):
    """MANDATORY bring-up: build the web AX tree and foreground the app."""
    _enable_web_ax(ax)
    try:
        from AppKit import NSRunningApplication
        a = NSRunningApplication.runningApplicationWithProcessIdentifier_(int(ax.get_pid()))
        if a is not None:
            a.activateWithOptions_(1 << 1)
    except Exception:
        pass
    time.sleep(0.4)
    return ax


def labels(ax):
    return [l.value for l in ax.find(role="label", max_results=250, max_depth=26) if l.value]


def field(ax, placeholder):
    for t in ax.find(role="text_field", max_results=15, max_depth=26):
        if (t.name or "") == placeholder:
            return t
    return None


def fields(ax):
    return ax.find(role="text_field", max_results=12, max_depth=26)


def text_areas(ax):
    return ax.find(role="text_area", max_results=8, max_depth=26)


def popups(ax):
    return ax.find(role="popup", max_results=12, max_depth=26)


def named_button(ax, name):
    for b in ax.find(role="button", max_results=40, max_depth=26):
        if (b.name or "").strip() == name.strip():
            return b
    return None


def press_labelled_group(ax, text):
    for g in ax.find(role="group", max_results=600, max_depth=26):
        if "AXPress" not in (g.actions or []):
            continue
        labs = ax.find(role="label", root_id=g.id, max_results=3, max_depth=2)
        if any((l.value or "").strip() == text for l in labs):
            return ax.action(g.id, "AXPress")
    return False


def webarea(ax):
    w = ax.find(role="webarea", max_results=1, max_depth=6)
    return w[0] if w else None


def menu_el(ax, path):
    items = ax.find(role="menu_bar_item", name=path[0], max_results=3, max_depth=3)
    if not items:
        return None
    cur = items[0]
    for lbl in path[1:]:
        kids = ax.find(role="menu_item", name=lbl, root_id=cur.id, max_results=3, max_depth=3)
        if not kids:
            return None
        cur = kids[0]
    return cur


def rb_enter_menu(ax, path, settle=1.2):
    """NAVIGATION: fire a menu item, crossing into whatever surface it opens."""
    el = menu_el(ax, path)
    if el is None:
        return False
    ok = ax.action(el.id, "AXPress")
    time.sleep(settle)
    return ok


def rb_enter_close_surface(ax, settle=1.3):
    """NAVIGATION: leave Preferences / Developer Tools / Presentation."""
    wa = webarea(ax)
    if wa is None:
        return False
    btns = ax.find(role="button", root_id=wa.id, max_results=5, max_depth=24)
    if not btns:
        return False
    ok = ax.action(btns[0].id, "AXPress")
    time.sleep(settle)
    return ok


def rb_enter_devtool(ax, tool_name, settle=1.3):
    """NAVIGATION: open the Developer Tools surface (if needed) and select a tool."""
    if "Developer Tools" not in labels(ax):
        rb_enter_menu(ax, ["massCode", "Developer Tools…"], settle=1.6)
    ok = press_labelled_group(ax, tool_name)
    time.sleep(settle)
    return ok


def select_option(ax, popup_value, option_label, settle=1.0):
    """AXPress a <select> popup (all options materialise as its menu_item children),
    then AXPress the wanted option. Returns True on success."""
    tgt = None
    for p in popups(ax):
        if (p.value or "") == popup_value:
            tgt = p
            break
    if tgt is None:
        return False
    ax.action(tgt.id, "AXPress")
    time.sleep(0.9)
    for p in popups(ax):
        for o in ax.find(role="menu_item", root_id=p.id, max_results=300, max_depth=4):
            if (o.value or "") == option_label:
                ok = ax.action(o.id, "AXPress")
                time.sleep(settle)
                return ok
    subprocess.run(["osascript", "-e",
                    'tell application "System Events" to key code 53'],
                   capture_output=True, timeout=5)
    return False


def set_input(ax, text, settle=1.0):
    """Write the first devtool text_area (Input String) and let the tool recompute."""
    ta = text_areas(ax)
    if not ta:
        return False
    ok = ax.set_value(ta[0].id, text)
    time.sleep(settle)
    return ok


def read_output(ax, index=1):
    ta = text_areas(ax)
    return ta[index].value if len(ta) > index else None


def go_home(ax):
    for _ in range(3):
        ls = labels(ax)
        if "Preferences" in ls or "Developer Tools" in ls or "1 / 0" in ls:
            if rb_enter_close_surface(ax):
                continue
        break
    if "Inbox" not in labels(ax):
        press_labelled_group(ax, "LIBRARY")
        time.sleep(0.8)
    return ax


def rb_enter_new_snippet(ax):
    """NAVIGATION: create + select a fresh snippet (the editor surface)."""
    return rb_enter_menu(ax, ["File", "New Snippet"], settle=1.6)


# ─────────────────────────────────────────────────────────────────────────────
# Local (non-navigating) computation helpers — all element lookups are re-done
# after every interaction, because AXHelper element ids are per-snapshot.
# ─────────────────────────────────────────────────────────────────────────────

UUID_RE = r"^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
_COUNT_RE = re.compile(r"^(\d+)\s+snippets?\.$")


def norm(s):
    """Normalise a multi-line devtool output for exact comparison."""
    return (s or "").replace("\r\n", "\n").replace("\r", "\n").strip()


def named_button_prefix(ax, prefix):
    """Button whose visible label STARTS WITH `prefix` (the reference truncates
    'Reverse' to 'Revers'; a recreation may spell it out)."""
    for b in ax.find(role="button", max_results=40, max_depth=26):
        if (b.name or "").strip().startswith(prefix):
            return b
    return None


def press_button(ax, name, settle=0.9):
    """Locate a devtool action button by its VISIBLE label and AXPress it."""
    b = named_button(ax, name) or named_button_prefix(ax, name)
    if b is None:
        return False
    ok = ax.action(b.id, "AXPress")
    time.sleep(settle)
    return ok


def read_result_any(ax, exclude=()):
    """Fallback Result reader: first non-empty value among the text_areas AFTER the
    input box, else any text_field value that is not a known input value."""
    for v in [ta.value for ta in text_areas(ax)][1:]:
        if v and str(v).strip() and v not in exclude:
            return v
    for f in fields(ax):
        v = f.value
        if v and str(v).strip() and v not in exclude:
            return v
    return None


def read_output_robust(ax, exclude=()):
    """Devtool Output/Result value. Prefers the pane's SECOND text_area (the documented
    Output String / Result box); falls back to any other non-empty non-input value so the
    same test also works if a recreation renders the Result as an <input>."""
    v = read_output(ax, 1)
    if v is not None and str(v).strip():
        return v
    return read_result_any(ax, exclude=exclude)


def case_convert(ax, text, button_name, in_settle=0.7, out_settle=0.8):
    """Set the Case Converter input, press one case button, return the Output String."""
    set_input(ax, text, settle=in_settle)
    if not press_button(ax, button_name, settle=out_settle):
        return None
    return read_output_robust(ax)


def set_url(ax, url, settle=1.1):
    """URL Parser input: a plain <input> (text_field), with a text_area fallback."""
    flds = fields(ax)
    if flds:
        ok = ax.set_value(flds[0].id, url)
    else:
        ta = text_areas(ax)
        ok = ax.set_value(ta[0].id, url) if ta else False
    time.sleep(settle)
    return ok


def parsed_rows(ax):
    """{Component: Value} built from the Parsed URL table(s): every row has 2 cells,
    each holding one label."""
    out = {}
    for r in ax.find(role="row", max_results=25, max_depth=28):
        cells = ax.find(role="cell", root_id=r.id, max_results=3, max_depth=2)
        vals = []
        for c in cells:
            ls = ax.find(role="label", root_id=c.id, max_results=2, max_depth=2)
            vals.append(ls[0].value if ls else "")
        if len(vals) >= 2 and vals[0]:
            out[vals[0]] = vals[1]
    return out


def select_option_any(ax, current_candidates, option_label):
    """Drive a <select> whose CURRENT value may be any of `current_candidates`
    (the reference default first) to `option_label`."""
    for cur in current_candidates:
        if select_option(ax, cur, option_label):
            return True
    return False


_ALGOS = ["MD5", "SHA1", "SHA256", "SHA512", "SHA384", "SHA224", "SHA3", "RIPEMD160"]


def uuid_result(ax):
    """UUID Generator Result box (this pane exposes ONE text_area — the Result)."""
    ta = text_areas(ax)
    if ta and str(ta[0].value or "").strip():
        return ta[0].value
    for f in fields(ax):
        v = str(f.value or "")
        if len(v) >= 36 and v.count("-") >= 4:
            return v
    return ta[0].value if ta else None


def snippet_count(ax):
    """N from the Preferences > Storage label 'N snippets.'"""
    for v in labels(ax):
        m = _COUNT_RE.match(str(v or "").strip())
        if m:
            return int(m.group(1))
    return None


CASE_INPUT = "hello world example"


class TestCaseConverter:
    """Developer Tools > Text Tools > Case Converter: input string -> 7 case outputs."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Output String 'helloWorldExample' then 'HelloWorldExample'")
    def test_case_camel_and_pascal(self, ax):
        app_ready(ax)
        assert rb_enter_devtool(ax, "Case Converter"), \
            f"could not reach Case Converter; labels={labels(ax)[:25]}"
        assert text_areas(ax), "Case Converter Input String text_area not found"

        camel = case_convert(ax, CASE_INPUT, "camelCase")
        assert kit.rb_value(norm(camel), "helloWorldExample"), \
            f"camelCase('{CASE_INPUT}') -> {camel!r}, expected 'helloWorldExample'"

        pascal = case_convert(ax, CASE_INPUT, "PascalCase")
        screenshot_assert(
            "computation_case_converter",
            "massCode Developer Tools surface, Case Converter pane. Left rail lists Text "
            "Tools (Case Converter, Slug Generator, Sort Lines, URL Parser), Cryptography / "
            "Security and Encoders / Decoders. The pane shows an Input String box holding "
            "'hello world example', the seven case buttons (camelCase, kebab-case, "
            "snake_case, PascalCase, lower case, Start Case, UPPER CASE) and an Output "
            "String box showing the PascalCase result 'HelloWorldExample'.")
        assert kit.rb_value(norm(pascal), "HelloWorldExample"), \
            f"PascalCase('{CASE_INPUT}') -> {pascal!r}, expected 'HelloWorldExample'"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Output String 'hello-world-example' then 'hello_world_example'")
    def test_case_kebab_and_snake(self, ax):
        app_ready(ax)
        assert rb_enter_devtool(ax, "Case Converter"), \
            f"could not reach Case Converter; labels={labels(ax)[:25]}"
        assert text_areas(ax), "Case Converter Input String text_area not found"

        kebab = case_convert(ax, CASE_INPUT, "kebab-case")
        assert kit.rb_value(norm(kebab), "hello-world-example"), \
            f"kebab-case('{CASE_INPUT}') -> {kebab!r}, expected 'hello-world-example'"

        snake = case_convert(ax, CASE_INPUT, "snake_case")
        assert kit.rb_value(norm(snake), "hello_world_example"), \
            f"snake_case('{CASE_INPUT}') -> {snake!r}, expected 'hello_world_example'"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Output String 'HELLO WORLD EXAMPLE', 'Hello World Example', "
                           "'hello world example'")
    def test_case_upper_lower_start(self, ax):
        app_ready(ax)
        assert rb_enter_devtool(ax, "Case Converter"), \
            f"could not reach Case Converter; labels={labels(ax)[:25]}"
        assert text_areas(ax), "Case Converter Input String text_area not found"

        upper = case_convert(ax, CASE_INPUT, "UPPER CASE", in_settle=0.6, out_settle=0.7)
        assert kit.rb_value(norm(upper), "HELLO WORLD EXAMPLE"), \
            f"UPPER CASE('{CASE_INPUT}') -> {upper!r}, expected 'HELLO WORLD EXAMPLE'"

        start = case_convert(ax, CASE_INPUT, "Start Case", in_settle=0.6, out_settle=0.7)
        assert kit.rb_value(norm(start), "Hello World Example"), \
            f"Start Case('{CASE_INPUT}') -> {start!r}, expected 'Hello World Example'"

        lower = case_convert(ax, CASE_INPUT, "lower case", in_settle=0.6, out_settle=0.7)
        assert kit.rb_value(norm(lower), "hello world example"), \
            f"lower case('{CASE_INPUT}') -> {lower!r}, expected 'hello world example'"


class TestTextTools:
    """Slug Generator (reactive) and Sort Lines (Sort / Revers buttons)."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Output String 'Hello-World!-This-is-a-Test'")
    def test_slug_generator(self, ax):
        app_ready(ax)
        assert rb_enter_devtool(ax, "Slug Generator"), \
            f"could not reach Slug Generator; labels={labels(ax)[:25]}"
        assert text_areas(ax), "Slug Generator Input String text_area not found"

        src = "Hello World! This is a Test"
        set_input(ax, src, settle=1.1)
        out = read_output_robust(ax, exclude=(src,))
        assert kit.rb_value(norm(out), "Hello-World!-This-is-a-Test"), \
            f"slug({src!r}) -> {out!r}, expected 'Hello-World!-This-is-a-Test'"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Sort -> 'apple\\nbanana\\ncherry'; Revers -> 'cherry\\napple\\nbanana'")
    def test_sort_lines_ascending_and_reverse(self, ax):
        app_ready(ax)
        assert rb_enter_devtool(ax, "Sort Lines"), \
            f"could not reach Sort Lines; labels={labels(ax)[:25]}"
        assert text_areas(ax), "Sort Lines Input String text_area not found"

        src = "banana\napple\ncherry"
        set_input(ax, src, settle=0.7)
        assert press_button(ax, "Sort", settle=0.9), "Sort button not found / not pressable"
        sorted_out = read_output_robust(ax, exclude=(src,))
        assert kit.rb_value(norm(sorted_out), "apple\nbanana\ncherry"), \
            f"Sort({src!r}) -> {sorted_out!r}, expected 'apple\\nbanana\\ncherry'"

        set_input(ax, src, settle=0.7)
        assert press_button(ax, "Revers", settle=0.9), "Revers button not found / not pressable"
        rev_out = read_output_robust(ax, exclude=(src,))
        assert kit.rb_value(norm(rev_out), "cherry\napple\nbanana"), \
            f"Revers({src!r}) -> {rev_out!r}, expected 'cherry\\napple\\nbanana'"


URL_SRC = "https://example.com:8080/path/page?x=1&y=2#frag"


class TestUrlParser:
    """Developer Tools > URL Parser: an Input URL decomposed into a Parsed URL table."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Parsed URL rows Protocol=https:, Host=example.com:8080, Port=8080, "
                           "Hostname=example.com, Pathname=/path/page")
    def test_url_parser_components(self, ax):
        app_ready(ax)
        assert rb_enter_devtool(ax, "URL Parser"), \
            f"could not reach URL Parser; labels={labels(ax)[:25]}"
        assert fields(ax) or text_areas(ax), "URL Parser Input URL widget not found"

        set_url(ax, URL_SRC, settle=1.2)
        rows = parsed_rows(ax)
        assert rows, f"Parsed URL table produced no rows for {URL_SRC!r}"

        assert kit.rb_value(rows.get("Protocol"), "https:"), \
            f"Protocol -> {rows.get('Protocol')!r}, expected 'https:' (rows={rows})"
        assert kit.rb_value(rows.get("Host"), "example.com:8080"), \
            f"Host -> {rows.get('Host')!r}, expected 'example.com:8080' (rows={rows})"
        assert kit.rb_value(rows.get("Port"), "8080"), \
            f"Port -> {rows.get('Port')!r}, expected '8080' (rows={rows})"
        assert kit.rb_value(rows.get("Hostname"), "example.com"), \
            f"Hostname -> {rows.get('Hostname')!r}, expected 'example.com' (rows={rows})"
        assert kit.rb_value(rows.get("Pathname"), "/path/page"), \
            f"Pathname -> {rows.get('Pathname')!r}, expected '/path/page' (rows={rows})"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Parsed URL rows Query=?x=1&y=2, Hash=#frag, "
                           "Origin=https://example.com:8080 plus split query x=1, y=2")
    def test_url_parser_query_and_hash(self, ax):
        app_ready(ax)
        assert rb_enter_devtool(ax, "URL Parser"), \
            f"could not reach URL Parser; labels={labels(ax)[:25]}"
        assert fields(ax) or text_areas(ax), "URL Parser Input URL widget not found"

        set_url(ax, URL_SRC, settle=1.2)
        rows = parsed_rows(ax)
        assert rows, f"Parsed URL table produced no rows for {URL_SRC!r}"

        assert kit.rb_value(rows.get("Query"), "?x=1&y=2"), \
            f"Query -> {rows.get('Query')!r}, expected '?x=1&y=2' (rows={rows})"
        assert kit.rb_value(rows.get("Hash"), "#frag"), \
            f"Hash -> {rows.get('Hash')!r}, expected '#frag' (rows={rows})"
        assert kit.rb_value(rows.get("Origin"), "https://example.com:8080"), \
            f"Origin -> {rows.get('Origin')!r}, expected 'https://example.com:8080' (rows={rows})"
        assert kit.rb_value(rows.get("x"), "1"), \
            f"split query x -> {rows.get('x')!r}, expected '1' (rows={rows})"
        assert kit.rb_value(rows.get("y"), "1" if False else "2"), \
            f"split query y -> {rows.get('y')!r}, expected '2' (rows={rows})"


class TestHashing:
    """Developer Tools > Cryptography / Security: Hash + HMAC generators."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Result '5d41402abc4b2a76b9719d911017c592' (MD5 of 'hello')")
    def test_hash_md5(self, ax):
        app_ready(ax)
        assert rb_enter_devtool(ax, "Hash Generator"), \
            f"could not reach Hash Generator; labels={labels(ax)[:25]}"
        assert text_areas(ax), "Hash Generator Input String text_area not found"

        set_input(ax, "hello", settle=1.1)
        out = read_output_robust(ax, exclude=("hello",))
        screenshot_assert(
            "computation_hash_generator",
            "massCode Developer Tools surface, Hash Generator pane. The Input String box "
            "holds 'hello', the Algorithm dropdown shows MD5, and the Result box shows the "
            "32-character hex digest 5d41402abc4b2a76b9719d911017c592. The left rail shows "
            "the Cryptography / Security group with Hash Generator selected.")
        assert kit.rb_value(norm(out), "5d41402abc4b2a76b9719d911017c592"), \
            f"MD5('hello') -> {out!r}, expected '5d41402abc4b2a76b9719d911017c592'"

    @pytest.mark.rb(depth=2, jump_kind="value",
                    expect="Result 'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d' (SHA1) then "
                           "'2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824' "
                           "(SHA256) for 'hello'")
    def test_hash_sha1_and_sha256(self, ax):
        app_ready(ax)
        assert rb_enter_devtool(ax, "Hash Generator"), \
            f"could not reach Hash Generator; labels={labels(ax)[:25]}"
        assert text_areas(ax), "Hash Generator Input String text_area not found"
        set_input(ax, "hello", settle=0.8)

        assert select_option_any(ax, _ALGOS, "SHA1"), \
            f"could not select SHA1 in the Algorithm popup; popups={[p.value for p in popups(ax)]}"
        sha1 = read_output_robust(ax, exclude=("hello",))
        assert kit.rb_value(norm(sha1), "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"), \
            f"SHA1('hello') -> {sha1!r}, expected 'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d'"

        assert select_option_any(ax, ["SHA1"] + _ALGOS, "SHA256"), \
            f"could not select SHA256; popups={[p.value for p in popups(ax)]}"
        sha256 = read_output_robust(ax, exclude=("hello",))
        assert kit.rb_value(
            norm(sha256),
            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"), \
            (f"SHA256('hello') -> {sha256!r}, expected "
             f"'2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'")

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Result 'bade63863c61ed0b3165806ecd6acefc' (HMAC-MD5 of 'hello' "
                           "with key 'secret')")
    def test_hmac_md5(self, ax):
        app_ready(ax)
        assert rb_enter_devtool(ax, "HMAC Generator"), \
            f"could not reach HMAC Generator; labels={labels(ax)[:25]}"
        assert text_areas(ax), "HMAC Generator Input String text_area not found"

        set_input(ax, "hello", settle=0.7)
        flds = fields(ax)
        assert flds, "HMAC Generator Secret Key text_field not found"
        ax.set_value(flds[0].id, "secret")
        time.sleep(1.2)

        out = read_output_robust(ax, exclude=("hello", "secret"))
        assert kit.rb_value(norm(out), "bade63863c61ed0b3165806ecd6acefc"), \
            f"HMAC-MD5('hello','secret') -> {out!r}, expected 'bade63863c61ed0b3165806ecd6acefc'"


class TestCodecs:
    """Developer Tools > Encoders / Decoders: Base64 and URL codecs (Type popup)."""

    @pytest.mark.rb(depth=2, jump_kind="value",
                    expect="Encode 'Hello massCode' -> 'SGVsbG8gbWFzc0NvZGU='; Decode "
                           "'SGVsbG8gbWFzc0NvZGU=' -> 'Hello massCode'")
    def test_base64_encode_and_decode(self, ax):
        app_ready(ax)
        assert rb_enter_devtool(ax, "Base64 Encoder / Decoder"), \
            f"could not reach Base64 Encoder / Decoder; labels={labels(ax)[:25]}"
        assert text_areas(ax), "Base64 Input String text_area not found"

        set_input(ax, "Hello massCode", settle=1.0)
        enc = read_output_robust(ax, exclude=("Hello massCode",))
        assert kit.rb_value(norm(enc), "SGVsbG8gbWFzc0NvZGU="), \
            f"base64 encode('Hello massCode') -> {enc!r}, expected 'SGVsbG8gbWFzc0NvZGU='"

        assert select_option_any(ax, ["Encode", "Decode"], "Decode"), \
            f"could not switch the Type popup to Decode; popups={[p.value for p in popups(ax)]}"
        set_input(ax, "SGVsbG8gbWFzc0NvZGU=", settle=1.0)
        dec = read_output_robust(ax, exclude=("SGVsbG8gbWFzc0NvZGU=",))
        assert kit.rb_value(norm(dec), "Hello massCode"), \
            f"base64 decode('SGVsbG8gbWFzc0NvZGU=') -> {dec!r}, expected 'Hello massCode'"

    @pytest.mark.rb(depth=2, jump_kind="value",
                    expect="Encode 'a b&c=d' -> 'a%20b%26c%3Dd'; Decode 'a%20b%26c%3Dd' "
                           "-> 'a b&c=d'")
    def test_url_encode_and_decode(self, ax):
        app_ready(ax)
        assert rb_enter_devtool(ax, "URL Encoder / Decoder"), \
            f"could not reach URL Encoder / Decoder; labels={labels(ax)[:25]}"
        assert text_areas(ax), "URL codec Input String text_area not found"

        set_input(ax, "a b&c=d", settle=1.0)
        enc = read_output_robust(ax, exclude=("a b&c=d",))
        assert kit.rb_value(norm(enc), "a%20b%26c%3Dd"), \
            f"url encode('a b&c=d') -> {enc!r}, expected 'a%20b%26c%3Dd'"

        assert select_option_any(ax, ["Encode", "Decode"], "Decode"), \
            f"could not switch the Type popup to Decode; popups={[p.value for p in popups(ax)]}"
        set_input(ax, "a%20b%26c%3Dd", settle=1.0)
        dec = read_output_robust(ax, exclude=("a%20b%26c%3Dd",))
        assert kit.rb_value(norm(dec), "a b&c=d"), \
            f"url decode('a%20b%26c%3Dd') -> {dec!r}, expected 'a b&c=d'"


class TestGenerators:
    """Developer Tools > UUID Generator: deterministic SHAPE (RFC-4122 form + Amount)."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Result holds 1 RFC-4122 UUID, then exactly 3 UUID lines for Amount=3")
    def test_uuid_generator_amount(self, ax):
        app_ready(ax)
        assert rb_enter_devtool(ax, "UUID Generator"), \
            f"could not reach UUID Generator; labels={labels(ax)[:25]}"

        assert press_button(ax, "Generate", settle=1.0), "UUID Generate button not found"
        one = uuid_result(ax)
        lines_one = [l.strip() for l in str(one or "").split("\n") if l.strip()]
        shape_ok = bool(lines_one) and bool(re.match(UUID_RE, lines_one[0]))
        assert kit.rb_value(shape_ok, True), \
            f"UUID Result {one!r} does not match {UUID_RE}"

        flds = fields(ax)
        assert flds, "UUID Generator Amount text_field not found"
        ax.set_value(flds[0].id, "3")
        time.sleep(0.6)
        assert press_button(ax, "Generate", settle=1.0), "UUID Generate button not found (2nd press)"

        three = uuid_result(ax)
        lines = [l.strip() for l in str(three or "").split("\n") if l.strip()]
        assert kit.rb_value(len(lines), 3), \
            f"Amount=3 produced {len(lines)} UUID line(s): {three!r}"
        assert len(lines) == 3, f"Amount=3 produced {len(lines)} UUID line(s): {three!r}"
        all_ok = all(bool(re.match(UUID_RE, l)) for l in lines)
        assert kit.rb_value(all_ok, True), f"not every generated line is a UUID: {three!r}"


class TestStorageCount:
    """Preferences > Storage 'N snippets.' — the app's snippet-count computation."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="'N+1 snippets.' after creating one snippet")
    def test_storage_snippet_count_increments(self, ax):
        app_ready(ax)
        go_home(ax)

        assert rb_enter_menu(ax, ["massCode", "Settings…"], settle=1.6), \
            "massCode > Settings… menu item not found"
        press_labelled_group(ax, "Storage")
        time.sleep(1.0)
        n1 = snippet_count(ax)
        screenshot_assert(
            "computation_storage_count",
            "massCode Preferences surface with the Storage pane selected. The left rail "
            "lists Storage / Editor / Markdown / Appearance / Language. The pane shows the "
            "storage path text field with the Move Storage, Open Storage, New Storage and "
            "Reload Storage buttons, the Migrate section (From massCode v1.0 / From "
            "SnippetsLab) and a Count row reading 'N snippets.' — one more than before the "
            "new snippet was created.")
        assert n1 is not None, \
            f"no 'N snippets.' label in Preferences > Storage; labels={labels(ax)[:30]}"

        assert rb_enter_close_surface(ax), "could not leave Preferences"
        assert rb_enter_new_snippet(ax), "File > New Snippet menu item not found"

        assert rb_enter_menu(ax, ["massCode", "Settings…"], settle=1.6), \
            "massCode > Settings… menu item not found (2nd open)"
        press_labelled_group(ax, "Storage")
        time.sleep(1.0)
        n2 = snippet_count(ax)
        assert n2 is not None, \
            f"no 'N snippets.' label after creating a snippet; labels={labels(ax)[:30]}"

        assert kit.rb_value(n2, n1 + 1), \
            f"snippet count went {n1} -> {n2}, expected {n1 + 1}"
        assert n2 == n1 + 1, f"snippet count went {n1} -> {n2}, expected {n1 + 1}"
        rb_enter_close_surface(ax)