<p><strong>此答案适用于尚未或无法更新到pytest 6+的用户。</strong><br/>
如果您使用的是pytest 6+及以上版本,请参阅下面的<a href="https://stackoverflow.com/a/68584135/2745495">updated answer</a></p>
<hr/>
<p>对于pytest<;6.x,您可以使用<code>_pytest.logging.LogCaptureFixture</code></p>
<pre><code>from _pytest.logging import LogCaptureFixture
def test_logs(caplog: LogCaptureFixture) -> None:
...
</code></pre>
<p>类型提示不适用于MyPy:</p>
<pre><code>from _pytest.logging import LogCaptureFixture
def test_logs(caplog: LogCaptureFixture) -> None:
caplog.at_level(logging.ERROR)
caplog.at_level('10')
</code></pre>
<pre><code>$ 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)
</code></pre>
<p>类型提示也适用于Intellisense:</p>
<p><a href="https://i.stack.imgur.com/0f8cR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0f8cR.png" alt="caplog with type hint"/></a></p>
<p>(上面的Intellisense弹出窗口与<a href="https://docs.pytest.org/en/6.2.x/reference.html?highlight=caplog#pytest.LogCaptureFixture.get_records" rel="nofollow noreferrer">API doc for ^{<cd2>}</a>匹配)</p>
<p>但是要注意,{<cd4>}中的{<cd3>}表明它不是一个“公共”API(如前面提到的{a4})。向装置添加类型始于此Github问题:<a href="https://github.com/pytest-dev/pytest/issues/3342" rel="nofollow noreferrer">Support for static typing</a>:</p>
<blockquote>
<p>I would also add that if you import from <code>_pytest</code> 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: <a href="https://github.com/pytest-dev/pytest/issues/7469" rel="nofollow noreferrer">#7469</a>.</p>
</blockquote>
<p>这导致了Github问题:<a href="https://github.com/pytest-dev/pytest/issues/7469" rel="nofollow noreferrer">Typing and public API</a>:</p>
<blockquote>
<p>pytest's "official" public API is exported by the <code>pytest</code> package, and everything else is defined in the <code>_pytest</code> package.</p>
</blockquote>
<p>…而“其他一切”包括<code>LogCaptureFixture</code>类型提示(从该问题的待办事项列表中可以看出)。关于如何使其“官方化”有很多讨论:</p>
<blockquote>
<blockquote>
<p>How do we want to officialy declare something as public API?</p>
</blockquote>
<p>我认为应该有三个标准:</p>
<ul>
<li>它在<code>pytest</code>中导出</李>
<li>它没有<code>_</code>或<code>__</code>前缀</李>
<li>它记录在参考文献中</李>
</ul>
</blockquote>