astrbot_plugin_imagestudio/tests/test_profile_repository_postgres_literal.py

120 行
4 KiB
Python

from __future__ import annotations
import re
from database.repositories.profile_repository import (
DETAILED_WORKFLOW_STATE_COLUMN,
PROFILE_CATEGORY_COLUMN,
PROFILE_GENERATION_KIND_COLUMN,
_sql_literal,
)
FRAGMENTS = (
PROFILE_GENERATION_KIND_COLUMN,
PROFILE_CATEGORY_COLUMN,
DETAILED_WORKFLOW_STATE_COLUMN,
)
def test_sqlite_fragments_are_untouched() -> None:
"""SQLite's ``?`` placeholders do no %-interpolation."""
for fragment in FRAGMENTS:
assert _sql_literal(fragment, "?") == fragment
def test_postgres_fragments_escape_every_percent() -> None:
"""Regression: get()/list() failed 100% of the time on backend: postgresql."""
for fragment in FRAGMENTS:
escaped = _sql_literal(fragment, "%s")
assert "%" in fragment, "fixture should contain the LIKE wildcards"
# Every original % becomes %%, and nothing else changes.
assert escaped == fragment.replace("%", "%%")
# After psycopg collapses %% -> %, the original SQL is recovered.
assert _psycopg_collapse(escaped) == fragment
def _psycopg_collapse(query: str) -> str:
"""Model psycopg's client-side %-template pass over a query string."""
return re.sub(r"%%", "%", query)
def test_escaped_query_has_no_stray_format_specifier() -> None:
"""A lone %" would make psycopg raise 'unsupported format character'."""
for fragment in FRAGMENTS:
escaped = _sql_literal(fragment, "%s")
# Walk the string: every % must be followed by another % (an escape)
# or by 's' (a real placeholder). Nothing else is valid.
index = 0
while index < len(escaped):
if escaped[index] == "%":
assert index + 1 < len(escaped), "query ends on a bare %"
assert escaped[index + 1] in "%s", (
f"invalid format specifier %{escaped[index + 1]!r} in escaped SQL"
)
index += 2
continue
index += 1
def test_list_and_get_execute_without_nameerror(tmp_path) -> None:
"""Regression guard for the %-escaping refactor.
``list()`` interpolates the same three fragments as ``get()`` but did not
define the ``placeholder`` local, so every profile listing raised
NameError. It went unnoticed because no test asserted a *successful*
``list()`` — and ``handle_request`` converts any exception into a generic
UNKNOWN_ERROR envelope, so the route-level tests stayed green.
"""
from database.db_helper import Database, DatabaseSettings, SqliteSettings
from database.repositories.profile_repository import ProfileRepository
database = Database(
DatabaseSettings(
backend="sqlite",
sqlite=SqliteSettings(path=str(tmp_path / "profiles.sqlite3")),
)
)
database.initialize()
repository = ProfileRepository(database)
repository.create(
{
"profile_id": "p-1",
"name": "Listed",
"owner_platform": "qq",
"owner_user_id": "u-1",
"status": "active",
"metadata": {},
}
)
listed = repository.list(owner_user_id="u-1")
assert [item.profile_id for item in listed.items] == ["p-1"]
assert listed.total == 1
fetched = repository.get("p-1")
assert fetched is not None and fetched.name == "Listed"
def test_every_fragment_interpolation_site_defines_placeholder() -> None:
"""Catch the next method that interpolates a fragment without the local."""
import inspect
from database.repositories import profile_repository as module
source = inspect.getsource(module)
for name, member in inspect.getmembers(module.ProfileRepository, inspect.isfunction):
body = inspect.getsource(member)
if "_sql_literal(" not in body:
continue
assert "placeholder = self.placeholder" in body, (
f"ProfileRepository.{name} interpolates a SQL fragment but never "
"binds `placeholder`, which raises NameError at call time"
)
assert "_sql_literal(" in source