pytest-dev / pytest

The pytest framework makes it easy to write small tests, yet scales to support complex functional testing
https://pytest.org
MIT License
11.64k stars 2.59k forks source link

`pytest.raises` with invalid regex in match kwarg fails with internal `re.error` #12505

Closed lovetheguitar closed 6 days ago

lovetheguitar commented 2 weeks ago

Using an invalid regex in pytest.raises fails in a messy way.

with pytest.raises(ValueError, match="invalid regex character ["):
    raise ValueError()
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\Users\user\Documents\Projects\external\pytest\src\_pytest\python_api.py", line 1011, in __exit__
    self.excinfo.match(self.match_expr)
  File "C:\Users\user\Documents\Projects\external\pytest\src\_pytest\_code\code.py", line 733, in match
    assert re.search(regexp, value), msg
  File "C:\Python38\lib\re.py", line 201, in search
    return _compile(pattern, flags).search(string)
  File "C:\Python38\lib\re.py", line 304, in _compile
    p = sre_compile.compile(pattern, flags)
  File "C:\Python38\lib\sre_compile.py", line 764, in compile
    p = sre_parse.parse(p, flags)
  File "C:\Python38\lib\sre_parse.py", line 948, in parse
    p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)
  File "C:\Python38\lib\sre_parse.py", line 443, in _parse_sub
    itemsappend(_parse(source, state, verbose, nested + 1,
  File "C:\Python38\lib\sre_parse.py", line 549, in _parse
    raise source.error("unterminated character set",
re.error: unterminated character set at position 24

Proposal would be to handle regex failures within pytest.raises and fail nicely for the user (UsageError).

The-Compiler commented 2 weeks ago

Here's how I would go about this:

https://github.com/pytest-dev/pytest/blob/329d3712146e69c471be3e30883d54bdde2f76cb/src/_pytest/python_api.py#L1005

https://github.com/pytest-dev/pytest/blob/329d3712146e69c471be3e30883d54bdde2f76cb/src/_pytest/_code/code.py#L728

(line numbers slightly different, not sure what version @lovetheguitar was on above)