跳到内容

pytest-raises-ambiguous-pattern (RUF043)

此规则不稳定且处于预览状态。使用需要 --preview 标志。

作用

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

为什么这不好?

match 参数在底层被隐式转换为正则表达式。应该明确字符串是想作为正则表达式还是“普通”模式,方法是在字符串前加上 r 后缀,使用反斜杠转义字符串中的元字符,或者将整个字符串包装在对 re.escape() 的调用中。

示例

import pytest


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

建议改为

import pytest


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

或者

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()

参考