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

如何用pytest验证函数中两个文件的正确打开操作?

解决方法:验证多次文件打开操作

问题出在assert_called_with只会校验最后一次调用的参数,而你的函数里最后一次open是打开输入文件,所以第二次断言失败。要验证所有文件打开操作,可以用以下两种方式:

方法1:使用assert_any_call

assert_any_call会检查mock对象是否有过指定的调用,不限制调用顺序和次数,刚好适合验证两次不同的open操作:

修改后的测试代码:

import pytest
from unittest.mock import patch, mock_open
from open_two_files import open_two_files


def test_open_two_files():
    open_mock = mock_open()
    with patch('open_two_files.open', open_mock, create=True):
        open_two_files("input_filepath", "output_filepath")
    
    # 验证两个文件都被正确打开过
    open_mock.assert_any_call("input_filepath", 'r')
    open_mock.assert_any_call("output_filepath", 'w')

方法2:检查call_args_list

call_args_list是mock对象的属性,保存了所有调用的参数元组,可以直接对比完整的调用序列,或者遍历检查:

import pytest
from unittest.mock import patch, mock_open, call
from open_two_files import open_two_files


def test_open_two_files():
    open_mock = mock_open()
    with patch('open_two_files.open', open_mock, create=True):
        open_two_files("input_filepath", "output_filepath")
    
    # 按调用顺序验证所有open操作
    assert open_mock.call_args_list == [
        call("output_filepath", 'w'),
        call("input_filepath", 'r')
    ]

小提示:原函数中输出文件open_output没有被关闭,建议也用with语句管理,避免文件资源泄漏:

def open_two_files(input_filepath, output_filepath):
    with open(output_filepath, 'w') as open_output, open(input_filepath, 'r') as open_input:
        for line in open_input:
            open_output.write('foo')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:31:16