Pytest:删除被测试函数创建的文件 [英] Pytest: deleting files created by the tested function

查看:63
本文介绍了Pytest:删除被测试函数创建的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am testing a function that, as part of its execution, pickles objects. After the test, I want to delete the pickle files.

如果是测试本身保存文件,pytest 的tmpdir"夹具似乎是解决方案.但是,由于正在测试的功能是保存文件的创建者,而不是测试,我不确定测试后清理文件的正确方法是什么.

If it is the test itself that saves files, pytest’s "tmpdir" fixture seems like the solution. However, with the function undergoing testing being the creator of saved files, and not the test, I’m not sure what the proper way to clean up the files after the test is.

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

In this case, the files are being saved in the "tests" directory that contains the tests being run. The only option I can think of is to delete all *.pkl pickle files from the test directory after each test. I am wondering if I am missing a more elegant solution that pytest may provide.

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

What is the standard way of cleaning up any files that are generated as a side effect of a function being tested with pytest?

推荐答案

您可以使用monkeypatch文件打开功能并检查是否写入了新文件.在列表中收集新文件.然后,浏览列表并删除文件.示例:

You can monkeypatch file opening function and check whether a new file is written. Collect new files in a list. Afterwards, go through the list and remove the files. Example:

# 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.

tests

Depending on what functions you test, monkeypatching builtins.open may not be enough: for example, to cleanup files written with pathlib, you need to additionally 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

这篇关于Pytest:删除被测试函数创建的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆