|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import os |
| 4 | +import sys |
| 5 | +import unittest |
| 6 | + |
| 7 | +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 8 | +if REPO_ROOT not in sys.path: |
| 9 | + sys.path.insert(0, REPO_ROOT) |
| 10 | + |
| 11 | +from models.errors import SchemaError |
| 12 | +from models.from_dict_validation import ( |
| 13 | + require_non_empty_str_field, |
| 14 | + require_non_empty_str_fields, |
| 15 | +) |
| 16 | + |
| 17 | + |
| 18 | +class RequireNonEmptyStrFieldMessages(unittest.TestCase): |
| 19 | + def test_absent_key_raises_missing_required_field(self) -> None: |
| 20 | + with self.assertRaises(SchemaError) as cm: |
| 21 | + require_non_empty_str_field({}, "composerId", model="TestModel") |
| 22 | + self.assertEqual(cm.exception.field, "composerId") |
| 23 | + self.assertIn("missing required field", str(cm.exception)) |
| 24 | + self.assertNotIn("invalid field", str(cm.exception)) |
| 25 | + |
| 26 | + def test_wrong_type_raises_invalid_field(self) -> None: |
| 27 | + with self.assertRaises(SchemaError) as cm: |
| 28 | + require_non_empty_str_field( |
| 29 | + {"composerId": 123}, |
| 30 | + "composerId", |
| 31 | + model="TestModel", |
| 32 | + ) |
| 33 | + self.assertEqual(cm.exception.field, "composerId") |
| 34 | + self.assertIn("invalid field", str(cm.exception)) |
| 35 | + self.assertIn("expected non-empty str, got int", str(cm.exception)) |
| 36 | + self.assertNotIn("missing required field", str(cm.exception)) |
| 37 | + |
| 38 | + |
| 39 | +class RequireNonEmptyStrFieldsMessages(unittest.TestCase): |
| 40 | + def test_absent_key_raises_missing_required_field(self) -> None: |
| 41 | + with self.assertRaises(SchemaError) as cm: |
| 42 | + require_non_empty_str_fields( |
| 43 | + {"title": "x", "workspace": "w"}, |
| 44 | + ("log_id", "title", "workspace"), |
| 45 | + model="ExportEntry", |
| 46 | + ) |
| 47 | + self.assertEqual(cm.exception.field, "log_id") |
| 48 | + self.assertIn("missing required field", str(cm.exception)) |
| 49 | + self.assertNotIn("invalid field", str(cm.exception)) |
| 50 | + |
| 51 | + def test_wrong_type_raises_invalid_field(self) -> None: |
| 52 | + with self.assertRaises(SchemaError) as cm: |
| 53 | + require_non_empty_str_fields( |
| 54 | + {"log_id": 1, "title": "x", "workspace": "w"}, |
| 55 | + ("log_id", "title", "workspace"), |
| 56 | + model="ExportEntry", |
| 57 | + ) |
| 58 | + self.assertEqual(cm.exception.field, "log_id") |
| 59 | + self.assertIn("invalid field", str(cm.exception)) |
| 60 | + self.assertIn("expected non-empty str, got int", str(cm.exception)) |
| 61 | + self.assertNotIn("missing required field", str(cm.exception)) |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + unittest.main() |
0 commit comments