Skip to content
Myr

Deprecate `isolated_filesystem` and document its limits (#3704)

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

authored by Rowlando13 · committed by GitHub · parents 333c28d, c2ed414 · Browse files · 10 files+287 added−161 removed
This commit

State

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

Diff stats

10 files+287 added−161 removed

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

10 files+287 added−161 removed

modified:docs/testing.md+45 added-27 removed
5 unmodified lines
67Click provides the {ref}`click.testing <testing>` module to help you invoke8command line applications and check their behavior.910These tools should only be used for testing since they change11the entire interpreter state for simplicity. They are not thread-safe!10```{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```1617The examples use [pytest](https://docs.pytest.org/en/stable/) style tests.1819```{contents}
102 unmodified lines
122```123124## File System Isolation125122The {meth}`CliRunner.isolated_filesystem` context manager sets the current123working directory to a new, empty folder.126To 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.131132```{code-block} python133:caption: cat.py134
10 unmodified lines
145146from click.testing import CliRunner147from cat import cat148142def test_cat():143 runner = CliRunner()144 with runner.isolated_filesystem():145 with open('hello.txt', 'w') as f:146 f.write('Hello World!')149def test_cat(tmp_path):150 hello = tmp_path / 'hello.txt'151 hello.write_text('Hello World!')152153 runner = CliRunner()148 result = runner.invoke(cat, ['hello.txt'])149 assert result.exit_code == 0150 assert result.output == 'Hello World!\n'154 result = runner.invoke(cat, [str(hello)])155 assert result.exit_code == 0156 assert result.output == 'Hello World!\n'157```158153Pass 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.159Because the directory is unique to the test and the command receives an160absolute path, nothing leaks between tests and the working directory is never161changed.162157```{code-block} python158:caption: test_cat.py163### Running tests in parallel164160from click.testing import CliRunner161from cat import cat165Isolating 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.167163def 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!')168{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.173169 result = runner.invoke(cat, ['hello.txt'])170 assert result.exit_code == 0171 assert result.output == 'Hello World!\n'174```{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`.179```180181Click'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```191192## Input Streams193194The test wrapper can provide input data for the input stream (stdin). This is195very useful for testing prompts.
88 unmodified lines
modified:docs/upgrade-guides.md+1 added-1 removed
modified:src/click/testing.py+26 added
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`.760761 :param temp_dir: Create the temporary directory under this762 directory. If given, the created directory is not removed763 when exiting.764765 .. 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.769770 .. versionchanged:: 8.0771 Added the ``temp_dir`` parameter.772 """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 )782783 cwd = os.getcwd()784 dt = tempfile.mkdtemp(dir=temp_dir)785 os.chdir(dt)786
12 unmodified lines
modified:tests/test_utils/test_open_file.py+50 added-55 removed
6 unmodified lines
7import click8from click._compat import WIN91011def test_open_file(runner):11def test_open_file(runner, tmp_path):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 with runner.isolated_filesystem():21 with open("hello.txt", "w") as f:22 f.write("Cool stuff")20 hello = tmp_path / "hello.txt"21 hello.write_text("Cool stuff")2224 result = runner.invoke(cli, ["hello.txt"])25 assert result.exception is None26 assert result.output == "Cool stuff\nmeep\n"23 result = runner.invoke(cli, [str(hello)])24 assert result.exception is None25 assert result.output == "Cool stuff\nmeep\n"2628 result = runner.invoke(cli, ["-"], input="foobar")29 assert result.exception is None30 assert result.output == "foobar\nmeep\n"27 result = runner.invoke(cli, ["-"], input="foobar")28 assert result.exception is None29 assert result.output == "foobar\nmeep\n"303132def test_open_file_pathlib_dash(runner):33 @click.command()
21 unmodified lines
55 result = runner.invoke(cli, ["-"], input=os.urandom(16))56 assert result.exception is None575860def test_open_file_respects_ignore(runner):61 with runner.isolated_filesystem():62 with open("test.txt", "w") as f:63 f.write("Hello world!")59def test_open_file_respects_ignore(tmp_path):60 path = tmp_path / "test.txt"61 path.write_text("Hello world!")6265 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:66 assert f.errors == "ignore"63 with click.open_file(str(path), encoding="utf8", errors="ignore") as f:64 assert f.errors == "ignore"656669def 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")67def test_open_file_ignore_invalid_utf8(tmp_path):68 path = tmp_path / "test.txt"69 path.write_bytes(b"\xe2\x28\xa1")7074 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:75 f.read()71 with click.open_file(str(path), encoding="utf8", errors="ignore") as f:72 f.read()737478def 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))75def test_open_file_ignore_no_encoding(tmp_path):76 path = tmp_path / "test.bin"77 path.write_bytes(os.urandom(16))7883 with click.open_file("test.bin", errors="ignore") as f:84 f.read()79 with click.open_file(str(path), errors="ignore") as f:80 f.read()818283@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")84@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])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)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)8995 @click.command()96 @click.argument("filename")97 def cli(filename):98 click.open_file(filename, "w", atomic=True).close()90 @click.command()91 @click.argument("filename")92 def cli(filename):93 click.open_file(filename, "w", atomic=True).close()94100 result = runner.invoke(cli, ["existing.txt"])101 assert result.exception is None102 assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions95 result = runner.invoke(cli, [str(existing)])96 assert result.exception is None97 assert stat.S_IMODE(os.stat(existing).st_mode) == permissions9899100@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")106def test_open_file_atomic_permissions_new_file(runner):107 with runner.isolated_filesystem():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()106109 @click.command()110 @click.argument("filename")111 def cli(filename):112 click.open_file(filename, "w", atomic=True).close()107 # 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)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)119120 result = runner.invoke(cli, ["new.txt"])121 assert result.exception is None122 assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions114 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) == permissions
modified:tests/test_arguments.py+16 added-19 removed
100 unmodified lines
101 catch_exceptions=False,102 )103104105def test_file_args(runner):105def test_file_args(runner, tmp_path):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 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!"116 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!"121123 result = runner.invoke(inout, ["hello.txt", "-"])124 assert result.output == "Hey!"125 assert result.exit_code == 0122 result = runner.invoke(inout, [str(hello), "-"])123 assert result.output == "Hey!"124 assert result.exit_code == 0125126127def test_path_allow_dash(runner):128 @click.command()
5 unmodified lines
134 assert result.output == "-\n"135 assert result.exit_code == 0136137139def test_file_atomics(runner):138def test_file_atomics(runner, tmp_path):139 @click.command()140 @click.argument("output", type=click.File("wb", atomic=True))141 def inout(output):142 output.write(b"Foo bar baz\n")
1 unmodified line
144 with open(output.name, "rb") as f:145 old_content = f.read()146 assert old_content == b"OLD\n"147149 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"148 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"154155156def test_stdout_default(runner):157 @click.command()
583 unmodified lines
modified:tests/test_basic.py+38 added-40 removed
413 unmodified lines
414 result = runner.invoke(cli, args)415 assert result.output == repr(expected)416417418def test_file_option(runner):418def test_file_option(runner, tmp_path):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 with runner.isolated_filesystem():430 result_in = runner.invoke(input, ["--file=example.txt"])431 result_out = runner.invoke(output, ["--file=example.txt"])429 example = tmp_path / "example.txt"430 result_in = runner.invoke(input, [f"--file={example}"])431 result_out = runner.invoke(output, [f"--file={example}"])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):439def test_file_lazy_mode(runner, tmp_path):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 with runner.isolated_filesystem():454 os.mkdir("example.txt")453 example = tmp_path / "example.txt"454 example.mkdir()455456 do_io = True457 result_in = runner.invoke(input, ["--file=example.txt"])458 assert result_in.exit_code == 1456 do_io = True457 result_in = runner.invoke(input, [f"--file={example}"])458 assert result_in.exit_code == 1459460 do_io = False461 result_in = runner.invoke(input, ["--file=example.txt"])462 assert result_in.exit_code == 0460 do_io = False461 result_in = runner.invoke(input, [f"--file={example}"])462 assert result_in.exit_code == 0463464 result_out = runner.invoke(output, ["--file=example.txt"])465 assert result_out.exception464 result_out = runner.invoke(output, [f"--file={example}"])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 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.output472 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.output477478479def test_path_option(runner):479def test_path_option(runner, tmp_path):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 with runner.isolated_filesystem():487 os.mkdir("test")486 test_dir = tmp_path / "test"487 test_dir.mkdir()488489 result = runner.invoke(write_to_dir, ["-O", "test"])490 assert not result.exception489 result = runner.invoke(write_to_dir, ["-O", str(test_dir)])490 assert not result.exception491492 with open("test/foo.txt", "rb") as f:493 assert f.read() == b"meh\n"492 with open(test_dir / "foo.txt", "rb") as f:493 assert f.read() == b"meh\n"494495 result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"])496 assert "is a file" in result.output495 result = runner.invoke(write_to_dir, ["-O", str(test_dir / "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():505 result = runner.invoke(showtype, ["-f", "xxx"])506 assert "does not exist" in result.output504 result = runner.invoke(showtype, ["-f", str(tmp_path / "xxx")])505 assert "does not exist" in result.output506508 result = runner.invoke(showtype, ["-f", "."])509 assert "is_file=False" in result.output510 assert "is_dir=True" in result.output507 result = runner.invoke(showtype, ["-f", str(tmp_path)])508 assert "is_file=False" in result.output509 assert "is_dir=True" in result.output510511 @click.command()512 @click.option("-f", type=click.Path())513 def exists(f):514 click.echo(f"exists={os.path.exists(f)}")515517 with runner.isolated_filesystem():518 result = runner.invoke(exists, ["-f", "xxx"])519 assert "exists=False" in result.output516 result = runner.invoke(exists, ["-f", str(tmp_path / "xxx")])517 assert "exists=False" in result.output518521 result = runner.invoke(exists, ["-f", "."])522 assert "exists=True" in result.output519 result = runner.invoke(exists, ["-f", str(tmp_path)])520 assert "exists=True" in result.output521522523def test_choice_option(runner):524 @click.command()
438 unmodified lines
modified:tests/test_deprecations.py+6 added
21 unmodified lines
22)23def test_utilities_deprecated(name):24 with pytest.warns(DeprecationWarning, match=name):25 getattr(click.utils, name)262728def test_isolated_filesystem_deprecated(runner):29 with pytest.warns(DeprecationWarning, match="isolated_filesystem"):30 with runner.isolated_filesystem():31 pass
modified:tests/test_shell_completion.py+18 added-19 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")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")577@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")582584 @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 pass583 @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 pass592594 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"593 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"597598599def test_fish_format_completion_escapes_help():600 fc = FishComplete(Command("x"), {}, "x", "_X_COMPLETE")
17 unmodified lines
modified:tests/test_testing.py+79 added
438 unmodified lines
439 result = runner.invoke(cli, ["-"])440 assert result.output == "<stdin>\nr"441442443@pytest.mark.filterwarnings("ignore:'isolated_filesystem':DeprecationWarning")444def test_isolated_runner(runner):445 with runner.isolated_filesystem() as d:446 assert os.path.exists(d)447448 assert not os.path.exists(d)449450451@pytest.mark.filterwarnings("ignore:'isolated_filesystem':DeprecationWarning")452def test_isolated_runner_custom_tempdir(runner, tmp_path):453 with runner.isolated_filesystem(temp_dir=tmp_path) as d:454 assert os.path.exists(d)455456 assert os.path.exists(d)457 os.rmdir(d)458459460def test_tempdir_replacement_pattern(runner, tmp_path):461 """The replacement for ``isolated_filesystem()``: a temp dir and absolute paths.462463 Rather than changing the working directory, create a directory (here with464 pytest's ``tmp_path``; ``tempfile.TemporaryDirectory`` works the same) and465 pass absolute paths to the command.466 """467468 @click.command()469 @click.argument("path", type=click.Path())470 def write_marker(path):471 with open(path, "w") as f:472 f.write("written")473474 target = tmp_path / "marker.txt"475 result = runner.invoke(write_marker, [str(target)])476477 assert result.exit_code == 0478 assert target.read_text() == "written"479480481def test_tempdir_isolation_is_thread_safe():482 """The recommended replacement is thread-safe, unlike ``isolated_filesystem()``.483484 Each thread owns a ``tempfile.TemporaryDirectory`` and works through485 absolute paths, so there is no ``os.chdir`` and no process-global CWD race486 (the reason ``isolated_filesystem()`` is not thread-safe, issue #3501).487488 ``invoke()`` is deliberately not called concurrently here: it redirects the489 process-global standard streams, so parallel invocations in one process490 corrupt each other regardless of the filesystem. To run commands in491 parallel, use separate processes (like pytest-xdist), not threads.492 """493 import tempfile494 import threading495496 workers = 8497 cwd_before = os.path.realpath(os.getcwd())498 results: list[tuple[str, str, str]] = []499 barrier = threading.Barrier(workers)500 lock = threading.Lock()501502 def worker(index):503 with tempfile.TemporaryDirectory() as d:504 target = os.path.join(d, "data.txt")505 # Release every thread at once to maximize contention.506 barrier.wait(timeout=10)507 with open(target, "w") as f:508 f.write(f"payload-{index}")509 with open(target) as f:510 content = f.read()511 with lock:512 results.append(513 (514 os.path.realpath(d),515 os.path.realpath(os.getcwd()),516 content,517 )518 )519520 threads = [threading.Thread(target=worker, args=(i,)) for i in range(workers)]521 for t in threads:522 t.start()523 for t in threads:524 t.join(timeout=10)525526 assert len(results) == workers527 # Every thread had its own distinct directory.528 assert len({d for d, _, _ in results}) == workers529 # No thread mutated the process-global working directory.530 assert {cwd for _, cwd, _ in results} == {cwd_before}531 # Each thread read back exactly the payload it wrote, with no cross-talk.532 assert sorted(content for _, _, content in results) == sorted(533 f"payload-{i}" for i in range(workers)534 )535536537def test_isolation_stderr_errors():538 """Writing to stderr should escape invalid characters instead of539 raising a UnicodeEncodeError.540 """
300 unmodified lines
modified:CHANGES.md+8 added
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` {pr}`3704`5455## Version 8.4.25657Released 2026-06-24
1561 unmodified lines