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

如何在程序化调用测试函数时传入capsys fixture?

问题描述

我可以选择性运行test_function_1,覆盖conftest.py fixture中的instrumentation内容¹

def test_function_1(instrumentation: dict[str, float]) -> None:
    assert instrumentation['a'] > instrumentation['b']

def test_function_2(capsys) -> None:
    print("Hello, pytest!")
    captured = capsys.readouterr()
    assert captured.out == "Hello, pytest!\n"

但当我尝试调用test_function_2时,不知道如何为其传入capsys²:

import tests
import pytest # <--- 没帮助...

def test_callee_with_instrumentation():
    tests.test_function_1({'a': 110, 'b': 55, 'g': 6000})

def test_callee_with_capsys():
    # tests.test_function_2()              # <--- TypeError: test_function_2() missing 1 required positional argument: 'capsys'
    # tests.test_function_2(capsys)        # <--- NameError: name 'capsys' is not defined 
    # tests.test_function_2(pytest.capsys) # <--- AttributeError: module 'pytest' has no attribute 'capsys'
    pass

test_callee_with_instrumentation()
test_callee_with_capsys()

我确定conftest.py的fixture与此无关,但为了完整起见,附上其内容:

import pytest

@pytest.fixture(scope='function')
def instrumentation():
    return { 'a': 800, 'b': 620, 'c': 44 }

¹ 在我的实际代码中,capsys只是众多参数之一。
² 有一个类似的问题,但我认为这不是重复问题,因为我询问的是程序化运行测试,而非capsys的正确含义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 10:07:39