Search code examples
pythonregexpytestassertassertion

Asserting string matches regex in pytest


I'm writing up a test using pytest to ensure a timestamp string that gets passed in matches the appropriate regex format. I have done this the following way.

test_epoch():
    timestamp = "1541811598.802"
    epoch_regex = re.compile(r'^[0-9]+$')
    assert epoch_regex.match(epoch)

However, when the test runs, I get the following error:

AssertionError: assert None
+  where None = <built-in method match of re.Pattern object at 0x11ade6480>('1541840398.802')
+    where <built-in method match of re.Pattern object at 0x11ade6480> = re.compile('^[0-9]+$').match

Does anyone know where I went wrong and how to properly assert a string matches regex?


Solution

  • Does timestamp really match the regular expression? What happens if you get rid of the '.' in timestamp? I have a feeling timestamp = "1541811598802" would pass.

    Also keep in mind that '.' is a special character in regular expressions, so when you modify your regex make sure you account for this (hint, escape special chars with \)!