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

如何正确测试执行文件操作的Python函数?(以修改/etc/hosts场景为例)

测试断言实现方案

你可以通过读取mock文件句柄的写入记录,拼接出最终写入文件的完整内容,再基于内容完成两个测试点的校验,完整测试代码如下:

import pytest
import logging
from your_module import registry  # 替换为你实际的模块导入路径

# 测试用的原始hosts文件样例,故意加入旧的SVC_NAME条目模拟真实场景
etc_hosts_sample_data = """127.0.0.1 localhost
192.168.1.100 SVC_NAME
::1 localhost ip6-localhost
"""

@pytest.fixture
def mocker_etc_hosts(mocker):
    mocked_etc_hosts_data = mocker.mock_open(read_data=etc_hosts_sample_data)
    mocker.patch("builtins.open", mocked_etc_hosts_data)
    return mocked_etc_hosts_data  # 返回mock实例给测试用例调用

def test_add_hosts_entry(mocker_etc_hosts, caplog):
    caplog.set_level(logging.INFO)
    registry.add_hosts_entry()

    # 拼接所有写入操作的内容,得到最终的hosts文件全文
    file_handle = mocker_etc_hosts_data()
    all_write_content = "".join([call.args[0] for call in file_handle.write.call_args_list])
    all_lines = all_write_content.strip().split("\n")

    # 测试点1:验证目标IP条目确实写入文件
    target_entry = "1.2.3.4\tSVC_NAME"
    assert target_entry in all_write_content, "未找到预期写入的IP条目"

    # 测试点2:验证SVC_NAME仅对应唯一IP
    matched_lines = [line for line in all_lines if "SVC_NAME" in line]
    assert len(matched_lines) == 1, f"SVC_NAME出现了{len(matched_lines)}次,不符合唯一性要求"
    # 可选补充:校验唯一的条目对应的IP就是预期值
    assert target_entry in matched_lines[0], "SVC_NAME对应的IP不符合预期"

    # 可选校验日志输出正常
    assert "Successfully made entry in /etc/hosts file" in caplog.text

你可以按需修改etc_hosts_sample_data的内容,覆盖原始文件无SVC_NAME、存在多个重复SVC_NAME等多种测试场景,上述断言逻辑都能正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:36:03