Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ Unreleased
- Show correct auto complete value for nargs option in combination with flag option :issue:`2813`
- Fix handling of quoted and escaped parameters in Fish autocompletion. :issue:`2995` :pr:`3013`
- Lazily import ``shutil``. :pr:`3023`
- Properly forward exception information to resources registered with
``click.core.Context.with_resource()``. :issue:`2447` :pr:`3058`

Version 8.2.2
-------------
Expand Down
25 changes: 22 additions & 3 deletions src/click/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,12 +483,15 @@ def __exit__(
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
tb: TracebackType | None,
) -> None:
) -> bool | None:
self._depth -= 1
exit_result: bool | None = None
if self._depth == 0:
self.close()
exit_result = self._close_with_exception_info(exc_type, exc_value, tb)
pop_context()

return exit_result

@contextmanager
def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]:
"""This helper method can be used with the context object to promote
Expand Down Expand Up @@ -615,10 +618,26 @@ def close(self) -> None:
:meth:`call_on_close`, and exit all context managers entered
with :meth:`with_resource`.
"""
self._exit_stack.close()
self._close_with_exception_info(None, None, None)

def _close_with_exception_info(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
tb: TracebackType | None,
) -> bool | None:
"""Unwind the exit stack by calling its :meth:`__exit__` providing the exception
information to allow for exception handling by the various resources registered
using :meth;`with_resource`

:return: Whatever ``exit_stack.__exit__()`` returns.
"""
exit_result = self._exit_stack.__exit__(exc_type, exc_value, tb)
# In case the context is reused, create a new exit stack.
self._exit_stack = ExitStack()

return exit_result

@property
def command_path(self) -> str:
"""The computed command path. This is used for the ``usage``
Expand Down
127 changes: 127 additions & 0 deletions tests/test_context.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import logging
from contextlib import AbstractContextManager
from contextlib import contextmanager
from types import TracebackType

import pytest

Expand Down Expand Up @@ -423,6 +425,131 @@ def manager():
assert rv == [0]


def test_with_resource_exception() -> None:
class TestContext(AbstractContextManager[list[int]]):
_handle_exception: bool
_base_val: int
val: list[int]

def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:
self._handle_exception = handle_exception
self._base_val = base_val

def __enter__(self) -> list[int]:
self.val = [self._base_val]
return self.val

def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> bool | None:
if not exc_type:
self.val[0] = self._base_val - 1
return None

self.val[0] = self._base_val + 1
return self._handle_exception

class TestException(Exception):
pass

ctx = click.Context(click.Command("test"))

base_val = 1

with ctx.scope():
rv = ctx.with_resource(TestContext(base_val=base_val))
assert rv[0] == base_val

assert rv == [base_val - 1]

with ctx.scope():
rv = ctx.with_resource(TestContext(base_val=base_val))
raise TestException()

assert rv == [base_val + 1]

with pytest.raises(TestException):
with ctx.scope():
rv = ctx.with_resource(
TestContext(base_val=base_val, handle_exception=False)
)
raise TestException()


def test_with_resource_nested_exception() -> None:
class TestContext(AbstractContextManager[list[int]]):
_handle_exception: bool
_base_val: int
val: list[int]

def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:
self._handle_exception = handle_exception
self._base_val = base_val

def __enter__(self) -> list[int]:
self.val = [self._base_val]
return self.val

def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> bool | None:
if not exc_type:
self.val[0] = self._base_val - 1
return None

self.val[0] = self._base_val + 1
return self._handle_exception

class TestException(Exception):
pass

ctx = click.Context(click.Command("test"))
base_val = 1
base_val_nested = 11

with ctx.scope():
rv = ctx.with_resource(TestContext(base_val=base_val))
rv_nested = ctx.with_resource(TestContext(base_val=base_val_nested))
assert rv[0] == base_val
assert rv_nested[0] == base_val_nested

assert rv == [base_val - 1]
assert rv_nested == [base_val_nested - 1]

with ctx.scope():
rv = ctx.with_resource(TestContext(base_val=base_val))
rv_nested = ctx.with_resource(TestContext(base_val=base_val_nested))
raise TestException()

# If one of the context "eats" the exceptions they will not be forwarded to other
# parts. This is due to how ExitStack unwinding works
assert rv_nested == [base_val_nested + 1]
assert rv == [base_val - 1]

with ctx.scope():
rv = ctx.with_resource(TestContext(base_val=base_val))
rv_nested = ctx.with_resource(
TestContext(base_val=base_val_nested, handle_exception=False)
)
raise TestException()

assert rv_nested == [base_val_nested + 1]
assert rv == [base_val + 1]

with pytest.raises(TestException):
rv = ctx.with_resource(TestContext(base_val=base_val, handle_exception=False))
rv_nested = ctx.with_resource(
TestContext(base_val=base_val_nested, handle_exception=False)
)
raise TestException()


def test_make_pass_decorator_args(runner):
"""
Test to check that make_pass_decorator doesn't consume arguments based on
Expand Down
Loading