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

如何在JupyterLite中测试无函数且含多input调用的Python文件

如何测试多input调用的Python脚本(JupyterLite环境)

这个场景完全可以测试,核心是先重构原脚本的结构,再修正测试代码的语法和逻辑错误,以下是具体实现步骤:

1. 重构two_strings.py,封装执行逻辑

原脚本的代码是顶级执行代码,导入模块时会自动触发input()调用,无法控制测试输入。需要把逻辑封装成函数,同时将核心拼接逻辑单独抽离,方便测试:

def combine_strings(str1, str2):
    """核心拼接逻辑,单独抽离以便独立测试"""
    return f"{str1},{str2}"

def main():
    """主执行流程,处理输入输出"""
    str1 = input()
    str2 = input()
    combined = combine_strings(str1, str2)
    print(combined)

if __name__ == "__main__":
    # 只有直接运行脚本时才执行主逻辑
    main()

2. 修正并完善测试代码test_two_strings.ipynb

原测试代码存在语法错误(列表元素缺失逗号)、逻辑错误(调用不存在的main()),以及路径导入顺序问题,修正后的代码如下:

import sys
from io import StringIO
import unittest
from unittest.mock import patch

# 先添加模块所在路径,再导入目标模块
sys.path.append('Challenge10/')
import two_strings

class SimpleTestCase(unittest.TestCase):
    def test_combine_logic(self):
        """单独测试核心拼接功能,无需依赖输入输出"""
        self.assertEqual(two_strings.combine_strings('a', 'b'), 'a,b')
        self.assertEqual(two_strings.combine_strings('10', 'sixty six'), '10,sixty six')
        self.assertEqual(two_strings.combine_strings('hello', 'there'), 'hello,there')
        self.assertEqual(two_strings.combine_strings('once upon a time', 'in fairyland'), 'once upon a time,in fairyland')
    
    def test_full_input_output(self):
        """测试完整的输入输出流程,模拟用户输入并捕获打印内容"""
        test_cases = [
            (['a','b'], 'a,b'),
            (['10','sixty six'], '10,sixty six'),
            (['hello','there'], 'hello,there'),
            (['once upon a time','in fairyland'], 'once upon a time,in fairyland')
        ]
        for input_values, expected_output in test_cases:
            # 模拟两次input调用,依次返回列表中的值
            with patch('builtins.input', side_effect=input_values):
                # 捕获print输出
                captured_output = StringIO()
                with patch('sys.stdout', new=captured_output):
                    two_strings.main()
                    # 去掉输出首尾的空白(print会自动添加换行符)
                    self.assertEqual(captured_output.getvalue().strip(), expected_output)

if __name__ == '__main__':
    # 在Jupyter环境中运行unittest,关闭自动exit避免中断内核
    unittest.main(argv=['-v'], verbosity=2, exit=False)

关键说明

  • 路径顺序:必须先通过sys.path.append添加模块路径,再导入two_strings,否则会出现模块找不到的问题。
  • Mock输入:使用side_effect参数给input()传入列表,每次调用input()会依次取列表中的值,刚好匹配两次输入的需求。
  • 捕获输出:用StringIO替换sys.stdout,可以捕获print()的输出内容,用于断言验证。
  • JupyterLite兼容性:JupyterLite完全支持unittest和unittest.mock,只要模块路径设置正确,测试即可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:07:23