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

Python Mock库模拟文件打开:多行文本存放及assertRaises测试示例

使用unittest.mock模拟多行文本文件并结合assertRaises测试

要模拟多行文本文件,直接把多行字符串(用Python三引号包裹)传给mock_open的read_data参数即可,这个字符串会被当作文件读取后的完整内容。

下面是完整的测试示例,包含正常场景和异常场景的测试:

import unittest
from unittest.mock import mock_open, patch

# 待测试的函数:读取文件并提取第二到第四行的所有整数
def process_file(file_path):
    with open(file_path, 'r') as f:
        lines = f.readlines()
    
    nums = []
    try:
        # 处理第二到第四行(索引1到3)
        for line in lines[1:4]:
            nums.extend([int(num) for num in line.strip().split()])
    except ValueError as e:
        raise ValueError("文件包含非整数内容") from e
    
    return nums

class TestFileProcessor(unittest.TestCase):
    def test_valid_multiline_file(self):
        # 定义你需要模拟的多行文件内容
        mock_file_content = """This is a file
11
15
27277 28183 29199
Hello"""
        
        # 替换内置open函数,注入模拟内容
        with patch("builtins.open", mock_open(read_data=mock_file_content)):
            result = process_file("任意路径均可.txt")
            # 验证提取的整数是否正确
            self.assertEqual(result, [11, 15, 27277, 28183, 29199])
    
    def test_invalid_content_raises_error(self):
        # 模拟包含非整数的文件内容,用于测试异常
        invalid_content = """This is a file
11
abc
27277 28183 29199
Hello"""
        
        with patch("builtins.open", mock_open(read_data=invalid_content)):
            # 使用assertRaises验证异常抛出
            with self.assertRaises(ValueError) as ctx:
                process_file("任意路径均可.txt")
            # 验证异常信息是否符合预期
            self.assertEqual(str(ctx.exception), "文件包含非整数内容")

if __name__ == "__main__":
    unittest.main()

关键细节

  • 多行文本直接用三引号字符串定义,换行符会被完整保留,和真实文件内容一致。
  • patch("builtins.open")会替换全局的open调用,让你的代码在测试时使用模拟文件,无需真实创建文件。
  • assertRaises通过上下文管理器捕获异常,确保函数在遇到非法内容时正确抛出错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:15:16