chore: port lab 5 solution into the lab 6 skeleton
Source: mtusi2026lab5-safronov, solution/bvt2301-safronov, 046ec9e. Contracts, public tests and evidence of lab 5 are not carried over. The compose project, image and CI prefix are renamed to lab6; the first broker start defect is recorded in KNOWN_ISSUES.md; PLAN.md outlines the OpenSpec changes of lab 6. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,329 @@
|
||||
"""Сервисы и порты зависят только от абстракций; порт, реализация и фейк — один
|
||||
набор методов; фейки клиентов — те же сигнатуры, что у настоящих клиентов.
|
||||
|
||||
Импорты проверяются разбором файлов, а не по `sys.modules`: `src.config.settings`
|
||||
сам импортирует SQLAlchemy (design change `unit-of-work`, Context).
|
||||
"""
|
||||
|
||||
import ast
|
||||
import inspect
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
import fakes
|
||||
from src.core.ports.attachment import AbstractAttachmentRepository
|
||||
from src.core.ports.attachment_job import AbstractAttachmentJobRepository
|
||||
from src.core.ports.attachment_job_replay import (
|
||||
AbstractAttachmentJobReplayRepository,
|
||||
)
|
||||
from src.core.ports.attachment_variant import (
|
||||
AbstractAttachmentVariantRepository,
|
||||
)
|
||||
from src.core.ports.chat import AbstractChatRepository
|
||||
from src.core.ports.idempotency import AbstractIdempotencyRepository
|
||||
from src.core.ports.message import AbstractMessageRepository
|
||||
from src.core.ports.session import AbstractSessionRepository
|
||||
from src.core.ports.user import AbstractUserRepository
|
||||
from src.core.repos.attachment import SqlAlchemyAttachmentRepository
|
||||
from src.core.repos.attachment_job import SqlAlchemyAttachmentJobRepository
|
||||
from src.core.repos.attachment_job_replay import (
|
||||
SqlAlchemyAttachmentJobReplayRepository,
|
||||
)
|
||||
from src.core.repos.attachment_variant import (
|
||||
SqlAlchemyAttachmentVariantRepository,
|
||||
)
|
||||
from src.core.repos.chat import SqlAlchemyChatRepository
|
||||
from src.core.repos.idempotency import SqlAlchemyIdempotencyRepository
|
||||
from src.core.repos.message import SqlAlchemyMessageRepository
|
||||
from src.core.repos.session import SqlAlchemySessionRepository
|
||||
from src.core.repos.user import SqlAlchemyUserRepository
|
||||
from src.infra.broker import JobPublisher
|
||||
from src.infra.cache import Cache
|
||||
from src.infra.render import ImageRenderer
|
||||
from src.infra.s3 import ObjectStorage
|
||||
from src.infra.s3.client import StoredObject
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
REPOSITORIES = (
|
||||
(
|
||||
AbstractUserRepository,
|
||||
SqlAlchemyUserRepository,
|
||||
fakes.FakeUserRepository,
|
||||
),
|
||||
(
|
||||
AbstractSessionRepository,
|
||||
SqlAlchemySessionRepository,
|
||||
fakes.FakeSessionRepository,
|
||||
),
|
||||
(
|
||||
AbstractChatRepository,
|
||||
SqlAlchemyChatRepository,
|
||||
fakes.FakeChatRepository,
|
||||
),
|
||||
(
|
||||
AbstractMessageRepository,
|
||||
SqlAlchemyMessageRepository,
|
||||
fakes.FakeMessageRepository,
|
||||
),
|
||||
(
|
||||
AbstractIdempotencyRepository,
|
||||
SqlAlchemyIdempotencyRepository,
|
||||
fakes.FakeIdempotencyRepository,
|
||||
),
|
||||
(
|
||||
AbstractAttachmentRepository,
|
||||
SqlAlchemyAttachmentRepository,
|
||||
fakes.FakeAttachmentRepository,
|
||||
),
|
||||
(
|
||||
AbstractAttachmentJobRepository,
|
||||
SqlAlchemyAttachmentJobRepository,
|
||||
fakes.FakeAttachmentJobRepository,
|
||||
),
|
||||
(
|
||||
AbstractAttachmentVariantRepository,
|
||||
SqlAlchemyAttachmentVariantRepository,
|
||||
fakes.FakeAttachmentVariantRepository,
|
||||
),
|
||||
(
|
||||
AbstractAttachmentJobReplayRepository,
|
||||
SqlAlchemyAttachmentJobReplayRepository,
|
||||
fakes.FakeAttachmentJobReplayRepository,
|
||||
),
|
||||
)
|
||||
|
||||
CLIENTS = (
|
||||
(Cache, fakes.FakeCache, ("get", "set", "aclose")),
|
||||
(
|
||||
ObjectStorage,
|
||||
fakes.FakeObjectStorage,
|
||||
(
|
||||
"stats",
|
||||
"start",
|
||||
"aclose",
|
||||
"put",
|
||||
"head",
|
||||
"list_page",
|
||||
"open",
|
||||
"delete",
|
||||
),
|
||||
),
|
||||
(StoredObject, fakes.FakeStoredObject, ("iter_chunks", "read")),
|
||||
(
|
||||
JobPublisher,
|
||||
fakes.FakeJobPublisher,
|
||||
("publish_many", "ready_messages", "aclose"),
|
||||
),
|
||||
(ImageRenderer, fakes.FakeImageRenderer, ("render",)),
|
||||
)
|
||||
|
||||
# модуль запрещён целиком или вместе с подмодулями
|
||||
FORBIDDEN_MODULES = (
|
||||
"sqlalchemy",
|
||||
"asyncpg",
|
||||
"src.infra.db",
|
||||
"src.infra.upload_slots",
|
||||
"src.infra.cache.instance",
|
||||
"src.infra.s3.instance",
|
||||
)
|
||||
# repo на SQL; `chat_cache` и `attachment_object` — над клиентами, решение 8
|
||||
SQL_REPOS = (
|
||||
"attachment",
|
||||
"attachment_job",
|
||||
"attachment_job_replay",
|
||||
"attachment_variant",
|
||||
"chat",
|
||||
"idempotency",
|
||||
"message",
|
||||
"session",
|
||||
"user",
|
||||
)
|
||||
|
||||
|
||||
def _module_files() -> list[Path]:
|
||||
root = ROOT / "src" / "core"
|
||||
return [
|
||||
*sorted((root / "services").glob("*.py")),
|
||||
*sorted((root / "ports").glob("*.py")),
|
||||
]
|
||||
|
||||
|
||||
def _is_type_checking(node: ast.If) -> bool:
|
||||
return isinstance(node.test, ast.Name) and node.test.id == "TYPE_CHECKING"
|
||||
|
||||
|
||||
def _imports(tree: ast.AST) -> list[tuple[int, str]]:
|
||||
"""Полные имена импортов модуля, кроме блока `TYPE_CHECKING`."""
|
||||
found: list[tuple[int, str]] = []
|
||||
|
||||
def visit(node: ast.AST) -> None:
|
||||
if isinstance(node, ast.If) and _is_type_checking(node):
|
||||
for child in node.orelse:
|
||||
visit(child)
|
||||
return
|
||||
if isinstance(node, ast.Import):
|
||||
found.extend((node.lineno, item.name) for item in node.names)
|
||||
elif isinstance(node, ast.ImportFrom) and node.module:
|
||||
found.append((node.lineno, node.module))
|
||||
found.extend(
|
||||
(node.lineno, f"{node.module}.{item.name}")
|
||||
for item in node.names
|
||||
)
|
||||
for child in ast.iter_child_nodes(node):
|
||||
visit(child)
|
||||
|
||||
visit(tree)
|
||||
return found
|
||||
|
||||
|
||||
def _is_forbidden(name: str) -> bool:
|
||||
if any(
|
||||
name == module or name.startswith(f"{module}.")
|
||||
for module in FORBIDDEN_MODULES
|
||||
):
|
||||
return True
|
||||
return any(name == f"src.core.repos.{repo}" for repo in SQL_REPOS)
|
||||
|
||||
|
||||
def forbidden_imports(path: Path) -> list[str]:
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"))
|
||||
return [
|
||||
f"{path.relative_to(ROOT)}:{line} imports {name}"
|
||||
for line, name in _imports(tree)
|
||||
if _is_forbidden(name)
|
||||
]
|
||||
|
||||
|
||||
def _public_methods(cls: type) -> dict[str, inspect.Signature]:
|
||||
return {
|
||||
name: inspect.signature(member)
|
||||
for name, member in inspect.getmembers(cls, inspect.isfunction)
|
||||
if not name.startswith("_")
|
||||
}
|
||||
|
||||
|
||||
def _method_shape(signature: inspect.Signature) -> list[tuple]:
|
||||
"""Имена, вид и наличие значения по умолчанию; аннотации клиентов и фейков
|
||||
не сравниваются: у фейка свои типы результата."""
|
||||
return [
|
||||
(item.name, item.kind, item.default is inspect.Parameter.empty)
|
||||
for item in signature.parameters.values()
|
||||
]
|
||||
|
||||
|
||||
def repository_mismatches(port: type, implementation: type) -> list[str]:
|
||||
"""Расхождения реализации с портом: класс и метод — в сообщении."""
|
||||
problems = []
|
||||
expected = _public_methods(port)
|
||||
# унаследованный абстрактный метод порта — не реализация
|
||||
actual = {
|
||||
name: signature
|
||||
for name, signature in _public_methods(implementation).items()
|
||||
if not getattr(
|
||||
getattr(implementation, name),
|
||||
"__isabstractmethod__",
|
||||
False,
|
||||
)
|
||||
}
|
||||
for name in expected.keys() - actual.keys():
|
||||
problems.append(f"{implementation.__name__}.{name}: нет метода порта")
|
||||
for name in actual.keys() - expected.keys():
|
||||
problems.append(
|
||||
f"{implementation.__name__}.{name}: метода нет в порте",
|
||||
)
|
||||
for name in expected.keys() & actual.keys():
|
||||
if _method_shape(expected[name]) != _method_shape(actual[name]):
|
||||
problems.append(
|
||||
f"{implementation.__name__}.{name}: сигнатура "
|
||||
f"{actual[name]} вместо {expected[name]}",
|
||||
)
|
||||
return problems
|
||||
|
||||
|
||||
def test_no_forbidden_imports() -> None:
|
||||
"""Сценарий «Запрещённый импорт»: называет файл и импорт."""
|
||||
problems = [
|
||||
problem
|
||||
for path in _module_files()
|
||||
for problem in forbidden_imports(path)
|
||||
]
|
||||
assert not problems, "\n".join(problems)
|
||||
|
||||
|
||||
def test_services_have_no_session_names() -> None:
|
||||
root = ROOT / "src" / "core" / "services"
|
||||
problems = [
|
||||
f"{path.relative_to(ROOT)}: {word}"
|
||||
for path in sorted(root.glob("*.py"))
|
||||
for word in ("AsyncSession", "db_scope(", "db_session=")
|
||||
if word in path.read_text(encoding="utf-8")
|
||||
]
|
||||
assert not problems, "\n".join(problems)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("port", "implementation", "fake"),
|
||||
REPOSITORIES,
|
||||
ids=[item[0].__name__ for item in REPOSITORIES],
|
||||
)
|
||||
def test_port_implementation_fake_match(
|
||||
port: type,
|
||||
implementation: type,
|
||||
fake: type,
|
||||
) -> None:
|
||||
"""Сценарий «Новый метод без фейка»: называет класс и метод."""
|
||||
problems = [
|
||||
*repository_mismatches(port, implementation),
|
||||
*repository_mismatches(port, fake),
|
||||
]
|
||||
assert not problems, "\n".join(problems)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("client", "fake", "methods"),
|
||||
CLIENTS,
|
||||
ids=[item[0].__name__ for item in CLIENTS],
|
||||
)
|
||||
def test_client_fakes_match(
|
||||
client: type,
|
||||
fake: type,
|
||||
methods: tuple[str, ...],
|
||||
) -> None:
|
||||
problems = []
|
||||
for name in methods:
|
||||
real = getattr(client, name, None)
|
||||
faked = getattr(fake, name, None)
|
||||
if real is None or faked is None:
|
||||
problems.append(f"{fake.__name__}.{name}: нет метода")
|
||||
continue
|
||||
if _method_shape(inspect.signature(real)) != _method_shape(
|
||||
inspect.signature(faked),
|
||||
):
|
||||
problems.append(
|
||||
f"{fake.__name__}.{name}: сигнатура "
|
||||
f"{inspect.signature(faked)} вместо "
|
||||
f"{inspect.signature(real)}",
|
||||
)
|
||||
assert not problems, "\n".join(problems)
|
||||
public = _public_methods(client).keys()
|
||||
extra = set(public) - set(methods)
|
||||
assert not extra, f"{client.__name__}: новые методы без фейка {extra}"
|
||||
|
||||
|
||||
def test_forbidden_import_detector() -> None:
|
||||
"""Сам разбор: импорт ловится, `TYPE_CHECKING` — нет."""
|
||||
source = (
|
||||
"from typing import TYPE_CHECKING\n"
|
||||
"from src.core.repos import attachment as attachment_repo\n"
|
||||
"from sqlalchemy.ext.asyncio import AsyncSession\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" from src.infra.upload_slots import UploadSlots\n"
|
||||
)
|
||||
problems = [
|
||||
name for _, name in _imports(ast.parse(source)) if _is_forbidden(name)
|
||||
]
|
||||
assert "src.core.repos.attachment" in problems
|
||||
assert any(name.startswith("sqlalchemy") for name in problems)
|
||||
assert not any("upload_slots" in name for name in problems)
|
||||
Reference in New Issue
Block a user