Pytest的“caplog”装置的类型提示是什么?

2024-05-17 11:35:31 发布

您现在位置:Python中文网/ 问答频道 /正文

正如标题所说。我正在使用pytest附带的caplog夹具。我正在使用mypy进行类型检查,并且想知道caplog的正确类型提示是什么

例如:

def test_validate_regs(caplog: Any) -> None:
    validate_regs(df, logger)
    assert caplog.text == "", "No logs should have been made."

在本例中,我将其设置为Any,但我想知道是否有更具体的类型提示可以使用

我试着阅读caplog上的文档,并在github中搜索pytest代码,以查看caplog fixture返回的内容,但除了the following之外,找不到其他内容。但是使用str类型只是给了我一个错误,说str类型没有属性text,这是有道理的

当我打印caplog类型时,我得到了_pytest.logging.LogCaptureFixture,尽管我不确定如何从_pytest导入并使用它


Tags: texttest标题类型内容pytestdefany
2条回答

此答案适用于尚未或无法更新到pytest 6+的用户。
如果您使用的是pytest 6+及以上版本,请参阅下面的updated answer


对于pytest<;6.x,您可以使用_pytest.logging.LogCaptureFixture

from _pytest.logging import LogCaptureFixture

def test_logs(caplog: LogCaptureFixture) -> None:
    ...

类型提示不适用于MyPy:

from _pytest.logging import LogCaptureFixture

def test_logs(caplog: LogCaptureFixture) -> None:
    caplog.at_level(logging.ERROR)
    caplog.at_level('10')
$ mypy test.py
/path/to/test.py:18: error: Argument 1 to "at_level" of "LogCaptureFixture" has incompatible type "str"; expected "int"
Found 3 errors in 2 files (checked 1 source file)

类型提示也适用于Intellisense:

caplog with type hint

(上面的Intellisense弹出窗口与API doc for ^{}匹配)

但是要注意,{}中的{}表明它不是一个“公共”API(如前面提到的{a4})。向装置添加类型始于此Github问题:Support for static typing

I would also add that if you import from _pytest we do not guarantee stability. It's OK as long as you are willing to adapt if/when it breaks. We are working on a stable solution for this for pytest 6.1: #7469.

这导致了Github问题:Typing and public API

pytest's "official" public API is exported by the pytest package, and everything else is defined in the _pytest package.

…而“其他一切”包括LogCaptureFixture类型提示(从该问题的待办事项列表中可以看出)。关于如何使其“官方化”有很多讨论:

How do we want to officialy declare something as public API?

我认为应该有三个标准:

  • 它在pytest中导出
  • 它没有___前缀
  • 它记录在参考文献中

从pytest 6.2.0开始,您应该使用pytest.LogCaptureFixture

在此之前,您需要导入一个不推荐使用的私有名称(我们经常在没有通知的情况下更改_pytest名称空间内的内部结构,并且不保证向前或向后兼容)


免责声明:我是pytest核心开发人员

相关问题 更多 >