Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"Regex pattern did not match", even though they should – pytest

I am trying to match the string in this error:

for warning in args:
    if not isinstance(warning, str):
        with StaticvarExceptionHandler():
            raise TypeError(f"Configure.suppress() only takes string arguments. Current type: {type(warning)}")

with the one in this pytest test:

with pytest.raises(
    TypeError,
    match = "Configure.suppress() only takes string arguments. Current type: .*"
):
    Configure.suppress('ComplicatedTypeWarning', 1)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It should match, but I am getting this error:

E    AssertionError: Regex pattern did not match.
E     Regex: 'Configure.suppress() only takes string arguments. Current type: .*'
E     Input: "Configure.suppress() only takes string arguments. Current type: <class 'int'>"

Keep in mind that for all other tests that I use .*, everything works fine.

I am very new to Regex, so I apologise if this is actually a really stupid question. Also, I’ve seen many many questions like these, but they were all in Java and not the same case as mine, so I couldn’t find a solution. Feel free to flag this as a duplicate and link a matching question, though.

>Solution :

Parentheses have a special meaning in Regex, for marking capture groups and a few other things, see https://regex101.com (select "Python" on the left menu to get Python-specific regex explanations, since they vary from language to language).

You need to escape them

match = "Configure.suppress\\(\\) only takes string arguments. Current type: .*"

or (note the r before the ", for a "raw string")

match = r"Configure.suppress\(\) only takes string arguments. Current type: .*"

Technically you don’t need to escape those periods, since a period will match any non-newline character, and it’s unlikely that there will be another error with a similar name that has a different character in place of those periods, but if you want to fix that use either of these:

match = "Configure\\.suppress\\(\\) only takes string arguments\\. Current type: .*"

or (note the r before the ", for a "raw string")

match = r"Configure\.suppress\(\) only takes string arguments\. Current type: .*"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading