test(регионы) красный набор круга 6: точная именительная форма без контекста, перебор матчей, ТЕРм, последний источник, кривые реестры

- «по адресу Московская улица» и «для Приморский район» давали чужой
  факт: ветка полного слова считала точную форму без контекста
- «для приморского района, затем в Приморском крае» оставался без
  факта: счётчик брал только первое вхождение основы
- ТЕРм: lookup не умел вид монтажных расценок — ложь «кода нет»
- два источника одного кода: fetchone без порядка возвращал старую
  цену после перезалива
- реестр [] и [null]: AttributeError мимо ловушки; регион из пробелов
  матчится с пустым именем
+ страж «в Республике Крым»: маркер в окне перед полным словом

8 красных, страж зелёный

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
Hermes
2026-11-25 04:14:45 +10:00
co-authored by Claude Code
parent 870985f15f
commit a9efeb6229
+174
View File
@@ -448,3 +448,177 @@ def test_score_name_lowercases_text():
import regional_ref
assert regional_ref._score_name(
"Оренбургская область", "В Оренбургской Области") == (1, 10)
def _env_krim(tmp_path, monkeypatch):
"""Республика Крым с ценой: имя заканчивается на «ым» — хвост
прилагательных — и при этом Declinируется («в Крыму»). Фикстура под
страж именительного падежа после слова «Республике»."""
db = tmp_path / "regional_ref.sqlite"
con = sqlite3.connect(db)
con.executescript("""
create table subjects(code integer primary key, name text);
create table sources(id integer primary key, subject_id int, kind text, edition text,
act text, file_sha text, manifest_sha text, imported_at text);
create table works(id integer primary key, subject_id int, kind text, code text,
name text, unit text, price real, source_id int);
create table prices(id integer primary key, subject_id int, kind text, code text,
name text, unit text, price_otp real, price_smet real, source_id int);
""")
con.execute("insert into subjects values(11,'Республика Крым')")
con.execute("insert into sources values(1,11,'ТЕР','ред. 2014','приказ','sha1','shak','now')")
con.execute("insert into works values(1,11,'ТЕР','01-01-001-01','15 м³','м3',450.0,1)")
con.commit(); con.close()
reg = tmp_path / "reference_sources.json"
reg.write_text('{"subjects":[{"code":11,"name":"Республика Крым"}]}', encoding="utf-8")
monkeypatch.setenv("REGIONAL_REF_PATH", str(db))
monkeypatch.setenv("REGIONAL_REGISTRY", str(reg))
def test_moskovskaya_ulitsa_no_fact(tmp_path, monkeypatch):
"""ГПТ круг 5: «Московская улица» — точная (именительная) форма слова
имени области, но рядом нет ни маркера региона, ни соседнего слова
имени («улица» не «область»). Ветка полного слова считала её без
контекста, и вопрос про улицу получал факт Московской области.
Именительный падеж в адресе естественен: «ул. Московская, дом 3»."""
_env_multi(tmp_path, monkeypatch)
assert main._regional_fact(
"Какая расценка 01-01-001-01 по адресу Московская улица, дом 3?") is None
def test_primorsky_rayon_nominative_no_fact(tmp_path, monkeypatch):
"""ГПТ круг 5: «Приморский район» в именительном падеже — то же
соседство без маркера: «район» не слово имени и не маркер края."""
_env_prim(tmp_path, monkeypatch)
assert main._regional_fact(
"Смета для Приморский район, расценка 01-01-001-01?") is None
def test_republic_krim_nominative_fact(tmp_path, monkeypatch):
"""Страж обратного окна (ГПТ круг 5, «в Республике Крым»): полное
слово «крым» с прилагательным хвостом легально, когда маркер
«республик» стоит в окне ПЕРЕД ним — официальная форма имени.
Ломается мутацией «обратное окно снято»."""
_env_krim(tmp_path, monkeypatch)
fact = main._regional_fact(
"Какая расценка 01-01-001-01 действует в Республике Крым?")
assert fact and "Крым" in fact and "450.0" in fact
def test_late_correct_mention_counted(tmp_path, monkeypatch):
"""ГПТ и дипсик круг 5: счётчик брал только первое вхождение основы.
«Для приморского района, затем в Приморском крае» — первое вхождение
честно отвергнуто (нет маркера в хвосте), до второго поиск не доходил,
вопрос оставался без факта вовсе."""
_env_prim(tmp_path, monkeypatch)
fact = main._regional_fact(
"Расценка 01-01-001-01 для приморского района, затем действует в Приморском крае?")
assert fact and "Приморский" in fact and "500.0" in fact
def _env_term(tmp_path, monkeypatch):
"""Один субъект с единственным видом ТЕРм — как пишет импортёр:
монтажные расценки лежат в works с kind='ТЕРм'."""
db = tmp_path / "regional_ref.sqlite"
con = sqlite3.connect(db)
con.executescript("""
create table subjects(code integer primary key, name text);
create table sources(id integer primary key, subject_id int, kind text, edition text,
act text, file_sha text, manifest_sha text, imported_at text);
create table works(id integer primary key, subject_id int, kind text, code text,
name text, unit text, price real, source_id int);
create table prices(id integer primary key, subject_id int, kind text, code text,
name text, unit text, price_otp real, price_smet real, source_id int);
""")
con.execute("insert into subjects values(337,'Оренбургская область')")
con.execute("insert into sources values(1,337,'ТЕРм','ред. 2017','приказ','sha1','shat','now')")
con.execute("insert into works values(1,337,'ТЕРм','01-01-001-01','монтаж','шт',123.0,1)")
con.commit(); con.close()
reg = tmp_path / "reference_sources.json"
reg.write_text('{"subjects":[{"code":337,"name":"Оренбургская область"}]}', encoding="utf-8")
monkeypatch.setenv("REGIONAL_REF_PATH", str(db))
monkeypatch.setenv("REGIONAL_REGISTRY", str(reg))
def test_termm_kind_lookup(tmp_path, monkeypatch):
"""ГПТ круг 5: lookup умеет только ТЕР и ТССЦ. Импортёр кладёт монтажные
в works с kind='ТЕРм' (16 тыс. кодов на живом Оренбурге), и lookup
отвечал «кода в региональной базе нет» на существующую запись — ложь
вместо цены."""
import regional_ref
_env_term(tmp_path, monkeypatch)
db = tmp_path / "regional_ref.sqlite"
hit = regional_ref.lookup("01-01-001-01", subject_id=337, kind="ТЕРм", db=db)
assert hit["status"] == "ok" and hit["price"] == 123.0
hit = regional_ref.lookup("01-01-001-01", subject_id=337, db=db)
assert hit["status"] == "ok" and hit["price"] == 123.0
def test_latest_source_price_wins(tmp_path, monkeypatch):
"""ГПТ круг 5: импортёр при перезаливе создаёт новый source, старые
строки works остаются. fetchone() без порядка выборки возвращал
произвольную из двух цен — после обновления расценки вопрос мог
получить старую. Последний загруженный источник обязан выигрывать
в обоих видах (ТЕР — works, ТССЦ — prices)."""
import regional_ref
db = tmp_path / "regional_ref.sqlite"
con = sqlite3.connect(db)
con.executescript("""
create table subjects(code integer primary key, name text);
create table sources(id integer primary key, subject_id int, kind text, edition text,
act text, file_sha text, manifest_sha text, imported_at text);
create table works(id integer primary key, subject_id int, kind text, code text,
name text, unit text, price real, source_id int);
create table prices(id integer primary key, subject_id int, kind text, code text,
name text, unit text, price_otp real, price_smet real, source_id int);
""")
con.execute("insert into subjects values(337,'Оренбургская область')")
con.execute("insert into sources values(1,337,'ТЕР','старая','приказ','s1','m1','now')")
con.execute("insert into sources values(2,337,'ТЕР','новая','приказ','s2','m2','now')")
con.execute("insert into sources values(3,337,'ТССЦ','старая','приказ','s3','m3','now')")
con.execute("insert into sources values(4,337,'ТССЦ','новая','приказ','s4','m4','now')")
con.execute("insert into works values(1,337,'ТЕР','01-01-001-01','старая','м3',100.0,1)")
con.execute("insert into works values(2,337,'ТЕР','01-01-001-01','новая','м3',200.0,2)")
con.execute("insert into prices values(1,337,'ТССЦ','81-01-001-01','старая','м3',110.0,120.0,3)")
con.execute("insert into prices values(2,337,'ТССЦ','81-01-001-01','новая','м3',210.0,220.0,4)")
con.commit(); con.close()
hit = regional_ref.lookup("01-01-001-01", subject_id=337, db=db)
assert hit["status"] == "ok" and hit["price"] == 200.0
hit = regional_ref.lookup("81-01-001-01", subject_id=337, kind="ТССЦ", db=db)
assert hit["status"] == "ok" and hit["price_otp"] == 210.0
def test_registry_empty_list_logged(tmp_path, monkeypatch, caplog):
"""ГПТ круг 5: реестр «[]» — data.get на списке ронял AttributeError
мимо ловушки KeyError/TypeError/ValueError, наружу вместо честного
«не распознан»."""
import logging
import regional_ref
reg = tmp_path / "reference_sources.json"
reg.write_text("[]", encoding="utf-8")
with caplog.at_level(logging.ERROR):
assert regional_ref._resolve_region("Оренбургская область", registry=str(reg)) is None
assert any(r.name == "regional_ref" and r.exc_info for r in caplog.records)
def test_registry_null_subject_logged(tmp_path, monkeypatch, caplog):
"""ГПТ круг 5: субъект null в реестре — s.get ронял AttributeError
мимо той же ловушки."""
import logging
import regional_ref
reg = tmp_path / "reference_sources.json"
reg.write_text('{"subjects":[null]}', encoding="utf-8")
with caplog.at_level(logging.ERROR):
assert regional_ref._resolve_region("Оренбургская область", registry=str(reg)) is None
assert any(r.name == "regional_ref" and r.exc_info for r in caplog.records)
def test_whitespace_region_none(tmp_path, monkeypatch):
"""Дипсик круг 5: регион из одних пробелов даёт want="" и точный
проход матчит субъекта с пустым именем. Пустая строка после strip —
не регион вовсе."""
import regional_ref
reg = tmp_path / "reference_sources.json"
reg.write_text('{"subjects":[{"name":"","code":1},'
'{"code":337,"name":"Оренбургская область"}]}', encoding="utf-8")
assert regional_ref._resolve_region(" ", registry=str(reg)) is None