意外结果:断言错误时,pytest.raises with match 参数

Sup*_*oot 7 python regex pytest

请进行健康检查!

我想包括不正确的函数调用返回的确切消息时,了解意外测试失败match的参数pytest.raises()

文档状态

match – 如果指定,则断言异常与文本或正则表达式匹配

下面的 repl 中的指令序列几乎说明了一切,但由于某种原因,最后一个测试失败了。

PS C:\Users\peter_000\OneDrive\git\test> pipenv run python
Loading .env environment variables…
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>>
>>> import pytest
>>> pytest.__version__
'4.4.1'
>>>
>>> with pytest.raises(TypeError, match='a string'):
...     raise TypeError('a string')  # passes
...
>>> def func():
...     pass
...
>>> func(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() takes 0 positional arguments but 1 was given
>>>
>>>
>>> with pytest.raises(TypeError, match='func() takes 0 positional arguments but 1 was given'):
...     func(None)  # fails
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: func() takes 0 positional arguments but 1 was given

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\Users\peter_000\.virtualenvs\test-_0Fb_hDQ\lib\site-packages\_pytest\python_api.py", line 735, in __exit__
    self.excinfo.match(self.match_expr)
  File "C:\Users\peter_000\.virtualenvs\test-_0Fb_hDQ\lib\site-packages\_pytest\_code\code.py", line 575, in match
    assert 0, "Pattern '{!s}' not found in '{!s}'".format(regexp, self.value)
AssertionError: Pattern 'func() takes 0 positional arguments but 1 was given' not found in 'func() takes 0 positional arguments but 1 was given'
>>>
Run Code Online (Sandbox Code Playgroud)

我认为这'()'可能意味着正则表达式中的某些内容会导致字符串不匹配,但是:

>>> with pytest.raises(TypeError, match='func()'):
...     raise TypeError('func()')
Run Code Online (Sandbox Code Playgroud)

……通过。

And*_*ini 11

匹配采用正则表达式模式,有些字符 like()是特殊的。你需要逃避他们:

>>> with pytest.raises(TypeError, match=r'func\(\) takes 0 positional arguments but 1 was given'):
... #                                   ^     ^^^^
...     func(None)  # succeeds
>>>
Run Code Online (Sandbox Code Playgroud)

之前失败的原因是()在正则表达式中对应于一个空组,因此您的模式将与字符串匹配func takes 0 positional arguments but 1 was given

通过的原因match='func()'是特定的正则表达式正在寻找func字符串中的任何位置:它可以跟在或之前是任何文本。

  • @Darkonaut 这实际上是我在问这个问题后提交的 PR 中的文档的重写!https://github.com/pytest-dev/pytest/pull/5223/files (2认同)
  • @SuperShoot 太棒了!已经想知道是否可能是这样:) (2认同)