"""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()