release: Евномия, новая версия, линейка юристов
This commit is contained in:
@@ -0,0 +1,422 @@
|
||||
#!/usr/bin/env python3
|
||||
"""UI Stack regression probe: every check is named after the audit defect it guards (Д-001…Д-008).
|
||||
|
||||
Run: python3 eunomia/tests/ui_stack_check.py [--out REPORT.json]
|
||||
Needs a running Eunomia at EUNOMIA_URL (default http://127.0.0.1:18765), Python Playwright with Chromium
|
||||
and axe-core: AXE_CORE or eunomia/frontend/node_modules/axe-core/axe.min.js (npm ci in eunomia/frontend).
|
||||
Exit code 1 on any failed check. A crashed section is a failed check, not silence.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
from playwright.sync_api import sync_playwright
|
||||
from chromium import executable
|
||||
|
||||
BASE = os.environ.get('EUNOMIA_URL', 'http://127.0.0.1:18765').rstrip('/')
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
AXE = Path(os.environ.get('AXE_CORE') or ROOT / 'frontend/node_modules/axe-core/axe.min.js')
|
||||
RESEARCH = ROOT / 'frontend/src/pantheon/Research.tsx'
|
||||
HOME = str(Path.home())
|
||||
SCREENS = {
|
||||
'главная': ('/', '.p-stone'),
|
||||
'поиск': ('/#view=search&q=395', '.p-result, .p-empty-scene'),
|
||||
'читатель': ('/#doc=legal-corpus%3Acode%3Atk-rf&fragment=doc%3Alegal-corpus%3Acode%3Atk-rf_article_395', 'main h1'),
|
||||
'граф': ('/#view=graph', '.p-force-canvas canvas'),
|
||||
'служба': ('/#view=updates', '.p-job'),
|
||||
}
|
||||
LANDMARK = ('nav, aside, main, header, footer, [role=navigation], [role=complementary], [role=main], '
|
||||
'[role=banner], [role=contentinfo], [role=region][aria-label], section[aria-label], form[aria-label]')
|
||||
# Roles that accept an accessible name from aria-label (ARIA 1.2); generic <div>/<span> do not.
|
||||
NAMED_ROLES = {'region', 'group', 'img', 'figure', 'application', 'navigation', 'complementary', 'main', 'form', 'search'}
|
||||
# Colour maths as in the fixed WCAG-143 block of qa/ui-stack-2026-09-22/scripts/audit.py:
|
||||
# color(srgb r g b / a) is 0..1 per channel, translucent layers are composited down to the first opaque one.
|
||||
CONTRAST = """() => {
|
||||
const parse = s => {const m=s.match(/^color\\(srgb ([\\d.]+) ([\\d.]+) ([\\d.]+)(?: \\/ ([\\d.]+))?\\)/);
|
||||
if(m) return [m[1]*255, m[2]*255, m[3]*255, m[4]===undefined?1:+m[4]];
|
||||
const n=s.match(/[\\d.]+/g).map(Number); return [n[0], n[1], n[2], n.length>3?n[3]:1]};
|
||||
const over = (top, under) => [0,1,2].map(i => top[i]*top[3] + under[i]*(1-top[3])).concat(1);
|
||||
const bgOf = el => {const layers=[]; for(let e=el; e; e=e.parentElement){const c=parse(getComputedStyle(e).backgroundColor); if(c[3]>0){layers.push(c); if(c[3]>=1) break}}
|
||||
return layers.reverse().reduce((bg, layer) => over(layer, bg), [255,255,255,1])};
|
||||
const lum = c => {const [r,g,b]=c.slice(0,3).map(v=>{v/=255;return v<=0.03928?v/12.92:Math.pow((v+0.055)/1.055,2.4)}); return 0.2126*r+0.7152*g+0.0722*b};
|
||||
const ratioOf = (fg, bg) => {const L1=lum(over(fg, bg)), L2=lum(bg); return (Math.max(L1,L2)+0.05)/(Math.min(L1,L2)+0.05)};
|
||||
const measure = el => {const cs=getComputedStyle(el); const px=parseFloat(cs.fontSize), w=parseInt(cs.fontWeight)||400;
|
||||
const need=(px>=24 || (px>=18.66 && w>=700)) ? 3 : 4.5; const ratio=ratioOf(parse(cs.color), bgOf(el));
|
||||
return {color: cs.color, px, ratio: +ratio.toFixed(2), need, pass: ratio >= need}};
|
||||
const rows = [];
|
||||
for (const s of ['.p-hero-copy > p:not(.p-eyebrow)','.p-stone-face span','.p-stone-face small','.p-catalog-total','.p-local-note','.p-tabs a:not([aria-current])','.p-sidebar-note','.p-brand small','.p-eyebrow','.p-tabs span']) {
|
||||
const el = document.querySelector(s); if (el) rows.push({sel: s, ...measure(el)})}
|
||||
const selfcheck = +ratioOf(parse('rgb(88, 101, 121)'), over(parse('color(srgb 1 1 1 / 0.97)'), [255,255,255,1])).toFixed(2);
|
||||
const probe = document.createElement('span'); probe.textContent = 'контроль';
|
||||
probe.style.cssText = 'color: rgb(150, 150, 150); font-size: 12px';
|
||||
(document.querySelector('.p-topbar') || document.body).appendChild(probe);
|
||||
const control = measure(probe); probe.remove();
|
||||
return {rows, selfcheck, control}
|
||||
}"""
|
||||
|
||||
|
||||
def state_labels():
|
||||
"""Human labels of the queue states, read from the component itself so the probe cannot drift from it."""
|
||||
text = RESEARCH.read_text(encoding='utf-8')
|
||||
block = re.search(r'const states[^=]*=\s*\{([^}]*)\}', text)
|
||||
if not block:
|
||||
raise RuntimeError('в Research.tsx не найден словарь states: проба не знает подписей состояний')
|
||||
return dict(re.findall(r"(\w+)\s*:\s*'([^']*)'", block.group(1)))
|
||||
|
||||
|
||||
def status_fixture(real):
|
||||
"""440 jobs in every state, shaped like the live /api/status answer; one failed job carries a home-path error."""
|
||||
template = {'resource_hash': '0' * 64, 'state': 'current', 'priority': 0, 'attempts': 1, 'available_at': None,
|
||||
'lease_until': None, 'progress': {'done': 0, 'pending_count': 0, 'total': 0}, 'detail': None,
|
||||
'freshness': 'unknown', 'availability': 'unknown', 'created_at': 0, 'updated_at': 0, 'started_at': None,
|
||||
'finished_at': None, 'last_checked': None, 'last_updated': None, 'pending_resource_hash': None,
|
||||
'id': 'legal-corpus:code:gk-rf', 'local_file_present': True}
|
||||
live = [job for job in real.get('jobs') or [] if isinstance(job, dict)]
|
||||
cycle = ['deferred', 'blocked', 'failed', 'current', 'updated', 'queued', 'running']
|
||||
jobs = []
|
||||
for i in range(440):
|
||||
job = dict(live[i % len(live)] if live else template)
|
||||
job.update(id=f"{job.get('id') or 'probe'}#probe-{i}", resource_hash=f'{i:064x}', state=cycle[i % len(cycle)])
|
||||
jobs.append(job)
|
||||
missing = Path(HOME, 'Проекты', 'themiz', '.agent', 'maintenance', 'background', 'jobs', '829828fc-probe', 'original.body')
|
||||
jobs[2]['detail'] = f"[Errno 2] No such file or directory: '{missing}'"
|
||||
return {**real, 'jobs': jobs}, bool(live)
|
||||
|
||||
|
||||
class Check:
|
||||
def __init__(self, browser):
|
||||
self.results, self.errors = [], []
|
||||
self.context = browser.new_context(viewport={'width': 1440, 'height': 900})
|
||||
# CDP init script bypasses the app's CSP script-src 'self' without weakening it.
|
||||
self.context.add_init_script(AXE.read_text(encoding='utf-8'))
|
||||
self.page = self.context.new_page()
|
||||
self.page.set_default_timeout(30000)
|
||||
self.page.on('pageerror', lambda error: self.errors.append(f'pageerror: {error}'))
|
||||
self.page.on('console', lambda message: self.errors.append(f'console: {message.text}') if message.type == 'error' else None)
|
||||
for path in ('**/api/update', '**/api/graph/rebuild', '**/api/practice/refresh'):
|
||||
self.page.route(path, lambda route: route.fulfill(status=200, content_type='application/json', body='{"detail":"mock"}'))
|
||||
|
||||
def check(self, name, ok, detail=''):
|
||||
self.results.append({'name': name, 'ok': bool(ok), 'detail': detail})
|
||||
|
||||
def info(self, name, detail):
|
||||
self.results.append({'name': name, 'ok': True, 'info': True, 'detail': detail})
|
||||
|
||||
def section(self, name, run):
|
||||
try:
|
||||
run()
|
||||
except Exception as error: # a crash is a red check with its cause, never silence
|
||||
self.check(f'{name}: раздел выполнен до конца', False, f'{type(error).__name__}: {str(error)[:400]}')
|
||||
|
||||
def open(self, route, ready, wait=700):
|
||||
self.page.goto(BASE + route, wait_until='domcontentloaded')
|
||||
self.page.wait_for_selector(ready)
|
||||
self.page.wait_for_timeout(wait)
|
||||
|
||||
def fragment(self):
|
||||
return parse_qs(urlsplit(self.page.url).fragment)
|
||||
|
||||
def axe(self, rules=None):
|
||||
options = {'resultTypes': ['violations']}
|
||||
if rules:
|
||||
options['runOnly'] = {'type': 'rule', 'values': rules}
|
||||
return self.page.evaluate("""async options => (await axe.run(document, options)).violations
|
||||
.map(v => ({id: v.id, impact: v.impact, nodes: v.nodes.length, target: v.nodes[0] && v.nodes[0].target}))""", options)
|
||||
|
||||
def use_status_fixture(self):
|
||||
real = self.page.request.get(BASE + '/api/status').json()
|
||||
fixture, live = status_fixture(real)
|
||||
if not live:
|
||||
self.info('Д-003 фикстура очереди', 'живых заданий нет: шаблон задания взят из кода пробы, а не из ответа сервера')
|
||||
body = json.dumps(fixture, ensure_ascii=False)
|
||||
self.page.route('**/api/status*', lambda route: route.fulfill(status=200, content_type='application/json', body=body))
|
||||
|
||||
def screens(self):
|
||||
self.use_status_fixture()
|
||||
for name, (route, ready) in SCREENS.items():
|
||||
self.open(route, ready, 3000 if name == 'граф' else 900)
|
||||
dangling = self.page.evaluate("""() => [...document.querySelectorAll('[aria-controls]')].flatMap(el =>
|
||||
el.getAttribute('aria-controls').split(/\\s+/).filter(id => id && !document.getElementById(id))
|
||||
.map(id => ({id, el: el.outerHTML.slice(0, 120)})))""")
|
||||
self.check(f'Д-001 aria-controls ведёт на существующий узел: {name}', not dangling, dangling[:3])
|
||||
violations = self.axe()
|
||||
region = [v for v in violations if v['id'] == 'region']
|
||||
self.check(f'Д-007 всё содержимое внутри landmark (axe region): {name}', not region, region)
|
||||
self.check(f'общее: ноль нарушений axe: {name}', not violations, violations)
|
||||
if name == 'главная':
|
||||
outside = self.page.evaluate(f"""() => [...document.querySelectorAll('[data-sidebar="header"]')]
|
||||
.filter(el => !el.closest({json.dumps(LANDMARK)})).length""")
|
||||
self.check('Д-007 шапка сайдбара лежит в landmark', outside == 0, f'вне landmark: {outside}')
|
||||
if name == 'граф':
|
||||
prohibited = [v for v in violations if v['id'] == 'aria-prohibited-attr']
|
||||
self.check('Д-006 aria-label без допустимой роли (axe aria-prohibited-attr): граф', not prohibited, prohibited)
|
||||
canvas = self.page.evaluate("""() => {const el = document.querySelector('.p-force-canvas');
|
||||
return el && {role: el.getAttribute('role'), label: el.getAttribute('aria-label')}}""")
|
||||
self.check('Д-006 поверхность графа названа через роль, которая принимает имя',
|
||||
bool(canvas and canvas['role'] in NAMED_ROLES and (canvas['label'] or '').strip()), canvas)
|
||||
if name == 'читатель':
|
||||
self.page.wait_for_selector('.p-context', timeout=20000)
|
||||
self.page.wait_for_timeout(800)
|
||||
bare = self.page.evaluate("""() => [...document.querySelectorAll('aside *, .p-context *')]
|
||||
.filter(e => e.children.length === 0 && /^\\d+$/.test((e.textContent || '').trim())
|
||||
&& !(e.getAttribute('aria-label') || e.getAttribute('title')))
|
||||
.slice(0, 4).map(e => ({tag: e.tagName, cls: String(e.className).slice(0, 30), text: e.textContent.trim()}))""")
|
||||
self.check('Д-008 в панели контекста нет голых чисел без имени', not bare, bare)
|
||||
self.page.unroute('**/api/status*')
|
||||
|
||||
def search_box(self):
|
||||
self.open('/', '.p-stone')
|
||||
self.page.keyboard.press('Tab')
|
||||
skip = self.page.evaluate("() => String(document.activeElement.className)")
|
||||
self.check('сохранено: первый Tab ведёт на skip-link', 'p-skip' in skip, skip)
|
||||
self.page.keyboard.press('Escape')
|
||||
search_label = "() => document.activeElement.getAttribute('aria-label') || ''"
|
||||
self.page.keyboard.press('Meta+k')
|
||||
self.page.wait_for_timeout(200)
|
||||
if 'Поиск' not in self.page.evaluate(search_label):
|
||||
self.page.keyboard.press('Control+k')
|
||||
self.page.wait_for_timeout(200)
|
||||
self.check('сохранено: Cmd/Ctrl+K фокусирует поиск', 'Поиск' in self.page.evaluate(search_label))
|
||||
self.page.keyboard.type('395')
|
||||
self.page.wait_for_selector('.p-suggestions [cmdk-item]', timeout=15000)
|
||||
state = """() => {const el = document.activeElement; const ids = (el.getAttribute('aria-controls') || '').split(/\\s+/).filter(Boolean);
|
||||
return {label: el.getAttribute('aria-label') || '', expanded: el.getAttribute('aria-expanded'), ids,
|
||||
missing: ids.filter(id => !document.getElementById(id)), lists: document.querySelectorAll('.p-suggestions').length}}"""
|
||||
opened = self.page.evaluate(state)
|
||||
self.check('Д-001 открытый список: aria-controls указывает на живой список',
|
||||
opened['ids'] and not opened['missing'] and opened['expanded'] == 'true', opened)
|
||||
self.page.keyboard.press('Escape')
|
||||
self.page.wait_for_timeout(200)
|
||||
closed = self.page.evaluate(state)
|
||||
self.check('Д-001 Escape закрывает подсказки и держит фокус в поле', closed['lists'] == 0 and 'Поиск' in closed['label'], closed)
|
||||
self.check('Д-001 закрытый список: aria-controls не висит в пустоте', not closed['missing'], closed)
|
||||
self.page.keyboard.press('Enter')
|
||||
self.page.wait_for_timeout(1200)
|
||||
self.check('сохранено: Enter в поиске даёт q= в URL', self.fragment().get('q') == ['395'], self.page.url)
|
||||
|
||||
def pagination_label(self):
|
||||
return self.page.locator('.p-pagination span').first.inner_text()
|
||||
|
||||
def first_row(self):
|
||||
return self.page.locator('.p-document-row').first.inner_text()
|
||||
|
||||
def catalog_pages(self):
|
||||
self.open('/#view=category&kind=plenum', '.p-pagination')
|
||||
self.page.locator('.p-pagination-actions button', has_text='Следующая').click()
|
||||
self.page.wait_for_timeout(500)
|
||||
label, second = self.pagination_label(), self.first_row()
|
||||
self.check('Д-002 «Следующая» пишет страницу в URL', self.fragment().get('page') == ['2'] and 'страница 2' in label,
|
||||
{'url': self.page.url, 'label': label})
|
||||
self.page.reload(wait_until='domcontentloaded')
|
||||
self.page.wait_for_selector('.p-pagination')
|
||||
self.page.wait_for_timeout(700)
|
||||
self.check('Д-002 перезагрузка держит страницу 2', 'страница 2' in self.pagination_label() and self.first_row() == second,
|
||||
self.pagination_label())
|
||||
self.page.go_back(wait_until='domcontentloaded')
|
||||
self.page.wait_for_timeout(900)
|
||||
back = self.page.locator('.p-pagination').count() and self.pagination_label()
|
||||
self.check('Д-002 Back возвращает страницу 1 того же каталога',
|
||||
self.fragment().get('kind') == ['plenum'] and bool(back) and 'страница 1' in back, {'url': self.page.url, 'label': back})
|
||||
|
||||
def catalog_filters(self):
|
||||
self.open('/#view=category&kind=plenum', '.p-topic')
|
||||
before = self.page.url
|
||||
self.page.locator('.p-topic').first.click()
|
||||
self.page.wait_for_timeout(500)
|
||||
row = self.first_row()
|
||||
self.check('Д-002 тема пишется в URL', self.page.url != before and 'topic' in self.fragment(), self.page.url)
|
||||
self.page.reload(wait_until='domcontentloaded')
|
||||
self.page.wait_for_selector('.p-document-row')
|
||||
self.page.wait_for_timeout(700)
|
||||
self.check('Д-002 перезагрузка держит тему', self.first_row() == row, self.page.url)
|
||||
self.open('/#view=category&kind=plenum', '.p-pagination')
|
||||
selects = self.page.locator('main select')
|
||||
selects.nth(0).select_option('old')
|
||||
self.page.wait_for_timeout(400)
|
||||
self.check('Д-002 сортировка пишется в URL', self.fragment().get('sort') == ['old'], self.page.url)
|
||||
# Year options carry no value attribute (<option>{year}</option>): pick by index, read select.value.
|
||||
selects.nth(1).select_option(index=1)
|
||||
self.page.wait_for_timeout(400)
|
||||
year = selects.nth(1).evaluate('select => select.value')
|
||||
self.check('Д-002 год пишется в URL', bool(year) and self.fragment().get('year') == [year], self.page.url)
|
||||
|
||||
def document_list(self):
|
||||
# Live corpus has at most 5 documents per non-plenum kind, so DocumentList never pages on real data:
|
||||
# the bootstrap answer is inflated to 30 federal laws built from the live ones.
|
||||
real = self.page.request.get(BASE + '/api/bootstrap').json()
|
||||
laws = [d for d in real.get('documents', []) if d.get('kind') == 'federal-law']
|
||||
if not laws:
|
||||
self.info('Д-002 DocumentList', 'в корпусе нет федеральных законов: пагинацию списка проверить не на чем')
|
||||
return
|
||||
extra = [{**laws[i % len(laws)], 'id': f"{laws[i % len(laws)]['id']}#probe-{i}"} for i in range(30)]
|
||||
body = json.dumps({**real, 'documents': [d for d in real['documents'] if d.get('kind') != 'federal-law'] + extra}, ensure_ascii=False)
|
||||
self.page.route('**/api/bootstrap*', lambda route: route.fulfill(status=200, content_type='application/json', body=body))
|
||||
try:
|
||||
self.page.goto('about:blank') # a hash-only goto keeps the loaded bootstrap; force a real load
|
||||
self.open('/#view=category&kind=federal-law', '.p-pagination')
|
||||
self.page.locator('.p-pagination-actions button', has_text='Следующая').click()
|
||||
self.page.wait_for_timeout(500)
|
||||
self.check('Д-002 DocumentList: страница в URL', self.fragment().get('page') == ['2'], self.page.url)
|
||||
self.page.reload(wait_until='domcontentloaded')
|
||||
self.page.wait_for_selector('.p-pagination')
|
||||
self.page.wait_for_timeout(600)
|
||||
self.check('Д-002 DocumentList: перезагрузка держит страницу', 'страница 2' in self.pagination_label(), self.pagination_label())
|
||||
finally:
|
||||
self.page.unroute('**/api/bootstrap*')
|
||||
self.page.goto('about:blank')
|
||||
|
||||
def rows(self):
|
||||
return self.page.locator('.p-job').all_inner_texts()
|
||||
|
||||
def pick_state(self, label):
|
||||
"""Choose a queue state through whatever control the queue offers: <select> option or button/link."""
|
||||
chosen = self.page.evaluate("""label => {
|
||||
for (const select of document.querySelectorAll('.p-jobs select')) {
|
||||
const option = [...select.options].find(o => o.textContent.includes(label));
|
||||
if (option) { select.value = option.value; select.dispatchEvent(new Event('change', {bubbles: true})); return 'select' } }
|
||||
const control = [...document.querySelectorAll('.p-jobs button, .p-jobs a[href], .p-jobs [role=tab], .p-jobs [role=radio]')]
|
||||
.find(e => e.textContent.includes(label));
|
||||
if (control) { control.click(); return 'click' }
|
||||
return null }""", label)
|
||||
self.page.wait_for_timeout(600)
|
||||
return chosen
|
||||
|
||||
def queue(self, labels):
|
||||
self.use_status_fixture()
|
||||
self.open('/#view=updates', '.p-job', 1000)
|
||||
size = self.page.evaluate("() => ({rows: document.querySelectorAll('.p-job').length, height: document.documentElement.scrollHeight})")
|
||||
self.check('Д-003 по умолчанию строк не больше 50', 0 < size['rows'] <= 50, size)
|
||||
self.check('Д-003 высота страницы не больше 20 000 px', size['height'] <= 20000, size)
|
||||
calm = [labels['current'], labels['updated']]
|
||||
noisy = [row[:80] for row in self.rows() if any(word in row for word in calm)]
|
||||
self.check('Д-003 по умолчанию показано то, что требует внимания', not noisy, noisy[:3])
|
||||
controls = self.page.evaluate("""() => [...document.querySelectorAll('.p-jobs option, .p-jobs button, .p-jobs a[href], .p-jobs [role=tab], .p-jobs [role=radio]')]
|
||||
.map(e => e.textContent.trim())""")
|
||||
wanted = [labels[key] for key in ('deferred', 'blocked', 'failed', 'current', 'updated')]
|
||||
absent = [label for label in wanted if not any(label in text for text in controls)]
|
||||
self.check('Д-003 фильтр по пяти состояниям стоит в очереди', not absent, {'нет подписей': absent})
|
||||
more = self.page.locator('.p-jobs button:not([disabled]), .p-jobs a[href]').filter(has_text=re.compile('Следующ|Далее|Ещё|ещё|Показать'))
|
||||
self.check('Д-003 остальное открывается явным действием', more.count() > 0, more.count())
|
||||
if more.count():
|
||||
first = self.rows()[0]
|
||||
more.first.click()
|
||||
self.page.wait_for_timeout(600)
|
||||
self.check('Д-003 явное действие показывает следующую порцию', self.rows() and self.rows()[0] != first)
|
||||
how = self.pick_state(labels['current'])
|
||||
chosen = self.rows()
|
||||
self.check(f"Д-003 фильтр «{labels['current']}» оставляет только такие задания",
|
||||
how is not None and 0 < len(chosen) <= 50 and all(labels['current'] in row for row in chosen),
|
||||
{'control': how, 'rows': len(chosen)})
|
||||
self.page.unroute('**/api/status*')
|
||||
|
||||
def error_copy(self, labels):
|
||||
self.use_status_fixture()
|
||||
self.open('/#view=updates', '.p-job', 1000)
|
||||
find = """() => {document.querySelectorAll('.p-job details').forEach(d => d.open = true);
|
||||
return [...document.querySelectorAll('.p-job details')].findIndex(d => d.textContent.includes('Errno 2'))}"""
|
||||
index = self.page.evaluate(find)
|
||||
if index < 0 and self.pick_state(labels['failed']):
|
||||
index = self.page.evaluate(find)
|
||||
self.check('Д-004 задание с ошибкой найдено в очереди', index >= 0, index)
|
||||
if index < 0:
|
||||
return
|
||||
copy = self.page.evaluate("""([index, home]) => {const d = document.querySelectorAll('.p-job details')[index];
|
||||
const first = d.querySelector('p');
|
||||
const raw = [...d.querySelectorAll('*')].reverse().find(e => e.textContent.includes('Errno 2'));
|
||||
return {first: first ? first.innerText : null,
|
||||
rawBelow: !!(first && raw && raw !== first && !raw.contains(first) && !first.contains(raw)
|
||||
&& (first.compareDocumentPosition(raw) & Node.DOCUMENT_POSITION_FOLLOWING)),
|
||||
homeVisible: document.body.innerText.includes(home)}}""", [index, HOME])
|
||||
human = copy['first'] or ''
|
||||
self.check('Д-004 первой идёт понятная причина, а не сырая ошибка',
|
||||
bool(human.strip()) and not re.search('Errno|Traceback|No such file', human) and HOME not in human, human[:160])
|
||||
self.check('Д-004 сырая строка оставлена ниже как техническая подробность', copy['rawBelow'], copy['rawBelow'])
|
||||
self.check('Д-004 домашний каталог не виден на странице', not copy['homeVisible'])
|
||||
self.page.unroute('**/api/status*')
|
||||
|
||||
def contrast(self):
|
||||
self.open('/', '.p-stone')
|
||||
measured = self.page.evaluate(CONTRAST)
|
||||
self.check('Д-005 разбор цвета: color(srgb 1 1 1 / 0.97) читается как белый', 5.5 < measured['selfcheck'] < 6.5, measured['selfcheck'])
|
||||
self.check('Д-005 положительный контроль: заведомо бледный текст краснеет', not measured['control']['pass'], measured['control'])
|
||||
bad = [row for row in measured['rows'] if not row['pass']]
|
||||
self.check('Д-005 контраст замеренных подписей не ниже нормы WCAG 1.4.3', measured['rows'] and not bad, bad or len(measured['rows']))
|
||||
contrast = self.axe(['color-contrast'])
|
||||
self.check('Д-005 axe color-contrast на главной', not contrast, contrast)
|
||||
|
||||
def narrow(self):
|
||||
self.page.set_viewport_size({'width': 320, 'height': 720})
|
||||
self.open('/', '.p-stone', 500)
|
||||
width = self.page.evaluate("() => document.documentElement.scrollWidth - document.documentElement.clientWidth")
|
||||
self.check('сохранено: нет горизонтального переполнения на 320 px', width <= 1, width)
|
||||
self.page.set_viewport_size({'width': 1440, 'height': 900})
|
||||
|
||||
def wait_ready(self, limit=180):
|
||||
"""A fresh server answers /api/bootstrap with 0 documents while it indexes (~20 s on the full corpus):
|
||||
checking the interface before status.index.ready would measure the cold start, not the defects."""
|
||||
deadline = time.monotonic() + limit
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(BASE + '/api/bootstrap', timeout=30) as response:
|
||||
boot = json.load(response)
|
||||
if (boot.get('status') or {}).get('index', {}).get('ready') and boot.get('documents'):
|
||||
return True
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
time.sleep(1)
|
||||
self.check('готовность: библиотека закончила индексацию', False, f'index.ready не наступил за {limit} с')
|
||||
return False
|
||||
|
||||
def run(self):
|
||||
self.wait_ready()
|
||||
labels = state_labels()
|
||||
self.section('Д-001 Д-006 Д-007 Д-008 экраны', self.screens)
|
||||
self.section('Д-001 поле поиска', self.search_box)
|
||||
self.section('Д-002 страницы каталога', self.catalog_pages)
|
||||
self.section('Д-002 фильтры каталога', self.catalog_filters)
|
||||
self.section('Д-002 DocumentList', self.document_list)
|
||||
self.section('Д-003 очередь', lambda: self.queue(labels))
|
||||
self.section('Д-004 текст ошибки', lambda: self.error_copy(labels))
|
||||
self.section('Д-005 контраст', self.contrast)
|
||||
self.section('сохранено: узкий экран', self.narrow)
|
||||
self.check('сохранено: ноль ошибок страницы и консоли', not self.errors, self.errors[:5])
|
||||
return 0 if all(item['ok'] for item in self.results if not item.get('info')) else 1
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument('--out', type=Path, help='куда записать JSON-отчёт; без флага только печать')
|
||||
args = parser.parse_args()
|
||||
if not AXE.is_file():
|
||||
print(f'FAIL axe-core не найден: npm ci в eunomia/frontend или AXE_CORE (искал {AXE.name})')
|
||||
return 1
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch(headless=True, executable_path=executable())
|
||||
check = Check(browser)
|
||||
try:
|
||||
code = check.run()
|
||||
except Exception as error:
|
||||
check.check('проба выполнена до конца', False, f'{type(error).__name__}: {error}')
|
||||
code = 1
|
||||
browser.close()
|
||||
# Reports land in a public repository: the home directory never leaves the machine. The placeholder is
|
||||
# <HOME>, as in the 22.09.2026 reports; '~' would still spell the projects path, which pd_guard rejects.
|
||||
results = json.loads(json.dumps(check.results, ensure_ascii=False).replace(HOME, '<HOME>'))
|
||||
if args.out:
|
||||
args.out.parent.mkdir(parents=True, exist_ok=True)
|
||||
report = json.dumps({'base': BASE, 'results': results, 'js_errors': check.errors}, ensure_ascii=False, indent=2)
|
||||
args.out.write_text(report.replace(HOME, '<HOME>') + '\n', encoding='utf-8')
|
||||
for item in results:
|
||||
detail = json.dumps(item.get('detail', ''), ensure_ascii=False)[:300]
|
||||
print('INFO' if item.get('info') else 'PASS' if item['ok'] else 'FAIL', item['name'], detail)
|
||||
failed = sum(1 for item in check.results if not item['ok'])
|
||||
print(json.dumps({'checks': len(check.results), 'failed': failed}, ensure_ascii=False))
|
||||
return code
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user