Files

117 lines
6.2 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
"""Отметки свежести «Состояния базы» (решение владельца 03.10.2026): законы - «Корпус полный · актуально на
ДД.ММ.ГГГГ» или что не готово и почему; практика - «Актуально на сегодня» или почему нет. Живое состояние,
а не текст: очередь законов, parts/state.json и подсчет скачанного."""
from __future__ import annotations
import json
import sys
import tempfile
import time
import unittest
from datetime import datetime, timedelta
from pathlib import Path
from unittest import mock
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / 'scripts'))
sys.path.insert(0, str(ROOT))
from eunomia import practice # noqa: E402
from eunomia.server import App # noqa: E402
from test_practice import get # noqa: E402
DAY = 86400
def iso(moment: float) -> str:
return datetime.fromtimestamp(moment).astimezone().isoformat()
def day(moment: float) -> str:
return datetime.fromtimestamp(moment).strftime('%d.%m.%Y')
def job(resource_id: str, state: str, checked: float | None, detail: str = '', **rest) -> dict:
return {'id': resource_id, 'state': state, 'detail': detail, 'last_checked': iso(checked) if checked else None,
'finished_at': None, 'updated_at': time.time() - 3600, **rest}
class FreshnessTests(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = Path(tmp.name)
self.app = App(self.root)
def law(self, *jobs: dict) -> dict:
queue = {'ok': True, 'queue': {}, 'jobs': list(jobs)}
with mock.patch('background_corpus.status', return_value=queue):
code, value = get(self.app, '/api/update/progress')
self.assertEqual(code, 200)
return value['freshness']
def acts(self, downloaded: int, total: int, **walk) -> dict:
path = self.root / practice.STATE_REL / 'parts' / 'state.json'
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps({'active': 10, **walk}), encoding='utf-8')
counted = {'done': downloaded, 'total': total, 'per_min': 0.0, 'eta_min': 0, 'updated_at': '2026-10-03T09:00:00Z'}
self.app.cache.clear() # полоса кешируется на 5 с, а здесь каждое состояние новое
with mock.patch('eunomia.server.progress', lambda root: counted):
code, value = get(self.app, '/api/practice/progress')
self.assertEqual(code, 200)
return value['freshness']
def test_law_corpus_full_when_every_document_is_current_and_checked_this_week(self):
now = time.time()
mark = self.law(job('legal-corpus:code:gk-rf', 'current', now - 2 * DAY),
job('legal-corpus:plenum:plenum-ot-24032016', 'updated', now - 3600))
self.assertTrue(mark['full'])
self.assertEqual(mark['label'], f'Корпус полный · актуально на {day(now - 2 * DAY)}') # дата самой старой проверки
self.assertEqual((mark['missing'], mark['interval_days']), ([], 7))
def test_law_mark_counts_and_names_what_is_missing_with_reason(self):
now = time.time()
mark = self.law(job('legal-corpus:code:gk-rf', 'current', now - DAY),
job('legal-corpus:code:tk-rf', 'deferred', now - 20 * DAY, 'job превысил 120.0 с'),
job('legal-corpus:code:sk-rf', 'current', now - 8 * DAY),
job('legal-corpus:review:vsrf-review-1-2024', 'blocked', None, 'review_parser_not_verified'),
job('legal-corpus:act:pp-152-13-02-2024', 'queued', None))
self.assertFalse(mark['full'])
self.assertEqual(mark['label'], 'Корпус неполный: не готовы 4 документа из 5')
reasons = {item['id']: item['reason'] for item in mark['missing']}
self.assertEqual(set(reasons), {'legal-corpus:code:tk-rf', 'legal-corpus:code:sk-rf',
'legal-corpus:review:vsrf-review-1-2024', 'legal-corpus:act:pp-152-13-02-2024'})
self.assertIn('не уложилась в срок', reasons['legal-corpus:code:tk-rf'])
self.assertIn(f'проверен {day(now - 8 * DAY)}', reasons['legal-corpus:code:sk-rf']) # старше недели - не актуален
self.assertIn('разборщик обзоров', reasons['legal-corpus:review:vsrf-review-1-2024'])
self.assertTrue(all(item['title'] for item in mark['missing']))
def test_law_mark_on_empty_queue_is_not_full(self):
self.assertFalse(self.law()['full'])
def test_practice_actual_today_when_daily_walk_ended_today_and_nothing_left(self):
now = datetime.now().astimezone()
mark = self.acts(96097, 96097, done=True, at=now.isoformat(), next_due=(now + timedelta(hours=8)).isoformat())
self.assertTrue(mark['fresh'])
self.assertEqual((mark['label'], mark['interval_days']), ('Актуально на сегодня', 1))
def test_practice_not_actual_after_yesterday_walk_or_with_acts_left(self):
yesterday = datetime.now().astimezone() - timedelta(days=1)
mark = self.acts(96097, 96097, done=True, at=yesterday.isoformat())
self.assertFalse(mark['fresh'])
self.assertIn(f"обход {yesterday.strftime('%d.%m.%Y')}", mark['label'])
mark = self.acts(96000, 96097, done=True, at=datetime.now().astimezone().isoformat())
self.assertFalse(mark['fresh'])
self.assertIn('не скачаны 97 актов', mark['label'])
mark = self.acts(96097, 96097, at=datetime.now().astimezone().isoformat()) # обход идет: еще не закончился
self.assertFalse(mark['fresh'])
mark = self.acts(96097, 96097, done=True, at=datetime.now().astimezone().isoformat(),
stopped='часть 2: СудАкт отказал (rate_limited)')
self.assertFalse(mark['fresh'])
self.assertIn('rate_limited', mark['label'])
if __name__ == '__main__':
unittest.main()