Files

416 lines
26 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.
#!/usr/bin/env python3
"""Браузерная приемка раздела «Судебная практика» на ширинах 1440 и 390.
python3 eunomia/tests/practice_check.py
Без EUNOMIA_URL запросы браузера уходят в настоящий обработчик Эвномии через
socketpair: порт не открывается, поэтому проверка идет и в песочнице. С
EUNOMIA_URL проверяется уже запущенный сервер. Данные - живые: библиотека и
хранилище практики корня Themiz. Снимки экрана содержат тексты актов и
ложатся в .agent/ (вне git), в qa/ - только итог без текста актов.
"""
from __future__ import annotations
import json
import os
import re
import socket
import sys
import threading
import time
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlsplit
from playwright.sync_api import sync_playwright
from chromium import executable
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / 'scripts'))
sys.path.insert(0, str(ROOT))
BASE = os.environ.get('EUNOMIA_URL', 'http://127.0.0.1:18765').rstrip('/')
SHOTS = ROOT / '.agent/maintenance/practice/qa'
REPORT = ROOT / 'eunomia/qa/practice-check.txt'
AXE = ROOT / 'eunomia/frontend/node_modules/axe-core/axe.min.js'
def bridge(app):
"""Маршрут Playwright → обработчик Эвномии через socketpair, без сети."""
from eunomia.server import handler
serve_request = handler(app)
fake = type('Server', (), {'server_port': 18765})()
def fulfil(route):
request, url = route.request, urlsplit(route.request.url)
target = url.path + ('?' + url.query if url.query else '')
headers = ''.join(f'{k}: {v}\r\n' for k, v in request.headers.items() if k.lower() not in ('host', 'connection'))
client, server_side = socket.socketpair()
client.sendall(f'{request.method} {target} HTTP/1.1\r\nHost: 127.0.0.1:18765\r\n{headers}'
f'Connection: close\r\n\r\n'.encode('latin-1', 'replace') + (request.post_data_buffer or b''))
def serve():
try:
serve_request(server_side, ('127.0.0.1', 0), fake)
finally:
server_side.close()
worker = threading.Thread(target=serve, daemon=True)
worker.start()
raw = b''
while chunk := client.recv(1 << 16):
raw += chunk
worker.join(30)
client.close()
head, _, body = raw.partition(b'\r\n\r\n')
lines = head.decode('latin-1').split('\r\n')
route.fulfill(status=int(lines[0].split()[1]), body=body,
headers=dict(line.split(': ', 1) for line in lines[1:] if ': ' in line))
return fulfil
class Check:
"""Одна вкладка на обе ширины: одно-процессный Chromium в песочнице не переживает закрытие вкладки."""
def __init__(self, page):
self.page, self.width, self.results, self.errors = page, 0, [], []
page.on('pageerror', lambda error: self.errors.append(str(error)))
page.on('console', lambda message: self.errors.append(f"{message.text} {message.location.get('url', '')}".strip())
if message.type == 'error' else None) # адрес ответа 404 - в отчет: без него дефект не найти
def resize(self, width, height):
self.width = width
self.page.set_viewport_size({'width': width, 'height': height})
def check(self, name, ok, detail=''):
self.results.append((f'{self.width}: {name}', bool(ok), str(detail)))
def open(self, fragment, selector):
self.page.goto(BASE + '/' + fragment, wait_until='domcontentloaded')
self.page.wait_for_selector(selector, timeout=30000)
self.page.wait_for_timeout(250)
def no_overflow(self, label):
width = self.page.evaluate('() => document.documentElement.scrollWidth')
self.check(f'{label}: без горизонтальной прокрутки', width <= self.width, f'{width}px')
def axe(self, label, scope):
if not self.page.evaluate('() => !!window.axe'):
return self.check(f'{label}: axe-core загружен', False, str(AXE))
found = self.page.evaluate('''scope => axe.run({include: [[scope]]}, {runOnly: ['wcag2a', 'wcag2aa', 'wcag21aa', 'wcag22aa']})
.then(r => r.violations.filter(v => ['serious', 'critical'].includes(v.impact)).map(v => v.id + ':' + v.nodes.length))''', scope)
self.check(f'{label}: axe без серьезных нарушений', not found, ', '.join(found))
def shot(self, name, full=False):
SHOTS.mkdir(parents=True, exist_ok=True)
self.page.screenshot(path=str(SHOTS / f'{name}-{self.width}.png'), full_page=full)
def total(self):
text = self.page.locator('.p-results-tools [role=status]').inner_text()
digits = re.sub(r'\D', '', text)
return int(digits) if digits else 0
def desktop(check):
page = check.page
check.open('', '.p-practice-teaser')
teaser = page.locator('.p-practice-teaser').inner_text()
check.check('главная: блок «Судебная практика» с числом актов', re.search(r'\d[\d\s ]* акт', teaser), teaser.split('\n')[-2:])
check.check('меню: пункт «Судебная практика»', page.get_by_role('link', name='Судебная практика').count() >= 1)
check.axe('главная', '.p-practice-teaser')
check.shot('home')
page.locator('.p-practice-teaser a').click()
page.wait_for_selector('.p-practice-row', timeout=30000)
check.check('список: 12 актов на странице', page.locator('.p-practice-row').count() == 12, page.locator('.p-practice-row').count())
check.check('список: общее число актов', check.total() > 0, check.total())
check.axe('список', '.p-practice')
check.no_overflow('список')
started = time.monotonic()
page.get_by_role('searchbox', name='Слова или статья').fill('неустойка')
page.get_by_role('button', name='Найти').click()
page.wait_for_function("() => location.hash.includes('q=') && document.querySelector('.p-result-excerpt mark')", timeout=30000)
check.check('поиск словами: найдено и подсвечено', check.total() > 0 and page.locator('.p-result-excerpt mark').count() > 0,
f'{check.total()} актов, {round(time.monotonic() - started, 2)} с с отрисовкой')
check.shot('search-words')
page.get_by_role('searchbox', name='Слова или статья').fill('ст. 333 ГК')
page.get_by_role('button', name='Найти').click()
page.wait_for_selector('.p-practice-articles .p-chip', timeout=30000)
page.wait_for_function("() => document.querySelector('.p-practice-row')", timeout=30000)
chip = page.locator('.p-practice-articles .p-chip').first.inner_text()
excerpt = page.locator('.p-result-excerpt').first.inner_text()
check.check('поиск по статье: «ст. 333 ГК» распознана', 'ст. 333 ГК РФ' in chip, chip)
check.check('поиск по статье: цитата со ссылкой на 333', '333' in excerpt, f'{check.total()} актов')
page.locator('.p-practice-row h2 a').first.click()
page.wait_for_selector('.p-practice-act h1', timeout=30000)
page.wait_for_selector('.p-act-text p', timeout=30000)
source = page.locator('.p-act-card a[target=_blank]').get_attribute('href') or ''
digest = page.locator('.p-hash').inner_text().strip()
check.check('акт: полный текст', page.locator('.p-act-text p').count() > 3, page.locator('.p-act-text p').count())
check.check('акт: адрес источника', source.startswith('https://sudact.ru/'), source)
check.check('акт: время загрузки', 'не указано' not in page.locator('.p-act-card dl').inner_text())
check.check('акт: SHA-256 и сверка', re.fullmatch(r'[0-9a-f]{64}', digest) and page.get_by_text('Хеш совпал').count() == 1, digest[:12])
articles = page.locator('#act-articles + ul li')
check.check('акт: статьи, которые цитирует', articles.count() > 0 and page.locator('.p-act-aside').get_by_text('ст. 333 ГК РФ').count() >= 1,
articles.count())
check.check('акт: ссылки на статьи прямо в тексте', page.locator('.p-act-text a').count() > 0, page.locator('.p-act-text a').count())
check.axe('акт', '.p-practice-act')
check.no_overflow('акт')
check.shot('act')
page.locator('.p-act-aside').get_by_role('link', name='ст. 333 ГК РФ', exact=True).click()
page.wait_for_selector('.p-norm-practice', timeout=30000)
fragment = unquote(parse_qs(urlsplit(page.url).fragment).get('fragment', [''])[0])
norm = page.locator('.p-norm-practice').inner_text()
check.check('статья 333 ГК открыта из акта', fragment.endswith('_article_333'), fragment)
check.check('статья 333 ГК: «Практика по статье»', 'ст. 333 ГК РФ' in norm and re.search(r'\d+ акт', norm), norm.replace('\n', ' · '))
check.shot('norm')
page.locator('.p-norm-practice').click()
page.wait_for_selector('.p-practice-row', timeout=30000)
check.check('практика по статье: список актов', page.locator('#practice-title').inner_text() == 'Практика по ст. 333 ГК РФ' and check.total() > 0,
check.total())
month = page.locator('.p-practice-filters select').first
value = month.locator('option').nth(1).get_attribute('value')
month.select_option(value)
page.wait_for_function(f"() => location.hash.includes('month={value}')", timeout=30000)
page.wait_for_timeout(500)
check.check('фильтр по месяцу сохраняет статью', 'article=333' in page.url, unquote(urlsplit(page.url).fragment))
check.open('#view=updates', '.p-load .p-load-count')
page.wait_for_function("() => / из /.test(document.querySelector('.p-load .p-load-count').textContent)", timeout=30000)
card = page.locator('.p-load').filter(has_text='Судебные акты').inner_text()
check.check('состояние базы: сколько актов скачано из карты', re.search(r'Скачано [\d\s ]+ из [\d\s ]+ акт', card), card.split('\n')[1:4])
# Подмененные ответы кнопок и полос: приемка не запускает настоящий обход СудАкта и проверку законов.
def now_iso():
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
def acts(**walk):
base = {'running': False, 'requested_at': None, 'stopped': None, 'at': '2026-10-03T01:51:30Z',
'next_due': '2026-10-03T21:00:00Z', 'found': 0}
running = walk.get('running')
fresh = {'fresh': True, 'label': 'Актуально на сегодня', 'as_of': '03.10.2026', 'interval_days': 1}
return {'done': 96000 if running else 96097, 'total': 96097, 'per_min': 120.0 if running else 0.0,
'eta_min': 1 if running else 0, 'updated_at': now_iso(), 'walk': {**base, **walk},
'freshness': {**fresh, 'fresh': False, 'label': 'Не актуально: идет обход СудАкта'} if running else fresh}
def law(running=False):
missing = [{'id': f'legal-corpus:code:c{n}', 'title': f'Кодекс {n}', 'reason': 'не хватило времени проверки, повтор позже'}
for n in range(7)]
return {'done': 100 if running else 445, 'total': 445, 'per_min': 12.0 if running else 0.0,
'eta_min': 29 if running else 0, 'running': running, 'updated_at': now_iso(),
'states': {'queued': 344, 'running': 1, 'blocked': 100} if running else {'blocked': 391, 'deferred': 54},
'freshness': {'full': False, 'label': 'Корпус неполный: не готовы 7 документов из 445', 'as_of': None,
'interval_days': 7, 'missing': missing}}
def updates(check):
"""«Состояние базы»: полосы «Судебные акты» и «Законодательство» с кнопками. Сначала живые данные,
затем подмененные ответы: кнопка шлет POST с CSRF, во время работы вторую не запускает,
остановку СудАкта называет."""
page = check.page
check.open('#view=updates', '.p-load progress')
page.wait_for_function("() => [...document.querySelectorAll('.p-load .p-load-count')].filter(n => / из /.test(n.textContent)).length === 2",
timeout=30000)
labels = {'Судебные акты': ('Скачано', {'Обновить судебные акты', 'Обход идет…', 'Обход начнется…', 'Обход остановлен'}),
'Законодательство': ('Готово', {'Обновить законодательство', 'Идет обновление…'})}
for title, (word, names) in labels.items():
card = page.locator('.p-load').filter(has=page.get_by_role('heading', name=title, exact=True))
text, value = card.inner_text(), card.locator('progress').get_attribute('value')
check.check(f'{title}: полоса 0-100 %, «{word} N из M»', card.count() == 1 and value is not None and 0 <= float(value) <= 100
and re.search(rf'{word} [\d\s ]+ из [\d\s ]+', text) and '%' in text, text.split('\n')[1:3])
button = card.locator('.p-load-actions button')
name = button.inner_text().strip()
check.check(f'{title}: кнопка обновления', button.count() == 1 and name in names, name)
button.focus()
page.keyboard.press('Shift+Tab')
page.keyboard.press('Tab')
ring = button.evaluate("b => b === document.activeElement && getComputedStyle(b).outlineStyle !== 'none' && parseFloat(getComputedStyle(b).outlineWidth) >= 2")
check.check(f'{title}: фокус кнопки виден', ring)
marks = {title: page.locator('.p-load').filter(has=page.get_by_role('heading', name=title, exact=True)).locator('.p-load-mark')
for title in ('Судебные акты', 'Законодательство')}
acts_mark, law_mark = (marks[title].inner_text().strip() if marks[title].count() else '' for title in marks)
check.check('отметка свежести практики по живому состоянию', re.fullmatch(r'Актуально на сегодня|Не актуально: .+', acts_mark), acts_mark)
check.check('отметка свежести законов по живому состоянию',
re.fullmatch(r'Корпус полный · актуально на \d\d\.\d\d\.\d{4}|Корпус неполный: не готов.+|Корпус пуст.+', law_mark), law_mark)
if law_mark.startswith('Корпус неполный'):
listed = page.locator('.p-load-missing li')
check.check('законы: недостача названа (до 5 пунктов и остаток числом)', 1 <= listed.count() <= 6 and ' — ' in listed.first.inner_text(),
[listed.nth(n).inner_text() for n in range(min(listed.count(), 2))])
check.axe('состояние базы', '.p-service-grid')
check.no_overflow('состояние базы')
check.shot('updates', full=True) # обе карточки целиком и на 390
state, posts = {'acts': acts(), 'law': law()}, []
def answer(key):
return lambda route: route.fulfill(status=200, content_type='application/json; charset=utf-8',
body=json.dumps(state[key], ensure_ascii=False))
def press(detail):
def fulfil(route):
posts.append((urlsplit(route.request.url).path, route.request.headers.get('x-eunomia-csrf', '')))
route.fulfill(status=202, content_type='application/json; charset=utf-8',
body=json.dumps({'ok': True, 'started': True, 'detail': detail}, ensure_ascii=False))
return fulfil
routes = {BASE + '/api/practice/progress': answer('acts'), BASE + '/api/update/progress': answer('law'),
BASE + '/api/practice/refresh': press('Обход СудАкта начнется в течение минуты.'),
BASE + '/api/update': press('Задание сохранено в очереди Themiz.')}
for url, handler in routes.items():
page.route(url, handler)
def reload(selector): # тот же адрес: goto не перезагрузил бы страницу, полосы ждали бы опроса
page.reload(wait_until='domcontentloaded')
page.wait_for_selector(selector, timeout=30000)
try:
reload('.p-load-actions .p-primary')
page.wait_for_function("() => document.querySelectorAll('.p-load-mark').length === 2", timeout=10000)
law_card = page.locator('.p-load').filter(has_text='Законодательство')
items = [law_card.locator('.p-load-missing li').nth(n).inner_text() for n in range(law_card.locator('.p-load-missing li').count())]
check.check('отметки: «Актуально на сегодня» и недостача законов с причинами, 5 пунктов и остаток',
page.locator('.p-load-mark').first.inner_text().strip() == 'Актуально на сегодня'
and law_card.locator('.p-load-mark').inner_text().strip() == 'Корпус неполный: не готовы 7 документов из 445'
and items[:1] == ['Кодекс 0 — не хватило времени проверки, повтор позже'] and items[-1] == 'И еще 2' and len(items) == 6, items)
for name, toast in (('Обновить судебные акты', 'в течение минуты'), ('Обновить законодательство', 'очереди')):
page.get_by_role('button', name=name).click()
page.wait_for_function(f"() => document.querySelector('.p-toast').textContent.includes('{toast}')", timeout=10000)
check.check('кнопки: POST /api/practice/refresh и /api/update с CSRF',
[path for path, _ in posts] == ['/api/practice/refresh', '/api/update'] and all(len(token) > 20 for _, token in posts), posts)
state.update(acts=acts(running=True), law=law(running=True))
reload('.p-load-wait')
page.wait_for_function("() => document.querySelectorAll('.p-load-wait').length === 2", timeout=10000)
busy = page.locator('.p-load-wait')
for button in (busy.nth(0), busy.nth(1)):
button.focus()
page.keyboard.press('Enter')
page.wait_for_timeout(300)
acts_card = page.locator('.p-load').filter(has_text='Судебные акты').inner_text()
check.check('во время работы: кнопки заняты и вторую работу не запускают',
[busy.nth(n).inner_text().strip() for n in (0, 1)] == ['Обход идет…', 'Идет обновление…']
and busy.nth(0).get_attribute('aria-disabled') == 'true' and len(posts) == 2, len(posts))
check.check('во время работы: скорость и остаток', '120 в минуту, осталось около 1 мин' in acts_card, acts_card.split('\n')[3:5])
state['acts'] = acts(stopped='часть 2: СудАкт отказал (rate_limited), повтор через неделю; все части остановлены')
reload('.p-load [role=alert]')
stopped = page.locator('.p-load').filter(has_text='Судебные акты')
check.check('остановка СудАкта: кнопка говорит об этом и обход не запускает',
stopped.locator('.p-load-actions button').inner_text().strip() == 'Обход остановлен'
and 'rate_limited' in stopped.locator('[role=alert]').inner_text())
finally:
for url, handler in routes.items():
page.unroute(url, handler)
def areas(check):
"""Отрасль «Семейные споры»: граф, подкатегории, пересечение, причина отнесения в акте."""
page = check.page
check.open('#view=practice', '.p-practice-divisions')
divisions = page.locator('.p-practice-divisions').inner_text()
check.check('деление: производства и отрасли', all(word.casefold() in divisions.casefold() for word in ('Производство', 'Гражданские', 'Отрасли', 'Семейные споры')),
divisions.replace('\n', ' · ')[:160])
page.locator('.p-practice-divisions a').filter(has_text='Семейные споры').click()
page.wait_for_selector('.p-area-graph', timeout=30000)
page.wait_for_function("() => document.querySelector('.p-practice-row')", timeout=30000)
head = page.locator('.p-area-head').inner_text()
area_total = int(re.search(r'(\d+) акт', head)[1])
check.check('отрасль: граф с подкатегориями виден', page.locator('.p-area-graph .p-area-node').count() >= 3,
page.locator('.p-area-graph .p-area-node').count())
check.check('отрасль: список совпадает с числом отрасли', check.total() == area_total, f'{check.total()} = {area_total}')
check.axe('отрасль', '.p-area')
check.no_overflow('отрасль')
check.shot('area')
child = page.locator('.p-area-children a').nth(1)
expected = int(child.locator('span').inner_text())
child.click()
page.wait_for_function("() => /area=family-[a-z]+(&|$)/.test(location.hash)", timeout=30000)
page.wait_for_timeout(600)
check.check('подкатегория: список по ней', check.total() == expected, f'{check.total()} = {expected}')
cross = page.locator('.p-area-cross a').first
if cross.count():
shared = int(re.sub(r'\D', '', cross.locator('span').inner_text()))
cross.click()
page.wait_for_function("() => decodeURIComponent(location.hash).includes(',family-')", timeout=30000)
page.wait_for_timeout(600)
check.check('пересечение: общие акты двух подкатегорий', check.total() == shared, f'{check.total()} = {shared}')
else:
check.check('пересечение: есть хотя бы одно', False, 'нет пересечений в данных')
page.locator('.p-practice-row h2 a').first.click()
page.wait_for_selector('#act-areas', timeout=30000)
card = page.locator('.p-act-areas').inner_text()
check.check('акт: отрасль и причина отнесения', 'Семейные споры →' in card and ('предмет требования' in card or 'статьи' in card),
card.replace('\n', ' · ')[:160])
def mobile_areas(check):
page = check.page
check.open('#view=practice&area=family', '.p-area-children')
check.check('отрасль: граф скрыт, подкатегории списком', not page.locator('.p-area-graph').is_visible()
and page.locator('.p-area-children a').count() >= 3)
check.no_overflow('отрасль')
check.shot('area')
def mobile(check):
page = check.page
check.open('', '.p-practice-teaser')
check.no_overflow('главная')
check.open('#view=practice', '.p-practice-row')
check.check('список виден', page.locator('.p-practice-row').count() > 0)
check.no_overflow('список')
check.shot('list')
page.locator('.p-practice-row h2 a').first.click()
page.wait_for_selector('.p-act-text p', timeout=30000)
check.no_overflow('акт')
text_top = page.locator('.p-act-text').bounding_box()['y']
aside_top = page.locator('.p-act-aside').bounding_box()['y']
check.check('акт: текст выше панели источника', text_top < aside_top, f'{round(text_top)} < {round(aside_top)}')
check.shot('act')
def main():
app = None
if 'EUNOMIA_URL' not in os.environ:
from eunomia.server import App
app = App(ROOT)
started = time.monotonic()
app.library.refresh()
print(f'библиотека готова за {round(time.monotonic() - started, 1)} с', flush=True)
with sync_playwright() as playwright:
chrome = executable()
browser = playwright.chromium.launch(headless=True, executable_path=chrome,
args=['--no-sandbox', '--single-process', '--no-zygote', '--disable-gpu'] if chrome else [])
page = browser.new_page()
if AXE.is_file(): # CSP Эвномии запрещает встроенные скрипты; init-скрипт идет мимо страницы
page.add_init_script(path=str(AXE))
if app is not None:
page.route(BASE + '/**', bridge(app))
check = Check(page)
for width, height, scenario in ((1440, 1000, desktop), (1440, 1000, areas), (1440, 1000, updates),
(390, 844, mobile), (390, 844, mobile_areas), (390, 844, updates)):
check.resize(width, height)
check.errors.clear()
try:
scenario(check)
except Exception as exc:
check.check('сценарий выполнен до конца', False, f'{type(exc).__name__}: {str(exc)[:300]}')
check.check('без ошибок JavaScript', not check.errors, check.errors[:3])
results = check.results
browser.close()
lines = [f"{'✓' if ok else '✗'} {name}{' — ' + detail if detail else ''}" for name, ok, detail in results]
REPORT.parent.mkdir(exist_ok=True)
REPORT.write_text(f'Приемка «Судебной практики» {time.strftime("%d.%m.%Y %H:%M")}\n' + '\n'.join(lines) + '\n', encoding='utf-8')
print('\n'.join(lines))
failed = sum(not ok for _, ok, _ in results)
print(json.dumps({'checks': len(results), 'failed': failed, 'screenshots': str(SHOTS)}, ensure_ascii=False))
return 1 if failed else 0
if __name__ == '__main__':
raise SystemExit(main())