Skip to content
Myr

Revert "Deprecate `isolated_filesystem` and document its limits"

Before adoption: this commit came in with the history the project adopted, so no landing records it.

This reverts commit fbdd434028fe07ecf35084c945b43b938dfd639f.

authored by Kevin Deldycke · committed by Kevin Deldycke · parent fbdd434 · Browse files · 9 files+161 added−288 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+161 added−288 removed

  • tests:+133 added−208 removed
  • other:+28 added−80 removed

9 files+161 added−288 removed

modified:docs/testing.md+27 added-45 removed
5 unmodified lines
67Click provides the {ref}`click.testing <testing>` module to help you invoke8command line applications and check their behavior.910```{warning}11These tools should only be used for testing since they change the entire12interpreter state for simplicity. They are not thread-safe: see13[Running tests in parallel](#running-tests-in-parallel) for the supported14way to run CLI tests concurrently.15```10These tools should only be used for testing since they change11the entire interpreter state for simplicity. They are not thread-safe!1213The examples use [pytest](https://docs.pytest.org/en/stable/) style tests.1415```{contents}
102 unmodified lines
118```119120## File System Isolation121126To test a command that reads or writes files, give each test its own127directory and pass absolute paths to the command. Pytest's128[`tmp_path`](https://docs.pytest.org/en/stable/how-to/tmp_path.html) fixture129provides a fresh directory per test; {class}`tempfile.TemporaryDirectory`130works without pytest.122The {meth}`CliRunner.isolated_filesystem` context manager sets the current123working directory to a new, empty folder.124125```{code-block} python126:caption: cat.py127
10 unmodified lines
138139from click.testing import CliRunner140from cat import cat141149def test_cat(tmp_path):150 hello = tmp_path / 'hello.txt'151 hello.write_text('Hello World!')152142def test_cat():143 runner = CliRunner()144 with runner.isolated_filesystem():145 with open('hello.txt', 'w') as f:146 f.write('Hello World!')147154 result = runner.invoke(cat, [str(hello)])155 assert result.exit_code == 0156 assert result.output == 'Hello World!\n'148 result = runner.invoke(cat, ['hello.txt'])149 assert result.exit_code == 0150 assert result.output == 'Hello World!\n'151```152159Because the directory is unique to the test and the command receives an160absolute path, nothing leaks between tests and the working directory is never161changed.153Pass in a path to control where the temporary directory is created.154In this case, the directory will not be removed by Click. Its useful155to integrate with a framework like Pytest that manages temporary files.156163### Running tests in parallel157```{code-block} python158:caption: test_cat.py159165Isolating the file system with pytest is thread-safe: each test, or each thread,166works in its own directory through absolute paths, with no shared state.160from click.testing import CliRunner161from cat import cat162168{meth}`CliRunner.invoke` is different. While a command runs it swaps several169pieces of process-global state into place (like `sys.stdout`, `sys.stderr`,170`sys.stdin`, etc). Two invocations active at the same time in one interpreter171overwrite each other's state, so the runner cannot be driven from several172threads at once.163def test_cat_with_path_specified():164 runner = CliRunner()165 with runner.isolated_filesystem('~/test_folder'):166 with open('hello.txt', 'w') as f:167 f.write('Hello World!')168174```{warning}175Do not parallelize CLI tests with threads. Use process-based isolation176instead, where each worker has its own interpreter and its own copy of those177globals. [pytest-xdist](https://pytest-xdist.readthedocs.io/) does this with178`pytest --numprocesses=auto`.169 result = runner.invoke(cat, ['hello.txt'])170 assert result.exit_code == 0171 assert result.output == 'Hello World!\n'172```173181Click's own test suite uses exactly this setup: the `tests-random` dependency182group and the `random` tox environment in183[`pyproject.toml`](https://github.com/pallets/click/blob/main/pyproject.toml)184run the suite under `pytest-randomly` and `pytest-xdist` to surface ordering185bugs and races.186187```{deprecated} 8.5.0188{meth}`CliRunner.isolated_filesystem` is deprecated and will be removed in189Click 9.0. Use a temporary directory with absolute paths, as shown above.190```191174## Input Streams175176The test wrapper can provide input data for the input stream (stdin). This is177very useful for testing prompts.
88 unmodified lines
modified:docs/upgrade-guides.md+1 added-1 removed
modified:src/click/testing.py-26 removed
745 unmodified lines
746 changes the current working directory to it. This isolates tests747 that affect the contents of the CWD to prevent them from748 interfering with each other.749750 .. warning::751 This helper predates Python 3 and modern pytest, and is not752 thread-safe: it relies on :func:`os.chdir`, which mutates753 process-global state, and :meth:`invoke` swaps the754 process-global standard streams too. Parallelize tests with755 processes (``pytest-xdist``), not threads. Locking the756 runner (:pr:`3511`, :pr:`3520`, :pr:`3530`) and a757 ``set_filesystem()`` API (:issue:`3123`) were declined:758 neither removes the global-state mutation. See :issue:`3700`759 and :issue:`3501`.760750 :param temp_dir: Create the temporary directory under this751 directory. If given, the created directory is not removed752 when exiting.753765 .. deprecated:: 8.5.0766 Will be removed in Click 9.0. Use767 :class:`tempfile.TemporaryDirectory` or pytest's768 ``tmp_path`` fixture with absolute paths instead.769754 .. versionchanged:: 8.0755 Added the ``temp_dir`` parameter.756 """773 import warnings774775 warnings.warn(776 "'isolated_filesystem' is deprecated and will be removed in Click"777 " 9.0. Use 'tempfile.TemporaryDirectory' or pytest's 'tmp_path'"778 " fixture with absolute paths instead.",779 DeprecationWarning,780 stacklevel=3,781 )782757 cwd = os.getcwd()758 dt = tempfile.mkdtemp(dir=temp_dir)759 os.chdir(dt)760
12 unmodified lines
modified:tests/test_utils/test_open_file.py+55 added-50 removed
6 unmodified lines
7import click8from click._compat import WIN91011def test_open_file(runner, tmp_path):11def test_open_file(runner):12 @click.command()13 @click.argument("filename")14 def cli(filename):15 with click.open_file(filename) as f:16 click.echo(f.read())1718 click.echo("meep")1920 hello = tmp_path / "hello.txt"21 hello.write_text("Cool stuff")20 with runner.isolated_filesystem():21 with open("hello.txt", "w") as f:22 f.write("Cool stuff")2323 result = runner.invoke(cli, [str(hello)])24 assert result.exception is None25 assert result.output == "Cool stuff\nmeep\n"24 result = runner.invoke(cli, ["hello.txt"])25 assert result.exception is None26 assert result.output == "Cool stuff\nmeep\n"2727 result = runner.invoke(cli, ["-"], input="foobar")28 assert result.exception is None29 assert result.output == "foobar\nmeep\n"28 result = runner.invoke(cli, ["-"], input="foobar")29 assert result.exception is None30 assert result.output == "foobar\nmeep\n"313233def test_open_file_pathlib_dash(runner):34 @click.command()
21 unmodified lines
56 result = runner.invoke(cli, ["-"], input=os.urandom(16))57 assert result.exception is None585959def test_open_file_respects_ignore(tmp_path):60 path = tmp_path / "test.txt"61 path.write_text("Hello world!")60def test_open_file_respects_ignore(runner):61 with runner.isolated_filesystem():62 with open("test.txt", "w") as f:63 f.write("Hello world!")6463 with click.open_file(str(path), encoding="utf8", errors="ignore") as f:64 assert f.errors == "ignore"65 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:66 assert f.errors == "ignore"676867def test_open_file_ignore_invalid_utf8(tmp_path):68 path = tmp_path / "test.txt"69 path.write_bytes(b"\xe2\x28\xa1")69def test_open_file_ignore_invalid_utf8(runner):70 with runner.isolated_filesystem():71 with open("test.txt", "wb") as f:72 f.write(b"\xe2\x28\xa1")7371 with click.open_file(str(path), encoding="utf8", errors="ignore") as f:72 f.read()74 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:75 f.read()767775def test_open_file_ignore_no_encoding(tmp_path):76 path = tmp_path / "test.bin"77 path.write_bytes(os.urandom(16))78def test_open_file_ignore_no_encoding(runner):79 with runner.isolated_filesystem():80 with open("test.bin", "wb") as f:81 f.write(os.urandom(16))8279 with click.open_file(str(path), errors="ignore") as f:80 f.read()83 with click.open_file("test.bin", errors="ignore") as f:84 f.read()858687@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")88@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])85def test_open_file_atomic_permissions_existing_file(runner, tmp_path, permissions):86 existing = tmp_path / "existing.txt"87 existing.write_text("content")88 os.chmod(existing, permissions)89def test_open_file_atomic_permissions_existing_file(runner, permissions):90 with runner.isolated_filesystem():91 with open("existing.txt", "w") as f:92 f.write("content")93 os.chmod("existing.txt", permissions)9490 @click.command()91 @click.argument("filename")92 def cli(filename):93 click.open_file(filename, "w", atomic=True).close()95 @click.command()96 @click.argument("filename")97 def cli(filename):98 click.open_file(filename, "w", atomic=True).close()9995 result = runner.invoke(cli, [str(existing)])96 assert result.exception is None97 assert stat.S_IMODE(os.stat(existing).st_mode) == permissions100 result = runner.invoke(cli, ["existing.txt"])101 assert result.exception is None102 assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions103104105@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")101def test_open_file_atomic_permissions_new_file(runner, tmp_path):102 @click.command()103 @click.argument("filename")104 def cli(filename):105 click.open_file(filename, "w", atomic=True).close()106def test_open_file_atomic_permissions_new_file(runner):107 with runner.isolated_filesystem():108107 # Create a test file to get the expected permissions for new files108 # according to the current umask.109 probe = tmp_path / "test.txt"110 with open(probe, "w"):111 pass112 permissions = stat.S_IMODE(os.stat(probe).st_mode)109 @click.command()110 @click.argument("filename")111 def cli(filename):112 click.open_file(filename, "w", atomic=True).close()113114 # Create a test file to get the expected permissions for new files115 # according to the current umask.116 with open("test.txt", "w"):117 pass118 permissions = stat.S_IMODE(os.stat("test.txt").st_mode)114 new = tmp_path / "new.txt"115 result = runner.invoke(cli, [str(new)])116 assert result.exception is None117 assert stat.S_IMODE(os.stat(new).st_mode) == permissions119120 result = runner.invoke(cli, ["new.txt"])121 assert result.exception is None122 assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions
modified:tests/test_arguments.py+19 added-16 removed
100 unmodified lines
101 catch_exceptions=False,102 )103104105def test_file_args(runner, tmp_path):105def test_file_args(runner):106 @click.command()107 @click.argument("input", type=click.File("rb"))108 @click.argument("output", type=click.File("wb"))109 def inout(input, output):
2 unmodified lines
112 if not chunk:113 break114 output.write(chunk)115116 hello = tmp_path / "hello.txt"117 result = runner.invoke(inout, ["-", str(hello)], input="Hey!")118 assert result.output == ""119 assert result.exit_code == 0120 assert hello.read_bytes() == b"Hey!"116 with runner.isolated_filesystem():117 result = runner.invoke(inout, ["-", "hello.txt"], input="Hey!")118 assert result.output == ""119 assert result.exit_code == 0120 with open("hello.txt", "rb") as f:121 assert f.read() == b"Hey!"122122 result = runner.invoke(inout, [str(hello), "-"])123 assert result.output == "Hey!"124 assert result.exit_code == 0123 result = runner.invoke(inout, ["hello.txt", "-"])124 assert result.output == "Hey!"125 assert result.exit_code == 0126127128def test_path_allow_dash(runner):129 @click.command()
5 unmodified lines
135 assert result.output == "-\n"136 assert result.exit_code == 0137138138def test_file_atomics(runner, tmp_path):139def test_file_atomics(runner):140 @click.command()141 @click.argument("output", type=click.File("wb", atomic=True))142 def inout(output):143 output.write(b"Foo bar baz\n")
1 unmodified line
145 with open(output.name, "rb") as f:146 old_content = f.read()147 assert old_content == b"OLD\n"148148 foo = tmp_path / "foo.txt"149 foo.write_bytes(b"OLD\n")150 result = runner.invoke(inout, [str(foo)], input="Hey!", catch_exceptions=False)151 assert result.output == ""152 assert result.exit_code == 0153 assert foo.read_bytes() == b"Foo bar baz\n"149 with runner.isolated_filesystem():150 with open("foo.txt", "wb") as f:151 f.write(b"OLD\n")152 result = runner.invoke(inout, ["foo.txt"], input="Hey!", catch_exceptions=False)153 assert result.output == ""154 assert result.exit_code == 0155 with open("foo.txt", "rb") as f:156 assert f.read() == b"Foo bar baz\n"157158159def test_stdout_default(runner):160 @click.command()
583 unmodified lines
modified:tests/test_basic.py+40 added-38 removed
413 unmodified lines
414 result = runner.invoke(cli, args)415 assert result.output == repr(expected)416417418def test_file_option(runner, tmp_path):418def test_file_option(runner):419 @click.command()420 @click.option("--file", type=click.File("w"))421 def input(file):422 file.write("Hello World!\n")
2 unmodified lines
425 @click.option("--file", type=click.File("r"))426 def output(file):427 click.echo(file.read())428429 example = tmp_path / "example.txt"430 result_in = runner.invoke(input, [f"--file={example}"])431 result_out = runner.invoke(output, [f"--file={example}"])429 with runner.isolated_filesystem():430 result_in = runner.invoke(input, ["--file=example.txt"])431 result_out = runner.invoke(output, ["--file=example.txt"])432433 assert not result_in.exception434 assert result_in.output == ""435 assert not result_out.exception436 assert result_out.output == "Hello World!\n\n"437438439def test_file_lazy_mode(runner, tmp_path):439def test_file_lazy_mode(runner):440 do_io = False441442 @click.command()443 @click.option("--file", type=click.File("w"))
5 unmodified lines
449 @click.option("--file", type=click.File("r"))450 def output(file):451 pass452453 example = tmp_path / "example.txt"454 example.mkdir()453 with runner.isolated_filesystem():454 os.mkdir("example.txt")455456 do_io = True457 result_in = runner.invoke(input, [f"--file={example}"])458 assert result_in.exit_code == 1456 do_io = True457 result_in = runner.invoke(input, ["--file=example.txt"])458 assert result_in.exit_code == 1459460 do_io = False461 result_in = runner.invoke(input, [f"--file={example}"])462 assert result_in.exit_code == 0460 do_io = False461 result_in = runner.invoke(input, ["--file=example.txt"])462 assert result_in.exit_code == 0463464 result_out = runner.invoke(output, [f"--file={example}"])465 assert result_out.exception464 result_out = runner.invoke(output, ["--file=example.txt"])465 assert result_out.exception466467 @click.command()468 @click.option("--file", type=click.File("w", lazy=False))469 def input_non_lazy(file):470 file.write("Hello World!\n")471472 non_lazy = tmp_path / "non_lazy.txt"473 non_lazy.mkdir()474 result_in = runner.invoke(input_non_lazy, [f"--file={non_lazy}"])475 assert result_in.exit_code == 2476 assert f"Invalid value for '--file': '{non_lazy}'" in result_in.output472 with runner.isolated_filesystem():473 os.mkdir("example.txt")474 result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])475 assert result_in.exit_code == 2476 assert "Invalid value for '--file': 'example.txt'" in result_in.output477478479def test_path_option(runner, tmp_path):479def test_path_option(runner):480 @click.command()481 @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True))482 def write_to_dir(o):483 with open(os.path.join(o, "foo.txt"), "wb") as f:484 f.write(b"meh\n")485486 test_dir = tmp_path / "test"487 test_dir.mkdir()486 with runner.isolated_filesystem():487 os.mkdir("test")488489 result = runner.invoke(write_to_dir, ["-O", str(test_dir)])490 assert not result.exception489 result = runner.invoke(write_to_dir, ["-O", "test"])490 assert not result.exception491492 with open(test_dir / "foo.txt", "rb") as f:493 assert f.read() == b"meh\n"492 with open("test/foo.txt", "rb") as f:493 assert f.read() == b"meh\n"494495 result = runner.invoke(write_to_dir, ["-O", str(test_dir / "foo.txt")])496 assert "is a file" in result.output495 result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"])496 assert "is a file" in result.output497498 @click.command()499 @click.option("-f", type=click.Path(exists=True))500 def showtype(f):501 click.echo(f"is_file={os.path.isfile(f)}")502 click.echo(f"is_dir={os.path.isdir(f)}")503504 with runner.isolated_filesystem():504 result = runner.invoke(showtype, ["-f", str(tmp_path / "xxx")])505 assert "does not exist" in result.output505 result = runner.invoke(showtype, ["-f", "xxx"])506 assert "does not exist" in result.output507507 result = runner.invoke(showtype, ["-f", str(tmp_path)])508 assert "is_file=False" in result.output509 assert "is_dir=True" in result.output508 result = runner.invoke(showtype, ["-f", "."])509 assert "is_file=False" in result.output510 assert "is_dir=True" in result.output511512 @click.command()513 @click.option("-f", type=click.Path())514 def exists(f):515 click.echo(f"exists={os.path.exists(f)}")516517 with runner.isolated_filesystem():516 result = runner.invoke(exists, ["-f", str(tmp_path / "xxx")])517 assert "exists=False" in result.output518 result = runner.invoke(exists, ["-f", "xxx"])519 assert "exists=False" in result.output520519 result = runner.invoke(exists, ["-f", str(tmp_path)])520 assert "exists=True" in result.output521 result = runner.invoke(exists, ["-f", "."])522 assert "exists=True" in result.output523524525def test_choice_option(runner):526 @click.command()
438 unmodified lines
modified:tests/test_shell_completion.py+19 added-18 removed
572 unmodified lines
573 assert click.shell_completion._available_shells["mysh"] is MyshComplete574575576# Don't make the ResourceWarning give an error577@pytest.mark.filterwarnings("default::ResourceWarning")578def test_files_closed(tmp_path) -> None:579 config_file = str(tmp_path / "foo.txt")580 with open(config_file, "w") as f:581 f.write("bar")577@pytest.mark.filterwarnings("default")578def test_files_closed(runner) -> None:579 with runner.isolated_filesystem():580 config_file = "foo.txt"581 with open(config_file, "w") as f:582 f.write("bar")583583 @click.group()584 @click.option(585 "--config-file",586 default=config_file,587 type=click.File(mode="r"),588 )589 @click.pass_context590 def cli(ctx, config_file):591 pass584 @click.group()585 @click.option(586 "--config-file",587 default=config_file,588 type=click.File(mode="r"),589 )590 @click.pass_context591 def cli(ctx, config_file):592 pass593593 with warnings.catch_warnings(record=True) as current_warnings:594 assert not current_warnings, "There should be no warnings to start"595 _get_completions(cli, args=[], incomplete="")596 assert not current_warnings, "There should be no warnings after either"594 with warnings.catch_warnings(record=True) as current_warnings:595 assert not current_warnings, "There should be no warnings to start"596 _get_completions(cli, args=[], incomplete="")597 assert not current_warnings, "There should be no warnings after either"598599600def test_fish_format_completion_escapes_help():601 fc = FishComplete(Command("x"), {}, "x", "_X_COMPLETE")
17 unmodified lines
modified:tests/test_testing.py-86 removed
438 unmodified lines
439 result = runner.invoke(cli, ["-"])440 assert result.output == "<stdin>\nr"441442443@pytest.mark.filterwarnings("ignore:'isolated_filesystem':DeprecationWarning")443def test_isolated_runner(runner):444 with runner.isolated_filesystem() as d:445 assert os.path.exists(d)446447 assert not os.path.exists(d)448449451@pytest.mark.filterwarnings("ignore:'isolated_filesystem':DeprecationWarning")450def test_isolated_runner_custom_tempdir(runner, tmp_path):451 with runner.isolated_filesystem(temp_dir=tmp_path) as d:452 assert os.path.exists(d)453454 assert os.path.exists(d)455 os.rmdir(d)456457460def test_isolated_filesystem_deprecated(runner):461 """``isolated_filesystem()`` warns: it relies on non-thread-safe ``os.chdir``."""462 with pytest.warns(DeprecationWarning, match="isolated_filesystem"):463 with runner.isolated_filesystem():464 pass465466467def test_tempdir_replacement_pattern(runner, tmp_path):468 """The replacement for ``isolated_filesystem()``: a temp dir and absolute paths.469470 Rather than changing the working directory, create a directory (here with471 pytest's ``tmp_path``; ``tempfile.TemporaryDirectory`` works the same) and472 pass absolute paths to the command.473 """474475 @click.command()476 @click.argument("path", type=click.Path())477 def write_marker(path):478 with open(path, "w") as f:479 f.write("written")480481 target = tmp_path / "marker.txt"482 result = runner.invoke(write_marker, [str(target)])483484 assert result.exit_code == 0485 assert target.read_text() == "written"486487488def test_tempdir_isolation_is_thread_safe():489 """The recommended replacement is thread-safe, unlike ``isolated_filesystem()``.490491 Each thread owns a ``tempfile.TemporaryDirectory`` and works through492 absolute paths, so there is no ``os.chdir`` and no process-global CWD race493 (the reason ``isolated_filesystem()`` is not thread-safe, issue #3501).494495 ``invoke()`` is deliberately not called concurrently here: it redirects the496 process-global standard streams, so parallel invocations in one process497 corrupt each other regardless of the filesystem. To run commands in498 parallel, use separate processes (like pytest-xdist), not threads.499 """500 import tempfile501 import threading502503 workers = 8504 cwd_before = os.path.realpath(os.getcwd())505 results: list[tuple[str, str, str]] = []506 barrier = threading.Barrier(workers)507 lock = threading.Lock()508509 def worker(index):510 with tempfile.TemporaryDirectory() as d:511 target = os.path.join(d, "data.txt")512 # Release every thread at once to maximize contention.513 barrier.wait(timeout=10)514 with open(target, "w") as f:515 f.write(f"payload-{index}")516 with open(target) as f:517 content = f.read()518 with lock:519 results.append(520 (521 os.path.realpath(d),522 os.path.realpath(os.getcwd()),523 content,524 )525 )526527 threads = [threading.Thread(target=worker, args=(i,)) for i in range(workers)]528 for t in threads:529 t.start()530 for t in threads:531 t.join(timeout=10)532533 assert len(results) == workers534 # Every thread had its own distinct directory.535 assert len({d for d, _, _ in results}) == workers536 # No thread mutated the process-global working directory.537 assert {cwd for _, cwd, _ in results} == {cwd_before}538 # Each thread read back exactly the payload it wrote, with no cross-talk.539 assert sorted(content for _, _, content in results) == sorted(540 f"payload-{i}" for i in range(workers)541 )542543458def test_isolation_stderr_errors():459 """Writing to stderr should escape invalid characters instead of460 raising a UnicodeEncodeError.461 """
300 unmodified lines
modified:CHANGES.md-8 removed
41 unmodified lines
42 now private (`_`-prefixed). The old names remain available with a43 `DeprecationWarning` until Click 9.0: `LazyFile`, `KeepOpenFile`,44 `make_default_short_help`, `PacifyFlushWrapper`, and `safecall`.45 {issue}`3099` {pr}`3695`46- Deprecate {meth}`CliRunner.isolated_filesystem`. It relies on47 {func}`os.chdir`, which mutates process-global state and is not48 thread-safe. The helper predates Python 3 and modern pytest: use a49 temporary directory ({class}`tempfile.TemporaryDirectory` or pytest's50 `tmp_path` fixture) with absolute paths instead. For running tests in51 parallel, use process-based isolation (such as `pytest-xdist`) rather52 than threads, since {meth}`CliRunner.invoke` also redirects the53 process-global standard streams. {issue}`3501` {issue}`3700`4647## Version 8.4.24849Released 2026-06-24
1561 unmodified lines