NewGuy
NewGuy

Reputation: 3423

How do I handle regular expression characters when doing a .match() on an exception using PyTest?

I have a test that looks like this:

@given(val=st.floats())
def test_validate_int_float(val):
    with pytest.raises(InvalidUsage) as ex:
        validate(val)
    print("{}|{}|{}".format(ex.value, f'Invalid value "{val}" for int param "n"',
                            ex.value == f'Invalid value "{val}" for int param "n"'))
    assert ex.match(f'Invalid value "{val}" for int param "n"')

When Hypothesis sets val = 1e+16, I get a failure.

E       AssertionError: Pattern 'Invalid value "1e+16" for int param "n"' not found in 'Invalid value "1e+16" for int param "n"'

The printed output for that failure is:

Invalid value "1e+16" for int param "n"|Invalid value "1e+16" for int param "n"|True

I believe this failure is happening because of the + character.

How do I properly match an exception message that contains a character used to define a regular expression? In thie case it failed on a +, but I have other tests that will use parenthesis, brackets, etc.

The documentation says that pytest is using re.search() behind the scenes in .match().

Upvotes: 0

Views: 767

Answers (1)

iBug
iBug

Reputation: 37287

But why are you using RE match when string equality works perfectly well?

assert ex.value == f'Invalid value "{val}" for int param "n"'

If you really need to handle RE metacharacters, you can escape them beforehand:

s = f'Invalid value "{val}" for int param "n"'
for ch in r"()[]{}.?*+^$|\":
    s = s.replace(ch, "\\" + ch)
assert ex.match(s)

Upvotes: 1

Related Questions