You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pytest中capsys fixture的合适类型注解是什么?

capsys fixture的类型注解方案

要消除mypy的类型注解警告,你可以给capsys参数添加pytest.CaptureFixture[str]类型注解,具体操作如下:

  1. 确保代码顶部已导入pytest模块
  2. 在测试函数的capsys参数后补充类型注解:capsys: pytest.CaptureFixture[str]

修改后的完整测试代码示例:

import pytest

@pytest.mark.parametrize(
    "values,expected",
    [
        ([], "guessed so far: \n"),
        (["single one"], "guessed so far: single one\n"),
        (["one", "two", "three", "4"], "guessed so far: 4, three, two, one\n"),
    ],
)
def test_print_guesses(capsys: pytest.CaptureFixture[str], values: list[str], expected: str) -> None:
    hm.print_guesses(values)
    assert capsys.readouterr().out == expected

额外建议:给values参数补充更精确的list[str]类型注解,能让mypy的类型检查更严谨准确。

内容的提问来源于stack exchange,提问作者KindaNewAtThis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 17:04:49