Deprecate `isolated_filesystem` and document its limits
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fix #3700 Refs #3501
authored by Kevin Deldycke · committed by Kevin Deldycke · parent 333c28d · Browse files · 9 files·+288 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
9 files+288 added−161 removed
- tests:+208 added−133 removed
- other:+80 added−28 removed
Provenance
- Commit
fbdd434- Tree
98ee57b- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
333c28d
9 files changed+288 added−161 removed
modified:docs/testing.md+45 added-27 removed
5 unmodified lines6 7 Click provides the {ref}`click.testing <testing>` module to help you invoke8 command line applications and check their behavior.9 10-These tools should only be used for testing since they change11-the entire interpreter state for simplicity. They are not thread-safe!10+```{warning}11+These tools should only be used for testing since they change the entire12+interpreter state for simplicity. They are not thread-safe: see13+[Running tests in parallel](#running-tests-in-parallel) for the supported14+way to run CLI tests concurrently.15+```16 17 The examples use [pytest](https://docs.pytest.org/en/stable/) style tests.18 19 ```{contents}102 unmodified lines122 ```123 124 ## File System Isolation125 122-The {meth}`CliRunner.isolated_filesystem` context manager sets the current123-working directory to a new, empty folder.126+To test a command that reads or writes files, give each test its own127+directory and pass absolute paths to the command. Pytest's128+[`tmp_path`](https://docs.pytest.org/en/stable/how-to/tmp_path.html) fixture129+provides a fresh directory per test; {class}`tempfile.TemporaryDirectory`130+works without pytest.131 132 ```{code-block} python133 :caption: cat.py134 10 unmodified lines145 146 from click.testing import CliRunner147 from cat import cat148 142-def test_cat():143- runner = CliRunner()144- with runner.isolated_filesystem():145- with open('hello.txt', 'w') as f:146- f.write('Hello World!')149+def test_cat(tmp_path):150+ hello = tmp_path / 'hello.txt'151+ hello.write_text('Hello World!')152 153+ 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 ```158 153-Pass in a path to control where the temporary directory is created.154-In this case, the directory will not be removed by Click. Its useful155-to integrate with a framework like Pytest that manages temporary files.159+Because the directory is unique to the test and the command receives an160+absolute path, nothing leaks between tests and the working directory is never161+changed.162 157-```{code-block} python158-:caption: test_cat.py163+### Running tests in parallel164 160-from click.testing import CliRunner161-from cat import cat165+Isolating the file system with pytest is thread-safe: each test, or each thread,166+works in its own directory through absolute paths, with no shared state.167 163-def 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 several169+pieces of process-global state into place (like `sys.stdout`, `sys.stderr`,170+`sys.stdin`, etc). Two invocations active at the same time in one interpreter171+overwrite each other's state, so the runner cannot be driven from several172+threads at once.173 169- result = runner.invoke(cat, ['hello.txt'])170- assert result.exit_code == 0171- assert result.output == 'Hello World!\n'174+```{warning}175+Do not parallelize CLI tests with threads. Use process-based isolation176+instead, where each worker has its own interpreter and its own copy of those177+globals. [pytest-xdist](https://pytest-xdist.readthedocs.io/) does this with178+`pytest --numprocesses=auto`.179 ```180 181+Click's own test suite uses exactly this setup: the `tests-random` dependency182+group and the `random` tox environment in183+[`pyproject.toml`](https://github.com/pallets/click/blob/main/pyproject.toml)184+run the suite under `pytest-randomly` and `pytest-xdist` to surface ordering185+bugs and races.186+187+```{deprecated} 8.5.0188+{meth}`CliRunner.isolated_filesystem` is deprecated and will be removed in189+Click 9.0. Use a temporary directory with absolute paths, as shown above.190+```191+192 ## Input Streams193 194 The test wrapper can provide input data for the input stream (stdin). This is195 very useful for testing prompts.88 unmodified linesmodified:docs/upgrade-guides.md+1 added-1 removed
11 unmodified lines1213141516161718192014 unmodified lines11 unmodified lines
### Deprecations
For each deprecation, provide a brief explanation, and direct users to new function / class if available.- TBD- `CliRunner.isolated_filesystem()` is deprecated and will be removed in Click 9.0. The helper predates Python 3 and modern pytest, and it relies on `os.chdir`, which mutates process-global state and is therefore not thread-safe. Replace it with a temporary directory (`tempfile.TemporaryDirectory`, or pytest's `tmp_path` fixture) and pass absolute paths to the command instead of relying on the current working directory. To run commands in parallel, use process-based isolation (such as `pytest-xdist`) rather than threads, since `CliRunner.invoke()` also redirects the process-global standard streams and other interpreter-wide state. See [#3700](https://github.com/pallets/click/issues/3700), [#3501](https://github.com/pallets/click/issues/3501) and the [testing guide](testing.md#running-tests-in-parallel).
### Removals with prior deprecation
For each removal, provide a brief explanation, and direct users to new function / class if available. If possible, deprecate and remove in 10.0.0, rather than removing outright.14 unmodified linesmodified:src/click/testing.py+26 added
745 unmodified lines746 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.749 750+ .. 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`.760+761 :param temp_dir: Create the temporary directory under this762 directory. If given, the created directory is not removed763 when exiting.764 765+ .. 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.769+770 .. versionchanged:: 8.0771 Added the ``temp_dir`` parameter.772 """773+ import warnings774+775+ 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+ )782+783 cwd = os.getcwd()784 dt = tempfile.mkdtemp(dir=temp_dir)785 os.chdir(dt)786 12 unmodified linesmodified:tests/test_utils/test_open_file.py+50 added-55 removed
6 unmodified lines7 import click8 from click._compat import WIN9 10 11-def test_open_file(runner):11+def 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())17 18 click.echo("meep")19 20- 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")22 24- 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"26 28- 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"30 31 32 def test_open_file_pathlib_dash(runner):33 @click.command()21 unmodified lines55 result = runner.invoke(cli, ["-"], input=os.urandom(16))56 assert result.exception is None57 58 60-def test_open_file_respects_ignore(runner):61- with runner.isolated_filesystem():62- with open("test.txt", "w") as f:63- f.write("Hello world!")59+def test_open_file_respects_ignore(tmp_path):60+ path = tmp_path / "test.txt"61+ path.write_text("Hello world!")62 65- 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"65 66 69-def 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")67+def test_open_file_ignore_invalid_utf8(tmp_path):68+ path = tmp_path / "test.txt"69+ path.write_bytes(b"\xe2\x28\xa1")70 74- 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()73 74 78-def 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))75+def test_open_file_ignore_no_encoding(tmp_path):76+ path = tmp_path / "test.bin"77+ path.write_bytes(os.urandom(16))78 83- 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()81 82 83 @pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")84 @pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])89-def 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)85+def 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)89 95- @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()94 100- 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) == permissions98 99 100 @pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")106-def test_open_file_atomic_permissions_new_file(runner):107- with runner.isolated_filesystem():101+def 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()106 109- @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)113 114- # 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)119-120- 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) == permissionsmodified:tests/test_arguments.py+16 added-19 removed
100 unmodified lines101 catch_exceptions=False,102 )103 104 105-def test_file_args(runner):105+def 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 lines112 if not chunk:113 break114 output.write(chunk)115 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!"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!"121 123- 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 == 0125 126 127 def test_path_allow_dash(runner):128 @click.command()5 unmodified lines134 assert result.output == "-\n"135 assert result.exit_code == 0136 137 139-def test_file_atomics(runner):138+def 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 line144 with open(output.name, "rb") as f:145 old_content = f.read()146 assert old_content == b"OLD\n"147 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"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"154 155 156 def test_stdout_default(runner):157 @click.command()583 unmodified linesmodified:tests/test_basic.py+38 added-40 removed
413 unmodified lines414 result = runner.invoke(cli, args)415 assert result.output == repr(expected)416 417 418-def test_file_option(runner):418+def 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 lines425 @click.option("--file", type=click.File("r"))426 def output(file):427 click.echo(file.read())428 429- 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}"])432 433 assert not result_in.exception434 assert result_in.output == ""435 assert not result_out.exception436 assert result_out.output == "Hello World!\n\n"437 438 439-def test_file_lazy_mode(runner):439+def test_file_lazy_mode(runner, tmp_path):440 do_io = False441 442 @click.command()443 @click.option("--file", type=click.File("w"))5 unmodified lines449 @click.option("--file", type=click.File("r"))450 def output(file):451 pass452 453- with runner.isolated_filesystem():454- os.mkdir("example.txt")453+ example = tmp_path / "example.txt"454+ example.mkdir()455 456- 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 == 1459 460- 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 == 0463 464- 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.exception466 467 @click.command()468 @click.option("--file", type=click.File("w", lazy=False))469 def input_non_lazy(file):470 file.write("Hello World!\n")471 472- 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.output477 478 479-def test_path_option(runner):479+def 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")485 486- with runner.isolated_filesystem():487- os.mkdir("test")486+ test_dir = tmp_path / "test"487+ test_dir.mkdir()488 489- 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.exception491 492- 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"494 495- 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.output497 498 @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)}")503 504- 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.output506 508- 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.output510 511 @click.command()512 @click.option("-f", type=click.Path())513 def exists(f):514 click.echo(f"exists={os.path.exists(f)}")515 517- 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.output518 521- 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.output521 522 523 def test_choice_option(runner):524 @click.command()438 unmodified linesmodified:tests/test_shell_completion.py+18 added-19 removed
572 unmodified lines573 assert click.shell_completion._available_shells["mysh"] is MyshComplete574 575 576 # Don't make the ResourceWarning give an error577-@pytest.mark.filterwarnings("default")578-def 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")578+def 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")582 584- @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+ pass592 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"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"597 598 599 def test_fish_format_completion_escapes_help():600 fc = FishComplete(Command("x"), {}, "x", "_X_COMPLETE")17 unmodified linesmodified:tests/test_testing.py+86 added
438 unmodified lines439 result = runner.invoke(cli, ["-"])440 assert result.output == "<stdin>\nr"441 442 443+@pytest.mark.filterwarnings("ignore:'isolated_filesystem':DeprecationWarning")444 def test_isolated_runner(runner):445 with runner.isolated_filesystem() as d:446 assert os.path.exists(d)447 448 assert not os.path.exists(d)449 450 451+@pytest.mark.filterwarnings("ignore:'isolated_filesystem':DeprecationWarning")452 def 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)455 456 assert os.path.exists(d)457 os.rmdir(d)458 459 460+def 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+ pass465+466+467+def test_tempdir_replacement_pattern(runner, tmp_path):468+ """The replacement for ``isolated_filesystem()``: a temp dir and absolute paths.469+470+ 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+ """474+475+ @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")480+481+ target = tmp_path / "marker.txt"482+ result = runner.invoke(write_marker, [str(target)])483+484+ assert result.exit_code == 0485+ assert target.read_text() == "written"486+487+488+def test_tempdir_isolation_is_thread_safe():489+ """The recommended replacement is thread-safe, unlike ``isolated_filesystem()``.490+491+ 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).494+495+ ``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 threading502+503+ 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()508+509+ 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+ )526+527+ 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)532+533+ 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+ )542+543+544 def test_isolation_stderr_errors():545 """Writing to stderr should escape invalid characters instead of546 raising a UnicodeEncodeError.547 """300 unmodified linesmodified:CHANGES.md+8 added
41 unmodified lines42 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`54 55 ## Version 8.4.256 57 Released 2026-06-241561 unmodified lines