[英]Execute pytest fixture teardown if debugging is quit
我设置了一个简单的测试
import pytest
import pathlib
@pytest.fixture
def some_resource():
testdir = pathlib.Path("i_want_to_be_deleted")
testdir.mkdir()
yield
testdir.rmdir()
def test_dummy_succeeds(some_resource):
assert pathlib.Path("i_want_to_be_deleted").exists()
def test_dummy_fails(some_resource):
assert False
如果我使用pytest
运行此测试,则会为测试创建目录i_want_to_be_deleted
,然后删除(也为失败的测试)。 这是预期的。
但是如果我在创建目录后在某处设置断点,在调试器中运行它,然后停止调试,目录i_want_to_be_deleted
仍然存在。
不幸的是,按照@BramAppel的回答中的建议,通过实施上下文管理器来增强此示例没有帮助:
import pytest
import pathlib
class ContextPath:
def __init__(self, pathstring):
self.path = pathlib.Path(pathstring)
def __enter__(self):
self.path.mkdir()
# The latter 3 args are just a boilerplate convention
def __exit__(self, exc_type, exc_val, exc_tb):
self.path.rmdir()
@pytest.fixture
def some_resource():
with ContextPath("i_want_to_be_deleted"):
yield
def test_dummy_succeeds(some_resource):
assert pathlib.Path("i_want_to_be_deleted").exists()
有没有办法让pytest
执行夹具的拆卸部分,而不管结束调试 session?
作为备注,Matlab 调试器展示了请求的行为。
我正在使用 pytest,它告诉我我在
platform linux -- Python 3.6.3, pytest-5.4.3, py-1.8.2, pluggy-0.13.1
此外,我使用带有Test Explorer UI和Python Test Explorer扩展的 vs code 2020 年 8 月版来运行和调试测试。
您是否尝试过实施上下文管理器? 这保证了__enter__
和__exit__
方法将被执行。 虽然我没有使用您的确切设置对此进行测试,但这可能是您问题的解决方案。
import pathlib
import pytest
class ContextPath(pathlib.Path):
def __init__(self, *args):
super().__init__(*args)
def __enter__(self):
self.mkdir()
# The latter 3 args are just a boilerplate convention
def __exit__(self, exc_type, exc_val, exc_tb):
self.rmdir()
@pytest.fixture
def some_resource():
with ContextPath("i_want_to_be_deleted"):
yield
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.