Skip to content

Commit a00723f

Browse files
Treat incompatible regex inline flags as an invalid format.
re.compile raises ValueError rather than re.error when a pattern sets ASCII and UNICODE flags in separate groups. Catch that so format validation reports the string as invalid instead of crashing.
1 parent eda9779 commit a00723f

3 files changed

Lines changed: 22 additions & 1 deletion

File tree

‎CHANGELOG.rst‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
v4.27.0
2+
=======
3+
4+
* Catch ``ValueError`` from ``re.compile`` in the ``regex`` format checker so
5+
incompatible inline flags (e.g. ``(?u)(?a)``) are reported as invalid rather
6+
than crashing (#1558).
7+
18
v4.26.0
29
=======
310

‎jsonschema/_format.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -413,7 +413,7 @@ def is_time(instance: object) -> bool:
413413
return is_datetime("1970-01-01T" + instance)
414414

415415

416-
@_checks_drafts(name="regex", raises=re.error)
416+
@_checks_drafts(name="regex", raises=(re.error, ValueError))
417417
def is_regex(instance: object) -> bool:
418418
if not isinstance(instance, str):
419419
return True

‎jsonschema/tests/test_format.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,20 @@ def test_format_error_causes_become_validation_error_causes(self):
7171
self.assertIs(cm.exception.cause, BOOM)
7272
self.assertIs(cm.exception.__cause__, BOOM)
7373

74+
def test_regex_format_incompatible_inline_flags_are_invalid(self):
75+
"""
76+
``re.compile`` raises ``ValueError`` (not ``re.error``) when a
77+
pattern sets incompatible inline flags in separate groups, e.g.
78+
``(?u)(?a)``. That must be reported as an invalid regex rather
79+
than escaping as an uncaught exception.
80+
"""
81+
checker = FormatChecker()
82+
self.assertFalse(checker.conforms("(?u)(?a)", "regex"))
83+
self.assertFalse(checker.conforms("(?a)(?u)", "regex"))
84+
with self.assertRaises(FormatError) as cm:
85+
checker.check("(?u)(?a)", "regex")
86+
self.assertIsInstance(cm.exception.cause, ValueError)
87+
7488
def test_format_checkers_come_with_defaults(self):
7589
# This is bad :/ but relied upon.
7690
# The docs for quite awhile recommended people do things like

0 commit comments

Comments
 (0)