coulomb-social/tests/legacy_slug.py
tegwick 021f0a5916
Some checks failed
Use-case regression gate / usecase-regressions (push) Has been cancelled
Prove the global space-slug constraint for WP-0013-T01
Migration 0003 refuses duplicate content slugs and rolls back by dropping
only spaces_space_slug_global_uniq. Tests cover the SQL boundary, import
and admin races, and legacy fail-closed reads. The live database is not
migrated.

Assistant: grok
Assistant-Session: 01a12cc2-e3b2-77a3-8aef-9cc60e577fee
2026-10-11 23:12:18 +02:00

59 lines
1.9 KiB
Python

"""Insert pre-constraint slug collisions without leaving the test database there.
Production migration 0003 refuses this state. These helpers exist so denial
tests can still represent a restored legacy duplicate.
"""
from contextlib import contextmanager
from django.db import connection
from django.db.models import Count
from coulomb_social.apps.spaces.models import Space
GLOBAL_SLUG = next(
constraint
for constraint in Space._meta.constraints
if constraint.name == "spaces_space_slug_global_uniq"
)
def _constraint_present() -> bool:
with connection.cursor() as cursor:
cursor.execute(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='spaces_space'"
)
row = cursor.fetchone()
return bool(row and row[0] and "spaces_space_slug_global_uniq" in row[0])
def _drop_extra_duplicate_rows() -> None:
duplicates = Space.objects.values("slug").annotate(n=Count("pk")).filter(n__gt=1)
for row in duplicates:
keep = (
Space.objects.filter(slug=row["slug"]).order_by("created_at", "pk").first()
)
Space.objects.filter(slug=row["slug"]).exclude(pk=keep.pk).delete()
@contextmanager
def without_global_slug_constraint():
"""Point the table at the pre-0003 shape for one test.
SQLite rebuilds constraints from the model, so the global constraint has to
leave the model state before the rebuild and return afterward.
"""
original = list(Space._meta.constraints)
Space._meta.constraints = [
constraint for constraint in original if constraint.name != GLOBAL_SLUG.name
]
try:
with connection.schema_editor() as editor:
editor.remove_constraint(Space, GLOBAL_SLUG)
Space._meta.constraints = original
yield
finally:
Space._meta.constraints = original
_drop_extra_duplicate_rows()
with connection.schema_editor() as editor:
editor.add_constraint(Space, GLOBAL_SLUG)