gpt4 book ai didi

python - Pytest:删除由测试函数创建的文件

转载 作者:行者123 更新时间:2023-12-01 01:42:32 25 4
gpt4 key购买 nike

我正在测试一个函数,该函数在执行过程中会 pickle 对象。测试结束后,我想删除pickle文件。

如果是测试本身保存文件,pytest 的“tmpdir”装置似乎是解决方案。然而,由于正在测试的函数是保存文件的创建者,而不是测试,我不确定测试后清理文件的正确方法是什么。

在这种情况下,文件将保存在包含正在运行的测试的“tests”目录中。我能想到的唯一选择是在每次测试后从测试目录中删除所有 *.pkl pickle 文件。我想知道我是否缺少 pytest 可能提供的更优雅的解决方案。

清理使用 pytest 测试的函数的副作用生成的任何文件的标准方法是什么?

最佳答案

您可以对文件打开功能进行monkeypatch并检查是否写入了新文件。将新文件收集到列表中。然后,浏览列表并删除文件。示例:

# spam.py
import pathlib
import numpy

def plain_write():
with open('spam.1', 'w') as f:
f.write('eggs')


def pathlib_write():
with pathlib.Path('spam.2').open('w') as f:
f.write('eggs')


def pathlib_write_text():
pathlib.Path('spam.3').write_text('eggs')


def pathlib_write_bytes():
pathlib.Path('spam.3').write_bytes(b'eggs')


def numpy_save():
numpy.save('spam.4', numpy.zeros([10, 10]))

def numpy_savetxt():
numpy.savetxt('spam.5', numpy.zeros([10, 10]))

测试

根据您测试的功能,monkeypatching builtins.open 可能还不够:例如,要清理使用 pathlib 编写的文件,您还需要另外 Monkeypatch io.open.

import builtins
import io
import os
import pytest
import spam


def patch_open(open_func, files):
def open_patched(path, mode='r', buffering=-1, encoding=None,
errors=None, newline=None, closefd=True,
opener=None):
if 'w' in mode and not os.path.isfile(path):
files.append(path)
return open_func(path, mode=mode, buffering=buffering,
encoding=encoding, errors=errors,
newline=newline, closefd=closefd,
opener=opener)
return open_patched


@pytest.fixture(autouse=True)
def cleanup_files(monkeypatch):
files = []
monkeypatch.setattr(builtins, 'open', patch_open(builtins.open, files))
monkeypatch.setattr(io, 'open', patch_open(io.open, files))
yield
for file in files:
os.remove(file)


def test_plain_write():
assert spam.plain_write() is None


def test_pathlib_write():
assert spam.pathlib_write() is None


def test_pathlib_write_text():
assert spam.pathlib_write_text() is None


def test_pathlib_write_bytes():
assert spam.pathlib_write_bytes() is None


def test_numpy_save():
assert spam.numpy_save() is None


def test_numpy_savetxt():
assert spam.numpy_savetxt() is None

关于python - Pytest:删除由测试函数创建的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51737334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com