删除py.测试测试成功后的tmpdir目录

2024-10-01 13:38:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我运行的测试在执行过程中会创建很多大文件。为此,如果测试通过,我想删除tmpdir目录。但是如果测试失败,tmpdir的内容应该保持不变。在

我知道如何确定测试结果:

from _pytest.runner import runtestprotocol

def pytest_runtest_protocol(item, nextitem):
    reports = runtestprotocol(item, nextitem=nextitem)
    for report in reports:
        if report.when == 'call':
            # value will be set to passed or filed
            test_outcome = report.outcome
            # But what next?

return True

但是我不知道如何找到创建的tmpdir目录的路径。在


Tags: 文件fromreport目录内容pytest过程item
2条回答

您应该create a tmpdir fixture来创建tempdir,将其传递到代码中,然后删除它。在

此外,fixture必须设置为始终删除tempdir,即使发生故障。否则,您可能会留下不干净的状态,这可能会导致其他测试失败(用户不会注意到)。在

相反,我建议你选一个

  1. 使用^{}在出现错误时将其放入Python调试器。设备尚未清理干净,您可以检查文件。在
  2. Creating a custom option允许您禁用tmpdir的清理。在
  3. 创建一个定制的tmpdir装置,它将所有tmpfiles复制到用户可配置的位置(同样,使用自定义选项),然后清理tmpdir。在

在任何情况下,不干净的tmpdir状态将是用户有意识的决定,并将防止意外的副作用。在

您可以从实际物品的函数中轻松检索tmpdir。在

在您的情况下:

from _pytest.runner import runtestprotocol

def pytest_runtest_protocol(item, nextitem):
    reports = runtestprotocol(item, nextitem=nextitem)
    for report in reports:
        if report.when == 'call':
            # value will be set to passed or filed
            test_outcome = report.outcome
            # depending on test_outcome value, remove tmpdir
            if test_outcome is "OK for you":
               if 'tmpdir' in item.funcargs:
                  tmpdir = item.funcargs['tmpdir'] #retrieve tmpdir
                  if tmpdir.check(): tmpdir.remove()

return True

为了这个故事,项目功能参数是一本包含{参数:值}通过测试项目我们目前正在检查。所以第一步是检查tmpdir是否确实是实际测试的一个arg,然后检索它。最后在移除它之前检查它的存在。在

希望这会有帮助。在

编辑: 似乎您的pytest_runtest_协议(..)尚未完全初始化该项。为了确保它是。。在

只需重写pytest_runtest_teardown(item),它会在每个测试项运行完成(成功或失败)后对其进行操作。 尝试这样添加方法:

^{pr2}$

因此,不要忘记以下几点(在文档中给出)以便轻松访问您的报告。在

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call,):
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()
    # set an report attribute for each phase of a call, which can
    # be "setup", "call", "teardown"
    setattr(item, "rep_" + rep.when, rep)

相关问题 更多 >