gendesign/backend/tests/services/test_planning_lookup.py
bot-backend 7cde3b8eaa
All checks were successful
CI Trade-In / changes (pull_request) Successful in 8s
CI / changes (pull_request) Successful in 10s
CI Trade-In / backend-tests (pull_request) Has been skipped
CI Trade-In / browser-tests (pull_request) Has been skipped
CI Trade-In / frontend-checks (pull_request) Has been skipped
CI / frontend-tests (pull_request) Has been skipped
CI / openapi-codegen-check (pull_request) Successful in 2m31s
CI / backend-tests (pull_request) Successful in 17m27s
fix(ptica): шесть lookup'ов /analyze глотали ошибку БД без SAVEPOINT (#2464)
Шесть функций в site_finder работают на ОБЩЕЙ с analyze_parcel сессии и
глотают (OperationalError, ProgrammingError) вокруг db.execute. Без SAVEPOINT
проглоченная ошибка оставляет транзакцию в aborted-состоянии: сам lookup
возвращает пустой результат «штатно», а падает следующий за ним запрос —
в другом месте отчёта и с другой причиной в логе.

Соседний ppt_tep_lookup — та же семья, та же таблица planning_projects —
SAVEPOINT имел. Правка сводит шесть отставших к нему:

  planning_lookup, granddoc_lookup, ird_overlay_lookup,
  functional_zone_lookup, reservation_lookup  — по одному db.execute
  zone_regulation                             — upsert был защищён, SELECT нет

Тест параметризован по всем шести именам, плюс два контроля: «без SAVEPOINT
сессия травится» и «здоровый путь по-прежнему читает строки». На origin/main
шесть падают с AbortedTransactionError, оба контроля зелёные.

Стабы _FakeDB/_DB в пяти существующих тестах получили no-op begin_nested —
без него 28 тестов падали на AttributeError. В шапке каждого стаба указано,
где SAVEPOINT проверяется по-настоящему, чтобы no-op не читался как покрытие.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 12:18:59 +05:00

68 lines
2.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.

"""Тесты parcel_planning_overlaps (#1085 analyze-wiring) — ППТ/ПМТ overlap по участку.
БД не дёргается: фейковая сессия с .execute().mappings().all(). Проверяем graceful на
отсутствие участка/таблицы и проброс строк.
"""
from __future__ import annotations
from contextlib import contextmanager
from typing import Any
from sqlalchemy.exc import ProgrammingError
from app.services.site_finder.planning_lookup import parcel_planning_overlaps
class _Result:
def __init__(self, rows: list[dict[str, Any]]) -> None:
self._rows = rows
def mappings(self) -> _Result:
return self
def all(self) -> list[dict[str, Any]]:
return self._rows
class _DB:
@contextmanager
def begin_nested(self): # type: ignore[no-untyped-def]
"""#2464: lookup оборачивает свой db.execute в SAVEPOINT (сессия общая с
analyze_parcel). Здесь достаточно пустого контекст-менеджера: эти тесты про
логику самого lookup'а. Что SAVEPOINT РЕАЛЬНО откатывает aborted-транзакцию,
проверяет tests/services/site_finder/test_2464_ird_lookups_savepoint.py на
двойнике с настоящей семантикой Postgres."""
yield
def __init__(self, rows: list[dict[str, Any]] | Exception) -> None:
self._rows = rows
def execute(self, sql: Any, params: dict[str, Any]) -> _Result:
if isinstance(self._rows, Exception):
raise self._rows
return _Result(self._rows)
def test_returns_overlaps() -> None:
rows = [
{
"project_type": "ppt",
"doc_status_name": "действующий",
"full_name": "ПАГЕ №1",
"project_name": "Галактика",
"dmd_actual_year": 2021,
},
]
out = parcel_planning_overlaps(_DB(rows), "POINT(60 56)") # type: ignore[arg-type]
assert out == rows
def test_empty_wkt_returns_empty() -> None:
assert parcel_planning_overlaps(_DB([]), None) == [] # type: ignore[arg-type]
def test_missing_table_is_graceful() -> None:
"""planning_projects ещё не задеплоена → ProgrammingError → [] (analyze не падает)."""
db = _DB(ProgrammingError("stmt", {}, Exception("relation planning_projects does not exist")))
assert parcel_planning_overlaps(db, "POINT(60 56)") == [] # type: ignore[arg-type]