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

如何用@pytest.fixture测试Python文件写入操作?

测试escreveArquivo函数的单元测试实现

测试思路

测试文件写入函数时,无需真实操作磁盘文件,通过mock模拟文件对象、monkeypatch替换模块中的open方法,结合@pytest.fixture复用测试依赖,验证以下核心点:

  • 函数是否以追加模式("a")打开目标文件
  • 写入的内容是否包含预期文本和换行符
  • 文件对象的write方法是否被正确调用

完整测试代码(test_palindromo.py)

import pytest
from unittest import mock
from src import lerEscreveArquivo

@pytest.fixture
def mock_file():
    # 创建模拟的文件对象
    mock_file_obj = mock.mock_open()
    return mock_file_obj

@pytest.fixture
def patched_open(monkeypatch, mock_file):
    # 使用monkeypatch替换lerEscreveArquivo模块中的open函数
    monkeypatch.setattr(lerEscreveArquivo, "open", mock_file)
    return mock_file

def test_escreve_arquivo_content(patched_open):
    # 调用待测试函数
    test_filename = "test.txt"
    test_content = "Olá, mundo!"
    lerEscreveArquivo.escreveArquivo(test_filename, test_content)

    # 验证open函数以追加模式被调用
    patched_open.assert_called_once_with(test_filename, "a")

    # 获取模拟的文件句柄,验证写入内容
    file_handle = patched_open()
    assert file_handle.write.call_count == 2
    file_handle.write.assert_any_call(test_content)
    file_handle.write.assert_any_call("\n")

def test_escreve_arquivo_no_exception():
    # 验证函数执行时无异常抛出(正常路径)
    with mock.patch.object(lerEscreveArquivo, "open"):
        lerEscreveArquivo.escreveArquivo("any_file.txt", "test data")

代码说明

  1. mock_file fixture:创建mock.mock_open()实例,模拟磁盘文件对象,避免真实IO操作。
  2. patched_open fixture:通过monkeypatch将lerEscreveArquivo模块中的原生open替换为模拟对象,确保测试时不会真的创建文件。
  3. test_escreve_arquivo_content:
    • 调用escreveArquivo后,断言open以正确的文件名和模式调用
    • 检查write方法被调用两次(一次写入内容,一次写入换行符),且参数符合预期
  4. test_escreve_arquivo_no_exception:验证正常场景下函数不会抛出异常,快速覆盖基础路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 11:35:25