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

使用testbook测试Jupyter notebook单元格时如何正确patch input()函数

问题原因与解决方法

你第二次尝试的patch路径是正确的,问题出在mock的配置和断言逻辑错误:

  1. Jupyter 环境中的input()最终调用的是ipykernel.kernelbase.Kernel.raw_input,所以patch这个对象的路径没有问题
  2. 你误用了return_value:它会让每次调用mock对象都返回同一个值,也就是你设置的整个列表,导致两次input()调用拿到的都是完整列表,长度判断失败才会输出无效名称。你需要用side_effect来实现多次调用依次返回列表内的不同元素
  3. 原代码的输出是完整的姓名字符串,不是仅返回first name,断言内容需要对应修改

正确测试代码

@testbook(path)
def test_name_checking(tb):
    with tb.patch("ipykernel.kernelbase.Kernel.raw_input") as mock_input:
        # side_effect 会按顺序返回列表内的元素,对应两次input调用的取值
        mock_input.side_effect = ["   haRrY   ", "  pOtter "]
        tb.execute_cell("name_checking")
        # 校验输出结果
        assert tb.cell_output_text("name_checking") == "Your name is Harry Potter."
        # 也可以直接校验单元格内的变量值
        assert tb.ref("fixed_first") == "Harry"
        assert tb.ref("fixed_last") == "Potter"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:06:02