您可以从实际项目的funcargs轻松检索您的 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
对于这个故事, item.funcargs 是一个字典,其中包含传递给我们当前正在检查的测试项目的 {arguments:value}。所以第一步是检查tmpdir确实是实际测试的 arg,然后检索它。最后在删除它之前检查它的存在。
希望这会有所帮助。
编辑:您的 pytest_runtest_protocol(..) 似乎还没有完全初始化该项目。为了确保它是..
只需覆盖 pytest_runtest_teardown(item),一旦运行完成(成功或失败),它就会作用于每个测试项目。尝试添加这样的方法:
def pytest_runtest_teardown(item):
if item.rep_call.passed:
if 'tmpdir' in item.funcargs:
tmpdir = item.funcargs['tmpdir'] #retrieve tmpdir
if tmpdir.check(): tmpdir.remove()
当然,不要忘记以下(在文档中给出)以轻松访问您的报告。
@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)