【问题标题】:Execute pytest fixture teardown if debugging is quit如果调试退出,则执行 pytest 夹具拆卸
【发布时间】:2021-01-08 11:10:29
【问题描述】:

问题

我设置了一个简单的测试,比如

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 仍然存在。

按照@an answer @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 执行夹具的拆卸部分,而不考虑结束调试会话?

作为说明,Matlab 调试器显示了请求的行为。

环境

我正在使用 pytest,它告诉我我正在使用

platform linux -- Python 3.6.3, pytest-5.4.3, py-1.8.2, pluggy-0.13.1

此外,我使用带有 Test Explorer UIPython Test Explorer 扩展的 vs code 2020 年 8 月版来运行和调试测试。

【问题讨论】:

    标签: python debugging visual-studio-code pytest


    【解决方案1】:

    您是否尝试过实现上下文管理器?这保证了__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
    

    【讨论】:

    • 子类化 pathlib 的类不能如答案 atm 所示那样工作,而且它似乎也不简单(stackoverflow.com/q/29850801bugs.python.org/issue24132)。但是,将 pathlib.Path 对象分配给没有继承的类的属性是可行的。不幸的是,上下文管理器的__exit__ 在这种情况下也没有被执行,这让我感到奇怪(上下文管理器的__exit__ 总是在调试结束后执行,对吧?)。
    • 更新问题,包括您提出的改进建议
    猜你喜欢
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多