pytestpython-re

What's the canonical way to use pytest to assert that a string matches a regex AND get good error reporting?


unittest module has the assertRegexMatches assert, but the beauty of pytest is that it lets you use more natural asserts. But

assert re.search(pattern, str) is not None

is not so nice and doesn't provide good info. I tried searches but they all lead to the special use of regex is pytest.raises, not for checking plain old regexes.


Solution

  • You can just use

    assert re.search(pattern, _str), f"{_str} does not match {pattern}"