Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/click/testing.py: 27%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

351 statements  

1from __future__ import annotations 

2 

3import collections.abc as cabc 

4import contextlib 

5import io 

6import os 

7import pdb 

8import shlex 

9import sys 

10import tempfile 

11import typing as t 

12from types import TracebackType 

13 

14from . import _compat 

15from . import formatting 

16from . import termui 

17from . import utils 

18from ._compat import _find_binary_reader 

19 

20if t.TYPE_CHECKING: 

21 from _typeshed import ReadableBuffer 

22 

23 from .core import Command 

24 

25if sys.platform == "win32": 

26 CaptureMode: t.TypeAlias = t.Literal["sys"] # pyright: ignore[reportRedeclaration] 

27else: 

28 CaptureMode: t.TypeAlias = t.Literal["sys", "fd"] # pyright: ignore[reportRedeclaration] 

29ExceptionInfo: t.TypeAlias = tuple[type[BaseException], BaseException, TracebackType] 

30 

31 

32class EchoingStdin: 

33 _input: t.BinaryIO 

34 _output: t.BinaryIO 

35 _paused: bool 

36 

37 def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None: 

38 self._input = input 

39 self._output = output 

40 self._paused = False 

41 

42 def __getattr__(self, x: str) -> t.Any: 

43 return getattr(self._input, x) 

44 

45 def _echo(self, rv: bytes) -> bytes: 

46 if not self._paused: 

47 self._output.write(rv) 

48 

49 return rv 

50 

51 def read(self, n: int = -1) -> bytes: 

52 return self._echo(self._input.read(n)) 

53 

54 def read1(self, n: int = -1) -> bytes: 

55 return self._echo(self._input.read1(n)) # type: ignore 

56 

57 def readline(self, n: int = -1) -> bytes: 

58 return self._echo(self._input.readline(n)) 

59 

60 def readlines(self) -> list[bytes]: 

61 return [self._echo(x) for x in self._input.readlines()] 

62 

63 def __iter__(self) -> cabc.Iterator[bytes]: 

64 return iter(self._echo(x) for x in self._input) 

65 

66 def __repr__(self) -> str: 

67 return repr(self._input) 

68 

69 

70@contextlib.contextmanager 

71def _pause_echo(stream: EchoingStdin | None) -> cabc.Generator[None]: 

72 if stream is None: 

73 yield 

74 else: 

75 stream._paused = True 

76 yield 

77 stream._paused = False 

78 

79 

80class _FDCapture: 

81 """Redirect a file descriptor to a temporary file for capture. 

82 

83 Saves the current target of *targetfd* via :func:`os.dup`, then 

84 redirects it to a temporary file via :func:`os.dup2`. On 

85 :meth:`stop`, restores the original ``fd`` and returns the captured 

86 bytes. Inspired by Pytest's ``FDCapture``. 

87 

88 .. versionadded:: 8.4.0 

89 """ 

90 

91 _targetfd: int 

92 saved_fd: int 

93 _tmpfile: t.BinaryIO | None 

94 

95 def __init__(self, targetfd: int) -> None: 

96 self._targetfd = targetfd 

97 self.saved_fd = -1 

98 self._tmpfile = None 

99 

100 def start(self) -> None: 

101 self.saved_fd = os.dup(self._targetfd) 

102 self._tmpfile = tempfile.TemporaryFile(buffering=0) 

103 os.dup2(self._tmpfile.fileno(), self._targetfd) 

104 

105 def stop(self) -> bytes: 

106 assert self._tmpfile is not None, "_FDCapture.start() was not called" 

107 os.dup2(self.saved_fd, self._targetfd) 

108 os.close(self.saved_fd) 

109 self.saved_fd = -1 

110 self._tmpfile.seek(0) 

111 data = self._tmpfile.read() 

112 self._tmpfile.close() 

113 self._tmpfile = None 

114 return data 

115 

116 

117class BytesIOCopy(io.BytesIO): 

118 """Patch ``io.BytesIO`` to let the written stream be copied to another. 

119 

120 .. versionadded:: 8.2 

121 """ 

122 

123 copy_to: io.BytesIO 

124 

125 def __init__(self, copy_to: io.BytesIO) -> None: 

126 super().__init__() 

127 self.copy_to = copy_to 

128 

129 def flush(self) -> None: 

130 super().flush() 

131 self.copy_to.flush() 

132 

133 def write(self, b: ReadableBuffer) -> int: 

134 self.copy_to.write(b) 

135 return super().write(b) 

136 

137 

138class StreamMixer: 

139 """Mixes `<stdout>` and `<stderr>` streams. 

140 

141 The result is available in the ``output`` attribute. 

142 

143 .. versionadded:: 8.2 

144 """ 

145 

146 output: io.BytesIO 

147 stdout: BytesIOCopy 

148 stderr: BytesIOCopy 

149 

150 def __init__(self) -> None: 

151 self.output = io.BytesIO() 

152 self.stdout = BytesIOCopy(copy_to=self.output) 

153 self.stderr = BytesIOCopy(copy_to=self.output) 

154 

155 

156class _NamedTextIOWrapper(io.TextIOWrapper): 

157 """A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode`` 

158 that does not close its underlying buffer. 

159 

160 When ``CliRunner`` runs in ``fd`` mode, ``_original_fd`` is patched to 

161 point at the saved (pre-redirection) ``fd``, so C-level consumers that call 

162 :meth:`fileno` (like ``faulthandler`` or ``subprocess``) keep working. In 

163 the default ``sys`` mode ``_original_fd`` stays at ``-1`` and 

164 :meth:`fileno` raises :exc:`io.UnsupportedOperation`, matching the 

165 pre-``8.3.3`` behavior. 

166 """ 

167 

168 _name: str 

169 _mode: str 

170 _original_fd: int 

171 

172 def __init__( 

173 self, 

174 buffer: t.BinaryIO, 

175 name: str, 

176 mode: str, 

177 **kwargs: t.Any, 

178 ) -> None: 

179 super().__init__(buffer, **kwargs) 

180 self._name = name 

181 self._mode = mode 

182 self._original_fd = -1 

183 

184 def close(self) -> None: 

185 """The buffer this object contains belongs to some other object, 

186 so prevent the default ``__del__`` implementation from closing 

187 that buffer. 

188 

189 .. versionadded:: 8.3.2 

190 """ 

191 

192 def fileno(self) -> int: 

193 """Return the file descriptor of the saved original stream when 

194 ``CliRunner`` runs in ``fd`` mode. Otherwise delegate to 

195 :class:`~io.TextIOWrapper`, which raises 

196 :exc:`io.UnsupportedOperation` for a ``BytesIO``-backed buffer. 

197 """ 

198 if self._original_fd >= 0: 

199 return self._original_fd 

200 return super().fileno() 

201 

202 @property 

203 def name(self) -> str: 

204 return self._name 

205 

206 @property 

207 def mode(self) -> str: 

208 return self._mode 

209 

210 

211def make_input_stream( 

212 input: str | bytes | t.IO[t.Any] | None, charset: str 

213) -> t.BinaryIO: 

214 # Is already an input stream. 

215 if hasattr(input, "read"): 

216 rv = _find_binary_reader(t.cast("t.IO[t.Any]", input)) 

217 

218 if rv is not None: 

219 return rv 

220 

221 raise TypeError("Could not find binary reader for input stream.") 

222 

223 if input is None: 

224 input = b"" 

225 elif isinstance(input, str): 

226 input = input.encode(charset) 

227 

228 return io.BytesIO(input) 

229 

230 

231class Result: 

232 """Holds the captured result of an invoked CLI script. 

233 

234 :param runner: The runner that created the result 

235 :param stdout_bytes: The standard output as bytes. 

236 :param stderr_bytes: The standard error as bytes. 

237 :param output_bytes: A mix of ``stdout_bytes`` and ``stderr_bytes``, as the 

238 user would see it in its terminal. 

239 :param return_value: The value returned from the invoked command. 

240 :param exit_code: The exit code as integer. 

241 :param exception: The exception that happened if one did. 

242 :param exc_info: Exception information (exception type, exception instance, 

243 traceback type). 

244 

245 .. versionchanged:: 8.2 

246 ``stderr_bytes`` no longer optional, ``output_bytes`` introduced and 

247 ``mix_stderr`` has been removed. 

248 

249 .. versionadded:: 8.0 

250 Added ``return_value``. 

251 """ 

252 

253 runner: CliRunner 

254 stdout_bytes: bytes 

255 stderr_bytes: bytes 

256 output_bytes: bytes 

257 return_value: t.Any 

258 exit_code: int 

259 exception: BaseException | None 

260 exc_info: ExceptionInfo | None 

261 

262 def __init__( 

263 self, 

264 runner: CliRunner, 

265 stdout_bytes: bytes, 

266 stderr_bytes: bytes, 

267 output_bytes: bytes, 

268 return_value: t.Any, 

269 exit_code: int, 

270 exception: BaseException | None, 

271 exc_info: ExceptionInfo | None = None, 

272 ) -> None: 

273 self.runner = runner 

274 self.stdout_bytes = stdout_bytes 

275 self.stderr_bytes = stderr_bytes 

276 self.output_bytes = output_bytes 

277 self.return_value = return_value 

278 self.exit_code = exit_code 

279 self.exception = exception 

280 self.exc_info = exc_info 

281 

282 @property 

283 def output(self) -> str: 

284 """The terminal output as unicode string, as the user would see it. 

285 

286 .. versionchanged:: 8.2 

287 No longer a proxy for ``self.stdout``. Now has its own independent stream 

288 that is mixing `<stdout>` and `<stderr>`, in the order they were written. 

289 """ 

290 return self.output_bytes.decode(self.runner.charset, "replace").replace( 

291 "\r\n", "\n" 

292 ) 

293 

294 @property 

295 def stdout(self) -> str: 

296 """The standard output as unicode string.""" 

297 return self.stdout_bytes.decode(self.runner.charset, "replace").replace( 

298 "\r\n", "\n" 

299 ) 

300 

301 @property 

302 def stderr(self) -> str: 

303 """The standard error as unicode string. 

304 

305 .. versionchanged:: 8.2 

306 No longer raise an exception, always returns the `<stderr>` string. 

307 """ 

308 return self.stderr_bytes.decode(self.runner.charset, "replace").replace( 

309 "\r\n", "\n" 

310 ) 

311 

312 def __repr__(self) -> str: 

313 exc_str = repr(self.exception) if self.exception else "okay" 

314 return f"<{type(self).__name__} {exc_str}>" 

315 

316 

317class CliRunner: 

318 """The CLI runner provides functionality to invoke a Click command line 

319 script for unittesting purposes in a isolated environment. This only 

320 works in single-threaded systems without any concurrency as it changes the 

321 global interpreter state. 

322 

323 :param charset: the character set for the input and output data. 

324 :param env: a dictionary with environment variables for overriding. 

325 :param echo_stdin: if this is set to `True`, then reading from `<stdin>` writes 

326 to `<stdout>`. This is useful for showing examples in 

327 some circumstances. Note that regular prompts 

328 will automatically echo the input. 

329 :param catch_exceptions: Whether to catch any exceptions other than 

330 ``SystemExit`` when running :meth:`~CliRunner.invoke`. 

331 :param capture: Selects the output capture strategy. ``sys`` (default) 

332 captures Python-level writes only and leaves 

333 :meth:`sys.stdout.fileno` raising :exc:`io.UnsupportedOperation`, so 

334 user code that calls :func:`os.dup2` on ``sys.stdout.fileno()`` cannot 

335 clobber the host runner's stdout. ``fd`` redirects file descriptors 

336 ``1`` and ``2`` via :func:`os.dup2` to a temporary file, also catching 

337 output from stale stream references, C extensions, and subprocesses. 

338 ``fd`` is not supported on Windows. 

339 

340 .. versionchanged:: 8.4.0 

341 Added the ``capture`` parameter. The default ``sys`` mode no longer exposes the 

342 original fd through :meth:`fileno`, reverting the change introduced in ``8.3.3`` 

343 that broke Pytest's ``fd``-level capture teardown. Use ``capture="fd"`` to 

344 restore that behavior with proper isolation. 

345 

346 .. versionchanged:: 8.2 

347 Added the ``catch_exceptions`` parameter. 

348 

349 .. versionchanged:: 8.2 

350 ``mix_stderr`` parameter has been removed. 

351 """ 

352 

353 charset: str 

354 env: cabc.Mapping[str, str | None] 

355 echo_stdin: bool 

356 catch_exceptions: bool 

357 capture: CaptureMode 

358 

359 def __init__( 

360 self, 

361 charset: str = "utf-8", 

362 env: cabc.Mapping[str, str | None] | None = None, 

363 echo_stdin: bool = False, 

364 catch_exceptions: bool = True, 

365 capture: CaptureMode = "sys", 

366 ) -> None: 

367 if capture not in {"sys", "fd"}: 

368 raise ValueError( 

369 f"capture={capture!r} is not valid. Choose from 'sys' or 'fd'." 

370 ) 

371 if capture == "fd" and sys.platform == "win32": 

372 raise ValueError( 

373 f"capture={capture!r} is not supported on Windows. Use 'sys'." 

374 ) 

375 self.charset = charset 

376 self.env = env or {} 

377 self.echo_stdin = echo_stdin 

378 self.catch_exceptions = catch_exceptions 

379 self.capture = capture 

380 

381 def get_default_prog_name(self, cli: Command) -> str: 

382 """Given a command object it will return the default program name 

383 for it. The default is the `name` attribute or ``"root"`` if not 

384 set. 

385 """ 

386 return cli.name or "root" 

387 

388 def make_env( 

389 self, overrides: cabc.Mapping[str, str | None] | None = None 

390 ) -> cabc.Mapping[str, str | None]: 

391 """Returns the environment overrides for invoking a script.""" 

392 rv = dict(self.env) 

393 if overrides: 

394 rv.update(overrides) 

395 return rv 

396 

397 @contextlib.contextmanager 

398 def isolation( 

399 self, 

400 input: str | bytes | t.IO[t.Any] | None = None, 

401 env: cabc.Mapping[str, str | None] | None = None, 

402 color: bool = False, 

403 ) -> cabc.Generator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]: 

404 """A context manager that sets up the isolation for invoking of a 

405 command line tool. This sets up `<stdin>` with the given input data 

406 and `os.environ` with the overrides from the given dictionary. 

407 This also rebinds some internals in Click to be mocked (like the 

408 prompt functionality). 

409 

410 This is automatically done in the :meth:`invoke` method. 

411 

412 :param input: the input stream to put into `sys.stdin`. 

413 :param env: the environment overrides as dictionary. 

414 :param color: whether the output should contain color codes. The 

415 application can still override this explicitly. 

416 

417 .. versionadded:: 8.2 

418 An additional output stream is returned, which is a mix of 

419 `<stdout>` and `<stderr>` streams. 

420 

421 .. versionchanged:: 8.2 

422 Always returns the `<stderr>` stream. 

423 

424 .. versionchanged:: 8.0 

425 `<stderr>` is opened with ``errors="backslashreplace"`` 

426 instead of the default ``"strict"``. 

427 

428 .. versionchanged:: 4.0 

429 Added the ``color`` parameter. 

430 """ 

431 bytes_input = make_input_stream(input, self.charset) 

432 echo_input = None 

433 

434 old_stdin = sys.stdin 

435 old_stdout = sys.stdout 

436 old_stderr = sys.stderr 

437 old_forced_width = formatting.FORCED_WIDTH 

438 formatting.FORCED_WIDTH = 80 

439 

440 env = self.make_env(env) 

441 

442 stream_mixer = StreamMixer() 

443 

444 if self.echo_stdin: 

445 bytes_input = echo_input = t.cast( 

446 t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout) 

447 ) 

448 

449 sys.stdin = text_input = _NamedTextIOWrapper( 

450 bytes_input, encoding=self.charset, name="<stdin>", mode="r" 

451 ) 

452 

453 if self.echo_stdin: 

454 # Force unbuffered reads, otherwise TextIOWrapper reads a 

455 # large chunk which is echoed early. 

456 text_input._CHUNK_SIZE = 1 # type: ignore 

457 

458 sys.stdout = _NamedTextIOWrapper( 

459 stream_mixer.stdout, 

460 encoding=self.charset, 

461 name="<stdout>", 

462 mode="w", 

463 ) 

464 

465 sys.stderr = _NamedTextIOWrapper( 

466 stream_mixer.stderr, 

467 encoding=self.charset, 

468 name="<stderr>", 

469 mode="w", 

470 errors="backslashreplace", 

471 ) 

472 

473 @_pause_echo(echo_input) # type: ignore 

474 def visible_input(prompt: str | None = None) -> str: 

475 sys.stdout.write(prompt or "") 

476 try: 

477 val = next(text_input).rstrip("\r\n") 

478 except StopIteration as e: 

479 raise EOFError() from e 

480 sys.stdout.write(f"{val}\n") 

481 sys.stdout.flush() 

482 return val 

483 

484 @_pause_echo(echo_input) # type: ignore 

485 def hidden_input(prompt: str | None = None) -> str: 

486 sys.stdout.write(f"{prompt or ''}\n") 

487 sys.stdout.flush() 

488 try: 

489 return next(text_input).rstrip("\r\n") 

490 except StopIteration as e: 

491 raise EOFError() from e 

492 

493 @_pause_echo(echo_input) # type: ignore 

494 def _getchar(echo: bool) -> str: 

495 char = sys.stdin.read(1) 

496 

497 if echo: 

498 sys.stdout.write(char) 

499 

500 sys.stdout.flush() 

501 return char 

502 

503 default_color = color 

504 

505 def should_strip_ansi( 

506 stream: t.IO[t.Any] | None = None, color: bool | None = None 

507 ) -> bool: 

508 if color is None: 

509 return not default_color 

510 return not color 

511 

512 old_visible_prompt_func = termui.visible_prompt_func 

513 old_hidden_prompt_func = termui.hidden_prompt_func 

514 old__getchar_func = termui._getchar 

515 old_should_strip_ansi = utils.should_strip_ansi # type: ignore 

516 old__compat_should_strip_ansi = _compat.should_strip_ansi 

517 old_pdb_init = pdb.Pdb.__init__ 

518 termui.visible_prompt_func = visible_input 

519 termui.hidden_prompt_func = hidden_input 

520 termui._getchar = _getchar 

521 utils.should_strip_ansi = should_strip_ansi # type: ignore 

522 _compat.should_strip_ansi = should_strip_ansi 

523 

524 def _patched_pdb_init( 

525 self: pdb.Pdb, 

526 completekey: str = "tab", 

527 stdin: t.IO[str] | None = None, 

528 stdout: t.IO[str] | None = None, 

529 **kwargs: t.Any, 

530 ) -> None: 

531 """Default ``pdb.Pdb`` to real terminal streams during 

532 ``CliRunner`` isolation. 

533 

534 Without this patch, ``pdb.Pdb.__init__`` inherits from 

535 ``cmd.Cmd`` which falls back to ``sys.stdin``/``sys.stdout`` 

536 when no explicit streams are provided. During isolation 

537 those are ``BytesIO``-backed wrappers, so the debugger 

538 reads from an empty buffer and writes to captured output, 

539 making interactive debugging impossible. 

540 

541 By defaulting to ``sys.__stdin__``/``sys.__stdout__`` (the 

542 original terminal streams Python preserves regardless of 

543 redirection), debuggers can interact with the user while 

544 ``click.echo`` output is still captured normally. 

545 

546 This covers ``pdb.set_trace()``, ``breakpoint()``, 

547 ``pdb.post_mortem()``, and debuggers that subclass 

548 ``pdb.Pdb`` (ipdb, pdbpp). Explicit ``stdin``/``stdout`` 

549 arguments are honored and not overridden. Debuggers that 

550 do not subclass ``pdb.Pdb`` (pudb, debugpy) are not 

551 covered. 

552 """ 

553 if stdin is None: 

554 stdin = sys.__stdin__ 

555 if stdout is None: 

556 stdout = sys.__stdout__ 

557 old_pdb_init( 

558 self, completekey=completekey, stdin=stdin, stdout=stdout, **kwargs 

559 ) 

560 

561 pdb.Pdb.__init__ = _patched_pdb_init # type: ignore[assignment] 

562 

563 old_env = {} 

564 try: 

565 for key, value in env.items(): 

566 old_env[key] = os.environ.get(key) 

567 if value is None: 

568 try: 

569 del os.environ[key] 

570 except Exception: 

571 pass 

572 else: 

573 os.environ[key] = value 

574 yield (stream_mixer.stdout, stream_mixer.stderr, stream_mixer.output) 

575 finally: 

576 for key, value in old_env.items(): 

577 if value is None: 

578 try: 

579 del os.environ[key] 

580 except Exception: 

581 pass 

582 else: 

583 os.environ[key] = value 

584 sys.stdout = old_stdout 

585 sys.stderr = old_stderr 

586 sys.stdin = old_stdin 

587 termui.visible_prompt_func = old_visible_prompt_func 

588 termui.hidden_prompt_func = old_hidden_prompt_func 

589 termui._getchar = old__getchar_func 

590 utils.should_strip_ansi = old_should_strip_ansi # type: ignore 

591 _compat.should_strip_ansi = old__compat_should_strip_ansi 

592 formatting.FORCED_WIDTH = old_forced_width 

593 pdb.Pdb.__init__ = old_pdb_init # type: ignore[method-assign] 

594 

595 def invoke( 

596 self, 

597 cli: Command, 

598 args: str | cabc.Sequence[str] | None = None, 

599 input: str | bytes | t.IO[t.Any] | None = None, 

600 env: cabc.Mapping[str, str | None] | None = None, 

601 catch_exceptions: bool | None = None, 

602 color: bool = False, 

603 **extra: t.Any, 

604 ) -> Result: 

605 """Invokes a command in an isolated environment. The arguments are 

606 forwarded directly to the command line script, the `extra` keyword 

607 arguments are passed to the :meth:`~clickpkg.Command.main` function of 

608 the command. 

609 

610 This returns a :class:`Result` object. 

611 

612 :param cli: the command to invoke 

613 :param args: the arguments to invoke. It may be given as an iterable 

614 or a string. When given as string it will be interpreted 

615 as a Unix shell command. More details at 

616 :func:`shlex.split`. 

617 :param input: the input data for `sys.stdin`. 

618 :param env: the environment overrides. 

619 :param catch_exceptions: Whether to catch any other exceptions than 

620 ``SystemExit``. If :data:`None`, the value 

621 from :class:`CliRunner` is used. 

622 :param extra: the keyword arguments to pass to :meth:`main`. 

623 :param color: whether the output should contain color codes. The 

624 application can still override this explicitly. 

625 

626 .. versionadded:: 8.2 

627 The result object has the ``output_bytes`` attribute with 

628 the mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would 

629 see it in its terminal. 

630 

631 .. versionchanged:: 8.2 

632 The result object always returns the ``stderr_bytes`` stream. 

633 

634 .. versionchanged:: 8.0 

635 The result object has the ``return_value`` attribute with 

636 the value returned from the invoked command. 

637 

638 .. versionchanged:: 4.0 

639 Added the ``color`` parameter. 

640 

641 .. versionchanged:: 3.0 

642 Added the ``catch_exceptions`` parameter. 

643 

644 .. versionchanged:: 3.0 

645 The result object has the ``exc_info`` attribute with the 

646 traceback if available. 

647 """ 

648 exc_info = None 

649 if catch_exceptions is None: 

650 catch_exceptions = self.catch_exceptions 

651 

652 # Set up fd capture before isolation replaces sys.stdout and sys.stderr. 

653 cap_out: _FDCapture | None = None 

654 cap_err: _FDCapture | None = None 

655 

656 if self.capture == "fd": 

657 cap_out = _FDCapture(1) 

658 cap_err = _FDCapture(2) 

659 try: 

660 cap_out.start() 

661 cap_err.start() 

662 except OSError: 

663 cap_out = cap_err = None 

664 

665 with self.isolation(input=input, env=env, color=color) as outstreams: 

666 # Point the captured streams' fileno() at the saved (original) 

667 # fd so that C-level consumers like faulthandler keep working 

668 # while fd 1/2 are redirected to the capture tmpfile. 

669 if cap_out is not None and cap_err is not None: 

670 sys.stdout._original_fd = cap_out.saved_fd # type: ignore[union-attr] 

671 sys.stderr._original_fd = cap_err.saved_fd # type: ignore[union-attr] 

672 

673 return_value = None 

674 exception: BaseException | None = None 

675 exit_code = 0 

676 

677 if isinstance(args, str): 

678 args = shlex.split(args) 

679 

680 try: 

681 prog_name = extra.pop("prog_name") 

682 except KeyError: 

683 prog_name = self.get_default_prog_name(cli) 

684 

685 try: 

686 return_value = cli.main(args=args or (), prog_name=prog_name, **extra) 

687 except SystemExit as e: 

688 exc_info = sys.exc_info() 

689 e_code = t.cast("int | t.Any | None", e.code) 

690 

691 if e_code is None: 

692 e_code = 0 

693 

694 if e_code != 0: 

695 exception = e 

696 

697 if not isinstance(e_code, int): 

698 sys.stdout.write(str(e_code)) 

699 sys.stdout.write("\n") 

700 e_code = 1 

701 

702 exit_code = e_code 

703 

704 except Exception as e: 

705 if not catch_exceptions: 

706 raise 

707 exception = e 

708 exit_code = 1 

709 exc_info = sys.exc_info() 

710 finally: 

711 sys.stdout.flush() 

712 sys.stderr.flush() 

713 

714 # Stop fd capture and merge the captured bytes into 

715 # the stdout/stderr BytesIO streams. BytesIOCopy mirrors 

716 # those writes into outstreams[2] automatically. 

717 if cap_out is not None and cap_err is not None: 

718 fd_out = cap_out.stop() 

719 fd_err = cap_err.stop() 

720 if fd_out: 

721 outstreams[0].write(fd_out) 

722 if fd_err: 

723 outstreams[1].write(fd_err) 

724 

725 stdout = outstreams[0].getvalue() 

726 stderr = outstreams[1].getvalue() 

727 output = outstreams[2].getvalue() 

728 

729 return Result( 

730 runner=self, 

731 stdout_bytes=stdout, 

732 stderr_bytes=stderr, 

733 output_bytes=output, 

734 return_value=return_value, 

735 exit_code=exit_code, 

736 exception=exception, 

737 exc_info=exc_info, # type: ignore 

738 ) 

739 

740 @contextlib.contextmanager 

741 def isolated_filesystem( 

742 self, temp_dir: str | os.PathLike[str] | None = None 

743 ) -> cabc.Generator[str]: 

744 """A context manager that creates a temporary directory and 

745 changes the current working directory to it. This isolates tests 

746 that affect the contents of the CWD to prevent them from 

747 interfering with each other. 

748 

749 .. warning:: 

750 This helper predates Python 3 and modern pytest, and is not thread-safe: it 

751 relies on :func:`os.chdir`, which mutates process-global state, and 

752 :meth:`invoke` swaps the process-global standard streams too. Parallelize 

753 tests with processes (``pytest-xdist``), not threads. Locking the runner was 

754 declined: a lock leaves the global-state mutation in place, and serializing 

755 thread-unsafe tests is the job of the test framework. A ``set_filesystem()`` 

756 API was declined as unneeded: pytest's ``tmp_path`` and 

757 ``monkeypatch.chdir()`` cover that case. 

758 

759 :param temp_dir: Create the temporary directory under this 

760 directory. If given, the created directory is not removed 

761 when exiting. 

762 

763 .. deprecated:: 8.5.0 

764 Will be removed in Click 9.0. Use 

765 :class:`tempfile.TemporaryDirectory` or pytest's 

766 ``tmp_path`` fixture with absolute paths instead. 

767 

768 .. versionchanged:: 8.0 

769 Added the ``temp_dir`` parameter. 

770 """ 

771 import warnings 

772 

773 warnings.warn( 

774 "'isolated_filesystem' is deprecated and will be removed in Click" 

775 " 9.0. Use 'tempfile.TemporaryDirectory' or pytest's 'tmp_path'" 

776 " fixture with absolute paths instead.", 

777 DeprecationWarning, 

778 stacklevel=3, 

779 ) 

780 

781 cwd = os.getcwd() 

782 dt = tempfile.mkdtemp(dir=temp_dir) 

783 os.chdir(dt) 

784 

785 try: 

786 yield dt 

787 finally: 

788 os.chdir(cwd) 

789 

790 if temp_dir is None: 

791 import shutil 

792 

793 try: 

794 shutil.rmtree(dt) 

795 except OSError: 

796 pass