Skip to content

Truly independent web browser

12.8 KB
Raw Blame
"""Historical regression tests — one test per fixed regression, named after the symptom.

Every time we fix an AccessibilityBridge regression, a test for the regression should go here."""

from __future__ import annotations

import pathlib
import sys
import time
import unittest

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))

import gi

gi.require_version("Atspi", "2.0")
from gi.repository import Atspi  # noqa: E402
from harness import AccessibilityBridgeTestCase  # noqa: E402
from harness import EventCollector  # noqa: E402
from harness import wait_for  # noqa: E402
from harness import wait_for_all_by_role  # noqa: E402
from harness import wait_for_descendant_by_role  # noqa: E402


class IKeyOnlyFirstCharRegressionTests(AccessibilityBridgeTestCase):
    """I-key problem.

    Symptom: pressing I in Orca to navigate to the next list item reads only the first character of each wrapping list
    item.

    Root cause: our LineBoundary override for textAtOffset applied visual-line splitting to leaf-like containers — so
    get_string_at_offset(li, 0, LINE) returned the first visual sub-line, rather than the full atomic text.

    Fix: restrict visual-line splitting to non-leaf-like containers."""

    FIXTURE = "listitems.html"

    def test_wrapping_listitem_not_truncated_to_first_char(self):
        items = wait_for_all_by_role(self.doc, "list item")
        self.assertTrue(items, "listitems.html must expose its list items")
        # The narrow ABC listitem wraps one char per line because of width: 20px.
        abc = next(
            (li for li in items if Atspi.Text.get_text(li, 0, Atspi.Text.get_character_count(li)) == "ABC"), None
        )
        self.assertIsNotNone(abc, "expected the narrow 'ABC' list item in the fixture")
        r = Atspi.Text.get_string_at_offset(abc, 0, Atspi.TextGranularity.LINE)
        self.assertEqual(
            r.content, "ABC", f"Orca would speak {r.content!r} instead of 'ABC' — I-key regression is back"
        )


class SayAllSkipsPostLinkProseRegressionTests(AccessibilityBridgeTestCase):
    """Say All used to jump link-to-link, silently dropping all non-link prose.

    Root cause: Qt's bridge exposes no AtkHypertext/AtkHyperlink, so Orca's _find_next_caret_in_order_internal, on
    exiting a link, failed its start+1 == end range-in-parent check and fell back to AXObject.get_next_sibling — which
    (because text-leaves are hidden) is always the next link.

    Fix: Orca-side hypertext fallback relying on the Nth U+FFFC marker in a paragraph corresponding to the Nth AT-SPI2
    exposed child.

    This test doesn't check the fix directly — it checks the underlying invariant the fix relies on."""

    FIXTURE = "paragraphs.html"

    def test_fffc_markers_align_with_exposed_children(self):
        ps = wait_for_all_by_role(self.doc, "paragraph")
        self.assertTrue(ps, "paragraphs.html must expose its paragraphs")
        for p in ps:
            count = Atspi.Text.get_character_count(p)
            text = Atspi.Text.get_text(p, 0, count) if count else ""
            fffc_positions = [i for i, c in enumerate(text) if c == ""]
            child_count = p.get_child_count()
            self.assertEqual(
                len(fffc_positions),
                child_count,
                f"paragraph with text {text!r} has {len(fffc_positions)} U+FFFC but "
                f"{child_count} exposed children — Orca's hypertext fallback will misalign",
            )


class TextLeafDuplicationRegressionTests(AccessibilityBridgeTestCase):
    """Flat review used to read link text twice ("See here for details here").

    Root cause: a paragraph exposed both its own Atspi.Text (with U+FFFC at link positions) *and* text-leaf children as
    AT-SPI2 children. Flat review built zones for both — duplicate coverage.

    Fix: collect_exposed_children hides text-leaf children for every container."""

    FIXTURE = "paragraphs.html"

    def test_paragraphs_expose_only_embedded_object_children(self):
        ps = wait_for_all_by_role(self.doc, "paragraph")
        self.assertTrue(ps, "paragraphs.html must expose its paragraphs")
        for p in ps:
            n = p.get_child_count()
            for i in range(n):
                child = p.get_child_at_index(i)
                self.assertNotEqual(
                    child.get_role_name(),
                    "text leaf",
                    "paragraph must not expose text-leaf children; flat review would duplicate-read",
                )


class WrappingTextYCollapseRegressionTests(AccessibilityBridgeTestCase):
    """Inline text in a wrapping paragraph used to report y=0 for every character.

    Root cause: LibWeb looked at the text node's own paintable for fragments, but inline text uses the containing
    block's PaintableWithLines.

    Fix: walk up to containing block, filter fragments by layout_node."""

    FIXTURE = "paragraphs.html"

    def test_wrapping_text_has_distinct_y_per_visual_line(self):
        ps = wait_for_all_by_role(self.doc, "paragraph")
        wrapping = next(
            (
                p
                for p in ps
                if "deliberately long paragraph" in Atspi.Text.get_text(p, 0, Atspi.Text.get_character_count(p))
            ),
            None,
        )
        self.assertIsNotNone(wrapping)
        count = Atspi.Text.get_character_count(wrapping)
        ys = {
            Atspi.Text.get_character_extents(wrapping, i, Atspi.CoordType.SCREEN).y
            for i in range(count)
            if (
                Atspi.Text.get_character_extents(wrapping, i, Atspi.CoordType.SCREEN).width,
                Atspi.Text.get_character_extents(wrapping, i, Atspi.CoordType.SCREEN).height,
            )
            != (0, 0)
        }
        self.assertGreater(len(ys), 1, f"wrapping text characters all share y={ys} — the y-collapse regression is back")


class ListAdvertisesTextRegressionTests(AccessibilityBridgeTestCase):
    """<ul>/<ol> (role 'list') used to advertise Text, and Orca skipped the whole list in Say All.

    Root cause: all containers exposed Text by default. A list's text is [U+FFFC][U+FFFC][U+FFFC]… (one marker per
    listitem) — and without Hypertext Orca can't expand the markers, so it silently skipped listitems in Say All.

    Fix: list role explicitly excluded from TextInterface."""

    FIXTURE = "listitems.html"

    def test_list_does_not_advertise_text(self):
        from harness import supports_interface

        lst = wait_for_descendant_by_role(self.doc, "list")
        self.assertIsNotNone(lst)
        self.assertFalse(
            supports_interface(lst, "text"), "list must *not* advertise Text; otherwise Orca skips it during Say All"
        )


class ParagraphMappedToSectionRegressionTests(AccessibilityBridgeTestCase):
    """<p> used to map to role 'section', breaking Orca's Say All sentence extension.

    Root cause: no explicit paragraph role mapping; fell through to the section default. Orca's is_text_block_element
    requires ROLE_PARAGRAPH to stop walking across <p>.

    Fix: explicit paragraph role mapping."""

    FIXTURE = "roles.html"

    def test_paragraph_has_role_paragraph(self):
        ps = wait_for_all_by_role(self.doc, "paragraph")
        self.assertGreater(len(ps), 0, "no paragraph-role accessibles found — regression to section mapping is back")


class TreeUpdatesUnderContinuousMutationTests(AccessibilityBridgeTestCase):
    """A page that mutates faster than WebContent's tree-update interval still gets its tree updated.

    ticker.html rewrites its status paragraph every 50 ms. WebContent coalesces mutations into one tree update per
    200 ms (PageClient::schedule_accessibility_tree_update); a timer that every mutation restarted would never fire for
    this page, and the AT would keep the first tree for good."""

    FIXTURE = "ticker.html"

    def _status_text(self):
        paragraph = wait_for_descendant_by_role(
            self.doc, "paragraph", pred=lambda obj: Atspi.Text.get_text(obj, 0, -1).startswith("Tick ")
        )
        self.assertIsNotNone(paragraph, "ticker.html must expose its status paragraph")
        return Atspi.Text.get_text(paragraph, 0, -1)

    def test_status_text_keeps_changing(self):
        initial = self._status_text()
        self.assertTrue(initial.startswith("Tick "), f"the status paragraph reads {initial!r}")
        # An AT's action on the page is what turns the mutation-driven tree updates on (Page::accessibility_interested),
        # so focus the page's link first, as Orca does when it lands on a page.
        link = wait_for_descendant_by_role(self.doc, "link", name="Status")
        self.assertIsNotNone(link, "ticker.html must expose its link")
        names = [Atspi.Action.get_action_name(link, i) for i in range(Atspi.Action.get_n_actions(link))]
        index = next((i for i, name in enumerate(names) if "focus" in name.lower()), None)
        self.assertIsNotNone(index, f"the link advertises no setFocus action; actions: {names}")
        self.assertTrue(Atspi.Action.do_action(link, index), "the setFocus action failed")
        self.assertTrue(
            wait_for(lambda: self._status_text() != initial, timeout=5.0, description="the status paragraph to change"),
            f"the tree never updated after the AT's action: the status paragraph still reads {initial!r}",
        )
        # And the updates have to keep coming: a timer that every mutation restarted would fire once at most.
        first = self._status_text()
        time.sleep(1.5)
        second = self._status_text()
        self.assertNotEqual(first, second, f"the tree stopped updating: the status paragraph still reads {first!r}")


class HiddenTabPostsNoElementFocusTests(AccessibilityBridgeTestCase):
    """A hidden tab's page focusing one of its elements posts no focus event; the focus is announced once the tab is
    back.

    hidden_tab_focus.html focuses its link when its document becomes hidden, which is what opening a second tab through
    the File menu's New Tab item does to it — so the focus lands while the page sits in a hidden tab, whatever the
    harness's timing. A focus event for it would pull Orca into a tab the user isn't looking at, through an interface
    hideEvent() had deregistered. WebContentView::on_accessibility_focus_changed skips a hidden view's element focus,
    the way notify_accessibility_focus_on_document_root() skips its document focus; the tree keeps the focus, and
    focusInEvent() re-announces it when the tab is current again — closing the second tab makes it so, and the
    window gives the view the keyboard focus back."""

    FIXTURE = "hidden_tab_focus.html"

    def test_hidden_tab_link_focus_posts_no_event(self):
        link = wait_for_descendant_by_role(self.doc, "link", name="Hidden tab link")
        self.assertIsNotNone(link, "hidden_tab_focus.html must expose its link")
        new_tab = wait_for_descendant_by_role(self.app, Atspi.Role.MENU_ITEM, name="New Tab")
        self.assertIsNotNone(new_tab, "the File menu's New Tab item isn't on the bus")
        close_tab = wait_for_descendant_by_role(self.app, Atspi.Role.MENU_ITEM, name="Close Current Tab")
        self.assertIsNotNone(close_tab, "the File menu's Close Current Tab item isn't on the bus")

        collector = EventCollector("object:state-changed:focused")
        self.addCleanup(collector.close)
        collector.pump(0.5)

        self.assertTrue(Atspi.Action.do_action(new_tab, 0), "pressing the New Tab menu item failed")
        # The page focuses its link as soon as its document is hidden, and the page keeps running in the hidden tab.
        collector.pump(3.0)

        gained = [(role, name) for _type, detail1, role, name in collector.events if detail1 == 1]
        self.assertNotIn(
            ("link", "Hidden tab link"),
            gained,
            f"the hidden tab's link focus was posted; events: {collector.events}",
        )

        # Back in the tab, the focus the page took while hidden is there to announce: the link reports it, and the
        # view's focusInEvent() posts it. Both prove the fixture did focus the link while hidden.
        del collector.events[:]
        self.assertTrue(Atspi.Action.do_action(close_tab, 0), "pressing the Close Current Tab menu item failed")
        focused_link = wait_for_descendant_by_role(
            self.app,
            "link",
            name="Hidden tab link",
            pred=lambda obj: obj.get_state_set().contains(Atspi.StateType.FOCUSED),
            timeout=10.0,
        )
        self.assertIsNotNone(focused_link, "the focus the page took while its tab was hidden isn't on the link")
        collector.pump(1.0)
        gained = [(role, name) for _type, detail1, role, name in collector.events if detail1 == 1]
        self.assertIn(
            ("link", "Hidden tab link"),
            gained,
            f"the link's focus wasn't re-announced when its tab came back; events: {collector.events}",
        )


if __name__ == "__main__":
    unittest.main()