如何用@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")
代码说明
mock_filefixture:创建mock.mock_open()实例,模拟磁盘文件对象,避免真实IO操作。patched_openfixture:通过monkeypatch将lerEscreveArquivo模块中的原生open替换为模拟对象,确保测试时不会真的创建文件。test_escreve_arquivo_content:- 调用
escreveArquivo后,断言open以正确的文件名和模式调用 - 检查
write方法被调用两次(一次写入内容,一次写入换行符),且参数符合预期
- 调用
test_escreve_arquivo_no_exception:验证正常场景下函数不会抛出异常,快速覆盖基础路径。
内容的提问来源于stack exchange,提问作者Rodrigo
相关产品推荐
相关产品推荐

