跳到内容

pytest-raises-ambiguous-pattern (RUF043)

添加于 0.13.0 · 相关问题 · 查看源码

作用

检查传递给 pytest.raises()match 参数的非原始字面字符串,若字符串中包含至少一个未转义的正则表达式元字符,则会触发此检查。

为什么这不好?

match 参数在底层会被隐式转换为正则表达式。应当通过在前缀添加 r、使用反斜杠转义字符串中的元字符,或将整个字符串包装在 re.escape() 调用中,来明确该字符串究竟是正则表达式还是“普通”匹配模式。

示例

import pytest


with pytest.raises(Exception, match="A full sentence."):
    do_thing_that_raises()

如果该模式旨在作为正则表达式使用,请使用原始字符串(raw string)来明确此意图

import pytest


with pytest.raises(Exception, match=r"A full sentence."):
    do_thing_that_raises()

或者,使用 re.escape 转义任何正则表达式元字符

import pytest
import re


with pytest.raises(Exception, match=re.escape("A full sentence.")):
    do_thing_that_raises()

或直接使用反斜杠进行转义

import pytest
import re


with pytest.raises(Exception, "A full sentence\\."):
    do_thing_that_raises()

参考