Files
dtf-system/tests/test_schema.py
Cauê Faleiros 6b7ef1c4c8 fix: a rollback never stops the database from starting; schema changes are migration files
schema.sql dropped and re-added three CHECK constraints on every start, so
an older image narrowed the lists and failed on rows written by a newer one
(an Expedição user, for example). They are now created only when missing,
and app/migrate.py applies timestamped files from app/migrations/ once each,
recording them in dtf_local.migrations; an older image skips names it does
not know. The first migration sets today's full lists. A CI step rehearses
the rollback on the real database inside a rolled-back transaction.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 16:11:30 -03:00

52 lines
2.2 KiB
Python

"""The schema runs on every start (app/bootstrap.py), so each constraint it
re-adds must be defined once: an earlier, narrower copy would refuse rows
written under a later one, and the database would never finish starting.
Run from the repository root: python3 -m unittest tests.test_schema
"""
import re
import unittest
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CONSTRAINTS = ('operators_role', 'mail_queue_kind_check', 'orders_origin_check')
def check_lists(text):
"""Each constraint's CHECK (column IN (...)) values, by constraint name."""
found = {}
for name in CONSTRAINTS:
match = re.search(r'ADD CONSTRAINT\s+' + name + r'\s+CHECK\s*\([^()]*\bIN\s*\(([^)]*)\)',
text, re.I | re.S)
if match:
found[name] = tuple(value.strip().strip("'") for value in match.group(1).split(','))
return found
class SchemaTest(unittest.TestCase):
def test_each_constraint_is_added_once(self):
schema = ROOT.joinpath('app', 'schema.sql').read_text()
added = Counter(re.findall(r'ADD CONSTRAINT\s+(\w+)', schema, re.I))
self.assertEqual([name for name, count in added.items() if count > 1], [])
def test_only_the_foreign_key_loop_drops_a_constraint(self):
# An image never lowers a CHECK on start. The FK loop rebuilds a
# foreign key only to add ON DELETE CASCADE, so it never narrows one.
schema = ROOT.joinpath('app', 'schema.sql').read_text()
loop = re.search(r'DO \$\$\nDECLARE r record;.*?\nEND \$\$;', schema, re.S)
self.assertIsNotNone(loop)
rest = schema[:loop.start()] + schema[loop.end():]
self.assertNotIn('DROP CONSTRAINT', rest)
def test_the_first_migration_has_the_current_lists(self):
schema = ROOT.joinpath('app', 'schema.sql').read_text()
files = list(ROOT.joinpath('app', 'migrations').glob('*_checks-current-lists.sql'))
self.assertEqual(len(files), 1)
migration = files[0].read_text()
self.assertEqual(check_lists(schema), check_lists(migration))
self.assertEqual(set(check_lists(schema)), set(CONSTRAINTS))
if __name__ == '__main__':
unittest.main()