zapretgui/tests/test_accessibility_static_guards.py
loop-uh 434eb0d3fb
All checks were successful
Zapret source guards / validate (push) Successful in 12s
Охранные тесты снова зелёные: плитки и матрица BlockCheck открываются с клавиатуры, кнопки тура названы для диктора, wf-priority в каталоге опций
- плитки видов и строки матрицы DNS-серверов получают фокус (Tab), стрелки, Enter и Пробел;
- кнопки карточки тура и пауза схемы получают имя для диктора, строки подсказок редактора — текст для диктора;
- подсказки на подписях и кнопке «назад» идут через set_tooltip, а не setToolTip;
- модель правок редактора переименована TextEdit -> SourceEdit (совпадала по имени с виджетом TextEdit);
- опция wf-priority добавлена в каталог опций winws2 (она есть в оригинальном zapret2);
- стратегия Protocol Mask STUN названа «из «Default v1»» без служебной пометки (game filter);
- тесты приведены к принятым решениям: GitHub первым источником обновления, «Занятые фоновые потоки» при любом зависании,
  объём «~67 КБ» по счёту фильтра, запись zapret_dns_server в настройках DNS, пропуск проверки «только чтение» под root;
  в охранном тесте явно перечислены декоративные виджеты без фокуса и мышиные обработчики без действий.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 15:21:04 +00:00

232 lines
7.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from __future__ import annotations
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
IMPORTANT_CONTROL_MARKERS = (
"PushButton(",
"PrimaryPushButton(",
"ToolButton(",
"PrimaryToolButton(",
"TransparentToolButton(",
"LineEdit(",
"SearchLineEdit(",
"ComboBox(",
"CheckBox(",
"SwitchButton(",
"PlainTextEdit(",
"TextEdit(",
"QListWidget(",
"QTableWidget(",
)
ACCESSIBILITY_MARKERS = (
"set_control_accessibility",
"set_state_text",
"set_item_accessible_text",
"set_segmented_items_accessibility",
"enable_keyboard_click",
"enable_keyboard_toggle",
"accessibility",
)
KEYBOARD_COLLECTION_WIDGET_MARKERS = (
"QListWidget(",
"(QListWidget):",
"ListView(",
"(ListView):",
"QTableWidget(",
"(QTableWidget):",
"TableWidget(",
"(TableWidget):",
"SegmentedWidget(",
)
KEYBOARD_COLLECTION_ACCESS_MARKERS = (
"keyPressEvent",
"focusInEvent",
"currentItemChanged",
"currentChanged",
"currentCellChanged",
"set_segmented_items_accessibility",
"AccessibleTextRole",
"setFocusPolicy(Qt.FocusPolicy.StrongFocus)",
"screenReaderStateText",
"enable_keyboard_click",
"enable_keyboard_toggle",
"set_item_accessible_text",
)
CUSTOM_MOUSE_ACTION_MARKERS = (
"def mousePressEvent",
"def mouseReleaseEvent",
"def mouseDoubleClickEvent",
".mousePressEvent =",
".mouseReleaseEvent =",
".mouseDoubleClickEvent =",
)
CUSTOM_KEYBOARD_ACTION_MARKERS = (
"def keyPressEvent",
".keyPressEvent =",
"enable_keyboard_click",
"enable_keyboard_toggle",
)
# Источники, где обработчики мыши ничего не открывают и не нажимают:
# - button_motion.py лишь рисует лёгкое «нажатие» и передаёт событие настоящей кнопке,
# а Enter и Пробел обрабатывает она сама;
# - mascot.py — талисман, по клику он просто крутится «для настроения»,
# ничто на его сигнал не подписано.
ALLOWED_MOUSE_ONLY_SOURCES = {
"src/ui/button_motion.py",
"src/ui/widgets/fun/mascot.py",
}
# Виджеты без фокуса: либо картинка, через которую проходят мышь и клавиатура
# (тень, снимок карточки, праздничный слой), либо список подсказок редактора,
# у которого фокус остаётся в самом редакторе (стрелки, Enter и Esc приходят оттуда).
ALLOWED_NO_FOCUS_SOURCES = {
"src/profile/ui/profile_geo_notice.py",
"src/ui/code_editor/completion_popup.py",
"src/ui/dialog_static_shadow.py",
"src/ui/holiday_effects.py",
"src/ui/accessibility.py",
"src/ui/segmented_accessibility.py",
"src/ui/window_preset_file_drop.py",
"src/ui/widgets/fluent_scrollbar.py",
"src/ui/widgets/win11_controls.py",
}
def _source(path: str) -> str:
return (ROOT / path).read_text(encoding="utf-8")
def test_ui_files_with_important_controls_keep_accessibility_wiring() -> None:
missing: list[str] = []
for path in sorted((ROOT / "src").rglob("*.py")):
rel_path = path.relative_to(ROOT).as_posix()
if rel_path.startswith("src/themes/cache/"):
continue
source = path.read_text(encoding="utf-8", errors="ignore")
if not any(marker in source for marker in IMPORTANT_CONTROL_MARKERS):
continue
if any(marker in source for marker in ACCESSIBILITY_MARKERS):
continue
missing.append(rel_path)
assert missing == []
def test_collection_controls_keep_keyboard_or_row_accessibility() -> None:
missing: list[str] = []
for path in sorted((ROOT / "src").rglob("*.py")):
rel_path = path.relative_to(ROOT).as_posix()
if rel_path.startswith("src/themes/cache/"):
continue
source = path.read_text(encoding="utf-8", errors="ignore")
if not any(marker in source for marker in KEYBOARD_COLLECTION_WIDGET_MARKERS):
continue
if any(marker in source for marker in KEYBOARD_COLLECTION_ACCESS_MARKERS):
continue
missing.append(rel_path)
assert missing == []
def test_custom_mouse_actions_keep_keyboard_activation() -> None:
missing: list[str] = []
for path in sorted((ROOT / "src").rglob("*.py")):
rel_path = path.relative_to(ROOT).as_posix()
if rel_path.startswith("src/themes/cache/"):
continue
source = path.read_text(encoding="utf-8", errors="ignore")
if not any(marker in source for marker in CUSTOM_MOUSE_ACTION_MARKERS):
continue
if any(marker in source for marker in CUSTOM_KEYBOARD_ACTION_MARKERS):
continue
if rel_path in ALLOWED_MOUSE_ONLY_SOURCES:
continue
missing.append(rel_path)
assert missing == []
def test_no_focus_usage_stays_limited_to_decorative_helpers() -> None:
unexpected: list[str] = []
for path in sorted((ROOT / "src").rglob("*.py")):
rel_path = path.relative_to(ROOT).as_posix()
if rel_path.startswith("src/themes/cache/"):
continue
source = path.read_text(encoding="utf-8", errors="ignore")
if "FocusPolicy.NoFocus" not in source:
continue
if rel_path in ALLOWED_NO_FOCUS_SOURCES:
continue
unexpected.append(rel_path)
assert unexpected == []
def test_profile_shell_keeps_toolbar_accessibility_helper() -> None:
source = _source("src/profile/ui/shell.py")
assert "from profile.ui.shell_accessibility import apply_profile_shell_accessibility" in source
assert "apply_profile_shell_accessibility(" in source
for control_name in (
"add_profile_btn",
"request_btn",
"view_menu_btn",
"order_btn",
"info_btn",
"profile_search_input",
):
assert f"{control_name}={control_name}" in source
def test_user_presets_build_keeps_accessibility_helper_for_toolbar_and_list() -> None:
source = _source("src/presets/ui/common/user_presets_build.py")
assert (
"from presets.ui.common.user_presets_accessibility import apply_user_presets_accessibility"
in source
)
assert source.count("apply_user_presets_accessibility(") >= 2
for control_name in (
"get_configs_btn",
"create_btn",
"import_btn",
"open_folder_btn",
"reset_all_btn",
"presets_info_btn",
"info_btn",
"preset_search_input",
"presets_list",
):
assert f"{control_name}={control_name}" in source
def test_premium_build_keeps_button_accessibility_helper() -> None:
source = _source("src/donater/ui/build.py")
assert "apply_premium_button_accessibility" in source
for keyword in (
"activate_btn=activate_btn",
"open_bot_btn=open_bot_btn",
"refresh_btn=refresh_btn",
"change_key_btn=change_key_btn",
"test_btn=test_btn",
"extend_btn=extend_btn",
):
assert keyword in source
def test_notification_infobar_keeps_accessibility_for_dynamic_actions() -> None:
source = _source("src/ui/window_notification_center.py")
assert "self._set_infobar_accessibility(bar" in source
assert "self._set_infobar_action_button_accessibility(btn, action, button_text)" in source
assert 'name = f"Действие уведомления: {button_text}"' in source