From 6e91c332baa25797fb53ef0102ddc23f131769ae Mon Sep 17 00:00:00 2001 From: Virendra Patil Date: Thu, 27 Jun 2024 19:21:17 +0530 Subject: [PATCH] handled invalid regex pattern exception inside init --- src/_pytest/python_api.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/_pytest/python_api.py b/src/_pytest/python_api.py index 24c6c1c3b..4174a55b5 100644 --- a/src/_pytest/python_api.py +++ b/src/_pytest/python_api.py @@ -987,6 +987,14 @@ class RaisesContext(ContextManager[_pytest._code.ExceptionInfo[E]]): self.message = message self.match_expr = match_expr self.excinfo: _pytest._code.ExceptionInfo[E] | None = None + if self.match_expr is not None: + re_error = None + try: + re.compile(self.match_expr) + except re.error as e: + re_error = e + if re_error is not None: + fail(f"Invalid regex pattern provided to 'match': {re_error}") def __enter__(self) -> _pytest._code.ExceptionInfo[E]: self.excinfo = _pytest._code.ExceptionInfo.for_later() @@ -1008,11 +1016,5 @@ class RaisesContext(ContextManager[_pytest._code.ExceptionInfo[E]]): exc_info = cast(Tuple[Type[E], E, TracebackType], (exc_type, exc_val, exc_tb)) self.excinfo.fill_unfilled(exc_info) if self.match_expr is not None: - re_error = None - try: - self.excinfo.match(self.match_expr) - except re.error as e: - re_error = e - if re_error is not None: - fail(f"Invalid regex pattern provided to 'match': {re_error}") + self.excinfo.match(self.match_expr) return True