+ @event_loop()
+ @patch("black.ProcessPoolExecutor", MagicMock(side_effect=OSError))
+ def test_works_in_mono_process_only_environment(self) -> None:
+ with cache_dir() as workspace:
+ for f in [
+ (workspace / "one.py").resolve(),
+ (workspace / "two.py").resolve(),
+ ]:
+ f.write_text('print("hello")\n')
+ self.invokeBlack([str(workspace)])
+
+ @event_loop()
+ def test_check_diff_use_together(self) -> None:
+ with cache_dir():
+ # Files which will be reformatted.
+ src1 = (THIS_DIR / "data" / "string_quotes.py").resolve()
+ self.invokeBlack([str(src1), "--diff", "--check"], exit_code=1)
+ # Files which will not be reformatted.
+ src2 = (THIS_DIR / "data" / "composition.py").resolve()
+ self.invokeBlack([str(src2), "--diff", "--check"])
+ # Multi file command.
+ self.invokeBlack([str(src1), str(src2), "--diff", "--check"], exit_code=1)
+
+ def test_no_src_fails(self) -> None:
+ with cache_dir():
+ self.invokeBlack([], exit_code=1)
+
+ def test_src_and_code_fails(self) -> None:
+ with cache_dir():
+ self.invokeBlack([".", "-c", "0"], exit_code=1)
+
+ def test_broken_symlink(self) -> None:
+ with cache_dir() as workspace:
+ symlink = workspace / "broken_link.py"
+ try:
+ symlink.symlink_to("nonexistent.py")
+ except (OSError, NotImplementedError) as e:
+ self.skipTest(f"Can't create symlinks: {e}")
+ self.invokeBlack([str(workspace.resolve())])
+
+ def test_single_file_force_pyi(self) -> None:
+ pyi_mode = replace(DEFAULT_MODE, is_pyi=True)
+ contents, expected = read_data("force_pyi")
+ with cache_dir() as workspace:
+ path = (workspace / "file.py").resolve()
+ with open(path, "w") as fh:
+ fh.write(contents)
+ self.invokeBlack([str(path), "--pyi"])
+ with open(path, "r") as fh:
+ actual = fh.read()
+ # verify cache with --pyi is separate
+ pyi_cache = black.read_cache(pyi_mode)
+ self.assertIn(str(path), pyi_cache)
+ normal_cache = black.read_cache(DEFAULT_MODE)
+ self.assertNotIn(str(path), normal_cache)
+ self.assertFormatEqual(expected, actual)
+ black.assert_equivalent(contents, actual)
+ black.assert_stable(contents, actual, pyi_mode)
+
+ @event_loop()
+ def test_multi_file_force_pyi(self) -> None:
+ reg_mode = DEFAULT_MODE
+ pyi_mode = replace(DEFAULT_MODE, is_pyi=True)
+ contents, expected = read_data("force_pyi")
+ with cache_dir() as workspace:
+ paths = [
+ (workspace / "file1.py").resolve(),
+ (workspace / "file2.py").resolve(),
+ ]
+ for path in paths:
+ with open(path, "w") as fh:
+ fh.write(contents)
+ self.invokeBlack([str(p) for p in paths] + ["--pyi"])
+ for path in paths:
+ with open(path, "r") as fh:
+ actual = fh.read()
+ self.assertEqual(actual, expected)
+ # verify cache with --pyi is separate
+ pyi_cache = black.read_cache(pyi_mode)
+ normal_cache = black.read_cache(reg_mode)
+ for path in paths:
+ self.assertIn(str(path), pyi_cache)
+ self.assertNotIn(str(path), normal_cache)
+
+ def test_pipe_force_pyi(self) -> None:
+ source, expected = read_data("force_pyi")
+ result = CliRunner().invoke(
+ black.main, ["-", "-q", "--pyi"], input=BytesIO(source.encode("utf8"))
+ )
+ self.assertEqual(result.exit_code, 0)
+ actual = result.output
+ self.assertFormatEqual(actual, expected)
+
+ def test_single_file_force_py36(self) -> None:
+ reg_mode = DEFAULT_MODE
+ py36_mode = replace(DEFAULT_MODE, target_versions=PY36_VERSIONS)
+ source, expected = read_data("force_py36")
+ with cache_dir() as workspace:
+ path = (workspace / "file.py").resolve()
+ with open(path, "w") as fh:
+ fh.write(source)
+ self.invokeBlack([str(path), *PY36_ARGS])
+ with open(path, "r") as fh:
+ actual = fh.read()
+ # verify cache with --target-version is separate
+ py36_cache = black.read_cache(py36_mode)
+ self.assertIn(str(path), py36_cache)
+ normal_cache = black.read_cache(reg_mode)
+ self.assertNotIn(str(path), normal_cache)
+ self.assertEqual(actual, expected)
+
+ @event_loop()
+ def test_multi_file_force_py36(self) -> None:
+ reg_mode = DEFAULT_MODE
+ py36_mode = replace(DEFAULT_MODE, target_versions=PY36_VERSIONS)
+ source, expected = read_data("force_py36")
+ with cache_dir() as workspace:
+ paths = [
+ (workspace / "file1.py").resolve(),
+ (workspace / "file2.py").resolve(),
+ ]
+ for path in paths:
+ with open(path, "w") as fh:
+ fh.write(source)
+ self.invokeBlack([str(p) for p in paths] + PY36_ARGS)
+ for path in paths:
+ with open(path, "r") as fh:
+ actual = fh.read()
+ self.assertEqual(actual, expected)
+ # verify cache with --target-version is separate
+ pyi_cache = black.read_cache(py36_mode)
+ normal_cache = black.read_cache(reg_mode)
+ for path in paths:
+ self.assertIn(str(path), pyi_cache)
+ self.assertNotIn(str(path), normal_cache)
+
+ def test_pipe_force_py36(self) -> None:
+ source, expected = read_data("force_py36")
+ result = CliRunner().invoke(
+ black.main,
+ ["-", "-q", "--target-version=py36"],
+ input=BytesIO(source.encode("utf8")),
+ )
+ self.assertEqual(result.exit_code, 0)
+ actual = result.output
+ self.assertFormatEqual(actual, expected)
+
+ @pytest.mark.incompatible_with_mypyc
+ def test_reformat_one_with_stdin(self) -> None:
+ with patch(
+ "black.format_stdin_to_stdout",
+ return_value=lambda *args, **kwargs: black.Changed.YES,
+ ) as fsts:
+ report = MagicMock()
+ path = Path("-")
+ black.reformat_one(
+ path,
+ fast=True,
+ write_back=black.WriteBack.YES,
+ mode=DEFAULT_MODE,
+ report=report,
+ )
+ fsts.assert_called_once()
+ report.done.assert_called_with(path, black.Changed.YES)
+
+ @pytest.mark.incompatible_with_mypyc
+ def test_reformat_one_with_stdin_filename(self) -> None:
+ with patch(
+ "black.format_stdin_to_stdout",
+ return_value=lambda *args, **kwargs: black.Changed.YES,
+ ) as fsts:
+ report = MagicMock()
+ p = "foo.py"
+ path = Path(f"__BLACK_STDIN_FILENAME__{p}")
+ expected = Path(p)
+ black.reformat_one(
+ path,
+ fast=True,
+ write_back=black.WriteBack.YES,
+ mode=DEFAULT_MODE,
+ report=report,
+ )
+ fsts.assert_called_once_with(
+ fast=True, write_back=black.WriteBack.YES, mode=DEFAULT_MODE
+ )
+ # __BLACK_STDIN_FILENAME__ should have been stripped
+ report.done.assert_called_with(expected, black.Changed.YES)
+
+ @pytest.mark.incompatible_with_mypyc
+ def test_reformat_one_with_stdin_filename_pyi(self) -> None:
+ with patch(
+ "black.format_stdin_to_stdout",
+ return_value=lambda *args, **kwargs: black.Changed.YES,
+ ) as fsts:
+ report = MagicMock()
+ p = "foo.pyi"
+ path = Path(f"__BLACK_STDIN_FILENAME__{p}")
+ expected = Path(p)
+ black.reformat_one(
+ path,
+ fast=True,
+ write_back=black.WriteBack.YES,
+ mode=DEFAULT_MODE,
+ report=report,
+ )
+ fsts.assert_called_once_with(
+ fast=True,
+ write_back=black.WriteBack.YES,
+ mode=replace(DEFAULT_MODE, is_pyi=True),
+ )
+ # __BLACK_STDIN_FILENAME__ should have been stripped
+ report.done.assert_called_with(expected, black.Changed.YES)
+
+ @pytest.mark.incompatible_with_mypyc
+ def test_reformat_one_with_stdin_filename_ipynb(self) -> None:
+ with patch(
+ "black.format_stdin_to_stdout",
+ return_value=lambda *args, **kwargs: black.Changed.YES,
+ ) as fsts:
+ report = MagicMock()
+ p = "foo.ipynb"
+ path = Path(f"__BLACK_STDIN_FILENAME__{p}")
+ expected = Path(p)
+ black.reformat_one(
+ path,
+ fast=True,
+ write_back=black.WriteBack.YES,
+ mode=DEFAULT_MODE,
+ report=report,
+ )
+ fsts.assert_called_once_with(
+ fast=True,
+ write_back=black.WriteBack.YES,
+ mode=replace(DEFAULT_MODE, is_ipynb=True),
+ )
+ # __BLACK_STDIN_FILENAME__ should have been stripped
+ report.done.assert_called_with(expected, black.Changed.YES)
+
+ @pytest.mark.incompatible_with_mypyc
+ def test_reformat_one_with_stdin_and_existing_path(self) -> None:
+ with patch(
+ "black.format_stdin_to_stdout",
+ return_value=lambda *args, **kwargs: black.Changed.YES,
+ ) as fsts:
+ report = MagicMock()
+ # Even with an existing file, since we are forcing stdin, black
+ # should output to stdout and not modify the file inplace
+ p = Path(str(THIS_DIR / "data/collections.py"))
+ # Make sure is_file actually returns True
+ self.assertTrue(p.is_file())
+ path = Path(f"__BLACK_STDIN_FILENAME__{p}")
+ expected = Path(p)
+ black.reformat_one(
+ path,
+ fast=True,
+ write_back=black.WriteBack.YES,
+ mode=DEFAULT_MODE,
+ report=report,
+ )
+ fsts.assert_called_once()
+ # __BLACK_STDIN_FILENAME__ should have been stripped
+ report.done.assert_called_with(expected, black.Changed.YES)
+
+ def test_reformat_one_with_stdin_empty(self) -> None:
+ output = io.StringIO()
+ with patch("io.TextIOWrapper", lambda *args, **kwargs: output):
+ try:
+ black.format_stdin_to_stdout(
+ fast=True,
+ content="",
+ write_back=black.WriteBack.YES,
+ mode=DEFAULT_MODE,
+ )
+ except io.UnsupportedOperation:
+ pass # StringIO does not support detach
+ assert output.getvalue() == ""
+
+ def test_invalid_cli_regex(self) -> None:
+ for option in ["--include", "--exclude", "--extend-exclude", "--force-exclude"]:
+ self.invokeBlack(["-", option, "**()(!!*)"], exit_code=2)
+
+ def test_required_version_matches_version(self) -> None:
+ self.invokeBlack(
+ ["--required-version", black.__version__, "-c", "0"],
+ exit_code=0,
+ ignore_config=True,
+ )
+
+ def test_required_version_matches_partial_version(self) -> None:
+ self.invokeBlack(
+ ["--required-version", black.__version__.split(".")[0], "-c", "0"],
+ exit_code=0,
+ ignore_config=True,
+ )
+
+ def test_required_version_does_not_match_on_minor_version(self) -> None:
+ self.invokeBlack(
+ ["--required-version", black.__version__.split(".")[0] + ".999", "-c", "0"],
+ exit_code=1,
+ ignore_config=True,
+ )
+
+ def test_required_version_does_not_match_version(self) -> None:
+ result = BlackRunner().invoke(
+ black.main,
+ ["--required-version", "20.99b", "-c", "0"],
+ )
+ self.assertEqual(result.exit_code, 1)
+ self.assertIn("required version", result.stderr)
+
+ def test_preserves_line_endings(self) -> None:
+ with TemporaryDirectory() as workspace:
+ test_file = Path(workspace) / "test.py"
+ for nl in ["\n", "\r\n"]:
+ contents = nl.join(["def f( ):", " pass"])
+ test_file.write_bytes(contents.encode())
+ ff(test_file, write_back=black.WriteBack.YES)
+ updated_contents: bytes = test_file.read_bytes()
+ self.assertIn(nl.encode(), updated_contents)
+ if nl == "\n":
+ self.assertNotIn(b"\r\n", updated_contents)
+
+ def test_preserves_line_endings_via_stdin(self) -> None:
+ for nl in ["\n", "\r\n"]:
+ contents = nl.join(["def f( ):", " pass"])
+ runner = BlackRunner()
+ result = runner.invoke(
+ black.main, ["-", "--fast"], input=BytesIO(contents.encode("utf8"))
+ )
+ self.assertEqual(result.exit_code, 0)
+ output = result.stdout_bytes
+ self.assertIn(nl.encode("utf8"), output)
+ if nl == "\n":
+ self.assertNotIn(b"\r\n", output)
+
+ def test_assert_equivalent_different_asts(self) -> None:
+ with self.assertRaises(AssertionError):
+ black.assert_equivalent("{}", "None")
+
+ def test_shhh_click(self) -> None:
+ try:
+ from click import _unicodefun
+ except ModuleNotFoundError:
+ self.skipTest("Incompatible Click version")
+ if not hasattr(_unicodefun, "_verify_python3_env"):
+ self.skipTest("Incompatible Click version")
+ # First, let's see if Click is crashing with a preferred ASCII charset.
+ with patch("locale.getpreferredencoding") as gpe:
+ gpe.return_value = "ASCII"
+ with self.assertRaises(RuntimeError):
+ _unicodefun._verify_python3_env() # type: ignore
+ # Now, let's silence Click...
+ black.patch_click()
+ # ...and confirm it's silent.
+ with patch("locale.getpreferredencoding") as gpe:
+ gpe.return_value = "ASCII"
+ try:
+ _unicodefun._verify_python3_env() # type: ignore
+ except RuntimeError as re:
+ self.fail(f"`patch_click()` failed, exception still raised: {re}")
+
+ def test_root_logger_not_used_directly(self) -> None:
+ def fail(*args: Any, **kwargs: Any) -> None:
+ self.fail("Record created with root logger")
+
+ with patch.multiple(
+ logging.root,
+ debug=fail,
+ info=fail,
+ warning=fail,
+ error=fail,
+ critical=fail,
+ log=fail,
+ ):
+ ff(THIS_DIR / "util.py")
+
+ def test_invalid_config_return_code(self) -> None:
+ tmp_file = Path(black.dump_to_file())
+ try:
+ tmp_config = Path(black.dump_to_file())
+ tmp_config.unlink()
+ args = ["--config", str(tmp_config), str(tmp_file)]
+ self.invokeBlack(args, exit_code=2, ignore_config=False)
+ finally:
+ tmp_file.unlink()
+
+ def test_parse_pyproject_toml(self) -> None:
+ test_toml_file = THIS_DIR / "test.toml"
+ config = black.parse_pyproject_toml(str(test_toml_file))
+ self.assertEqual(config["verbose"], 1)
+ self.assertEqual(config["check"], "no")
+ self.assertEqual(config["diff"], "y")
+ self.assertEqual(config["color"], True)
+ self.assertEqual(config["line_length"], 79)
+ self.assertEqual(config["target_version"], ["py36", "py37", "py38"])
+ self.assertEqual(config["python_cell_magics"], ["custom1", "custom2"])
+ self.assertEqual(config["exclude"], r"\.pyi?$")
+ self.assertEqual(config["include"], r"\.py?$")
+
+ def test_read_pyproject_toml(self) -> None:
+ test_toml_file = THIS_DIR / "test.toml"
+ fake_ctx = FakeContext()
+ black.read_pyproject_toml(fake_ctx, FakeParameter(), str(test_toml_file))
+ config = fake_ctx.default_map
+ self.assertEqual(config["verbose"], "1")
+ self.assertEqual(config["check"], "no")
+ self.assertEqual(config["diff"], "y")
+ self.assertEqual(config["color"], "True")
+ self.assertEqual(config["line_length"], "79")
+ self.assertEqual(config["target_version"], ["py36", "py37", "py38"])
+ self.assertEqual(config["exclude"], r"\.pyi?$")
+ self.assertEqual(config["include"], r"\.py?$")
+
+ @pytest.mark.incompatible_with_mypyc
+ def test_find_project_root(self) -> None:
+ with TemporaryDirectory() as workspace:
+ root = Path(workspace)
+ test_dir = root / "test"
+ test_dir.mkdir()
+
+ src_dir = root / "src"
+ src_dir.mkdir()
+
+ root_pyproject = root / "pyproject.toml"
+ root_pyproject.touch()
+ src_pyproject = src_dir / "pyproject.toml"
+ src_pyproject.touch()
+ src_python = src_dir / "foo.py"
+ src_python.touch()
+
+ self.assertEqual(
+ black.find_project_root((src_dir, test_dir)),
+ (root.resolve(), "pyproject.toml"),
+ )
+ self.assertEqual(
+ black.find_project_root((src_dir,)),
+ (src_dir.resolve(), "pyproject.toml"),
+ )
+ self.assertEqual(
+ black.find_project_root((src_python,)),
+ (src_dir.resolve(), "pyproject.toml"),
+ )
+
+ @patch(
+ "black.files.find_user_pyproject_toml",
+ )
+ def test_find_pyproject_toml(self, find_user_pyproject_toml: MagicMock) -> None:
+ find_user_pyproject_toml.side_effect = RuntimeError()
+
+ with redirect_stderr(io.StringIO()) as stderr:
+ result = black.files.find_pyproject_toml(
+ path_search_start=(str(Path.cwd().root),)
+ )
+
+ assert result is None
+ err = stderr.getvalue()
+ assert "Ignoring user configuration" in err
+
+ @patch(
+ "black.files.find_user_pyproject_toml",
+ black.files.find_user_pyproject_toml.__wrapped__,
+ )
+ def test_find_user_pyproject_toml_linux(self) -> None:
+ if system() == "Windows":
+ return
+
+ # Test if XDG_CONFIG_HOME is checked
+ with TemporaryDirectory() as workspace:
+ tmp_user_config = Path(workspace) / "black"
+ with patch.dict("os.environ", {"XDG_CONFIG_HOME": workspace}):
+ self.assertEqual(
+ black.files.find_user_pyproject_toml(), tmp_user_config.resolve()
+ )
+
+ # Test fallback for XDG_CONFIG_HOME
+ with patch.dict("os.environ"):
+ os.environ.pop("XDG_CONFIG_HOME", None)
+ fallback_user_config = Path("~/.config").expanduser() / "black"
+ self.assertEqual(
+ black.files.find_user_pyproject_toml(), fallback_user_config.resolve()
+ )
+
+ def test_find_user_pyproject_toml_windows(self) -> None:
+ if system() != "Windows":
+ return
+
+ user_config_path = Path.home() / ".black"
+ self.assertEqual(
+ black.files.find_user_pyproject_toml(), user_config_path.resolve()
+ )
+
+ def test_bpo_33660_workaround(self) -> None:
+ if system() == "Windows":
+ return
+
+ # https://bugs.python.org/issue33660
+ root = Path("/")
+ with change_directory(root):
+ path = Path("workspace") / "project"
+ report = black.Report(verbose=True)
+ normalized_path = black.normalize_path_maybe_ignore(path, root, report)
+ self.assertEqual(normalized_path, "workspace/project")
+
+ def test_newline_comment_interaction(self) -> None:
+ source = "class A:\\\r\n# type: ignore\n pass\n"
+ output = black.format_str(source, mode=DEFAULT_MODE)
+ black.assert_stable(source, output, mode=DEFAULT_MODE)
+
+ def test_bpo_2142_workaround(self) -> None:
+
+ # https://bugs.python.org/issue2142
+
+ source, _ = read_data("missing_final_newline.py")
+ # read_data adds a trailing newline
+ source = source.rstrip()
+ expected, _ = read_data("missing_final_newline.diff")
+ tmp_file = Path(black.dump_to_file(source, ensure_final_newline=False))
+ diff_header = re.compile(
+ rf"{re.escape(str(tmp_file))}\t\d\d\d\d-\d\d-\d\d "
+ r"\d\d:\d\d:\d\d\.\d\d\d\d\d\d \+\d\d\d\d"
+ )
+ try:
+ result = BlackRunner().invoke(black.main, ["--diff", str(tmp_file)])
+ self.assertEqual(result.exit_code, 0)
+ finally:
+ os.unlink(tmp_file)
+ actual = result.output
+ actual = diff_header.sub(DETERMINISTIC_HEADER, actual)
+ self.assertEqual(actual, expected)
+
+ @staticmethod
+ def compare_results(
+ result: click.testing.Result, expected_value: str, expected_exit_code: int
+ ) -> None:
+ """Helper method to test the value and exit code of a click Result."""
+ assert (
+ result.output == expected_value
+ ), "The output did not match the expected value."
+ assert result.exit_code == expected_exit_code, "The exit code is incorrect."
+
+ def test_code_option(self) -> None:
+ """Test the code option with no changes."""
+ code = 'print("Hello world")\n'
+ args = ["--code", code]
+ result = CliRunner().invoke(black.main, args)
+
+ self.compare_results(result, code, 0)
+
+ def test_code_option_changed(self) -> None:
+ """Test the code option when changes are required."""
+ code = "print('hello world')"
+ formatted = black.format_str(code, mode=DEFAULT_MODE)
+
+ args = ["--code", code]
+ result = CliRunner().invoke(black.main, args)
+
+ self.compare_results(result, formatted, 0)
+
+ def test_code_option_check(self) -> None:
+ """Test the code option when check is passed."""
+ args = ["--check", "--code", 'print("Hello world")\n']
+ result = CliRunner().invoke(black.main, args)
+ self.compare_results(result, "", 0)
+
+ def test_code_option_check_changed(self) -> None:
+ """Test the code option when changes are required, and check is passed."""
+ args = ["--check", "--code", "print('hello world')"]
+ result = CliRunner().invoke(black.main, args)
+ self.compare_results(result, "", 1)
+
+ def test_code_option_diff(self) -> None:
+ """Test the code option when diff is passed."""
+ code = "print('hello world')"
+ formatted = black.format_str(code, mode=DEFAULT_MODE)
+ result_diff = diff(code, formatted, "STDIN", "STDOUT")
+
+ args = ["--diff", "--code", code]
+ result = CliRunner().invoke(black.main, args)
+
+ # Remove time from diff
+ output = DIFF_TIME.sub("", result.output)
+
+ assert output == result_diff, "The output did not match the expected value."
+ assert result.exit_code == 0, "The exit code is incorrect."
+
+ def test_code_option_color_diff(self) -> None:
+ """Test the code option when color and diff are passed."""
+ code = "print('hello world')"
+ formatted = black.format_str(code, mode=DEFAULT_MODE)
+
+ result_diff = diff(code, formatted, "STDIN", "STDOUT")
+ result_diff = color_diff(result_diff)
+
+ args = ["--diff", "--color", "--code", code]
+ result = CliRunner().invoke(black.main, args)
+
+ # Remove time from diff
+ output = DIFF_TIME.sub("", result.output)
+
+ assert output == result_diff, "The output did not match the expected value."
+ assert result.exit_code == 0, "The exit code is incorrect."
+
+ @pytest.mark.incompatible_with_mypyc
+ def test_code_option_safe(self) -> None:
+ """Test that the code option throws an error when the sanity checks fail."""
+ # Patch black.assert_equivalent to ensure the sanity checks fail
+ with patch.object(black, "assert_equivalent", side_effect=AssertionError):
+ code = 'print("Hello world")'
+ error_msg = f"{code}\nerror: cannot format <string>: \n"
+
+ args = ["--safe", "--code", code]
+ result = CliRunner().invoke(black.main, args)
+
+ self.compare_results(result, error_msg, 123)
+
+ def test_code_option_fast(self) -> None:
+ """Test that the code option ignores errors when the sanity checks fail."""
+ # Patch black.assert_equivalent to ensure the sanity checks fail
+ with patch.object(black, "assert_equivalent", side_effect=AssertionError):
+ code = 'print("Hello world")'
+ formatted = black.format_str(code, mode=DEFAULT_MODE)
+
+ args = ["--fast", "--code", code]
+ result = CliRunner().invoke(black.main, args)
+
+ self.compare_results(result, formatted, 0)
+
+ @pytest.mark.incompatible_with_mypyc
+ def test_code_option_config(self) -> None:
+ """
+ Test that the code option finds the pyproject.toml in the current directory.
+ """
+ with patch.object(black, "parse_pyproject_toml", return_value={}) as parse:
+ args = ["--code", "print"]
+ # This is the only directory known to contain a pyproject.toml
+ with change_directory(PROJECT_ROOT):
+ CliRunner().invoke(black.main, args)
+ pyproject_path = Path(Path.cwd(), "pyproject.toml").resolve()
+
+ assert (
+ len(parse.mock_calls) >= 1
+ ), "Expected config parse to be called with the current directory."
+
+ _, call_args, _ = parse.mock_calls[0]
+ assert (
+ call_args[0].lower() == str(pyproject_path).lower()
+ ), "Incorrect config loaded."
+
+ @pytest.mark.incompatible_with_mypyc
+ def test_code_option_parent_config(self) -> None:
+ """
+ Test that the code option finds the pyproject.toml in the parent directory.
+ """
+ with patch.object(black, "parse_pyproject_toml", return_value={}) as parse:
+ with change_directory(THIS_DIR):
+ args = ["--code", "print"]
+ CliRunner().invoke(black.main, args)
+
+ pyproject_path = Path(Path().cwd().parent, "pyproject.toml").resolve()
+ assert (
+ len(parse.mock_calls) >= 1
+ ), "Expected config parse to be called with the current directory."
+
+ _, call_args, _ = parse.mock_calls[0]
+ assert (
+ call_args[0].lower() == str(pyproject_path).lower()
+ ), "Incorrect config loaded."
+
+ def test_for_handled_unexpected_eof_error(self) -> None:
+ """
+ Test that an unexpected EOF SyntaxError is nicely presented.
+ """
+ with pytest.raises(black.parsing.InvalidInput) as exc_info:
+ black.lib2to3_parse("print(", {})
+
+ exc_info.match("Cannot parse: 2:0: EOF in multi-line statement")
+
+ def test_equivalency_ast_parse_failure_includes_error(self) -> None:
+ with pytest.raises(AssertionError) as err:
+ black.assert_equivalent("a«»a = 1", "a«»a = 1")
+
+ err.match("--safe")
+ # Unfortunately the SyntaxError message has changed in newer versions so we
+ # can't match it directly.
+ err.match("invalid character")
+ err.match(r"\(<unknown>, line 1\)")
+
+
+class TestCaching:
+ def test_get_cache_dir(
+ self,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ # Create multiple cache directories
+ workspace1 = tmp_path / "ws1"
+ workspace1.mkdir()
+ workspace2 = tmp_path / "ws2"
+ workspace2.mkdir()
+
+ # Force user_cache_dir to use the temporary directory for easier assertions
+ patch_user_cache_dir = patch(
+ target="black.cache.user_cache_dir",
+ autospec=True,
+ return_value=str(workspace1),
+ )
+
+ # If BLACK_CACHE_DIR is not set, use user_cache_dir
+ monkeypatch.delenv("BLACK_CACHE_DIR", raising=False)
+ with patch_user_cache_dir:
+ assert get_cache_dir() == workspace1
+
+ # If it is set, use the path provided in the env var.
+ monkeypatch.setenv("BLACK_CACHE_DIR", str(workspace2))
+ assert get_cache_dir() == workspace2
+