+ def test_shhh_click(self) -> None:
+ try:
+ from click import _unicodefun # type: ignore
+ 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()
+ # 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()
+ 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_FILE)
+
+ 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["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?$")
+
+ 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()
+ )
+ self.assertEqual(black.find_project_root((src_dir,)), src_dir.resolve())
+ self.assertEqual(black.find_project_root((src_python,)), src_dir.resolve())
+
+ @patch("black.find_user_pyproject_toml", black.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.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.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.find_user_pyproject_toml(), user_config_path.resolve())
+
+ def test_bpo_33660_workaround(self) -> None:
+ if system() == "Windows":
+ return
+
+ # https://bugs.python.org/issue33660
+
+ old_cwd = Path.cwd()
+ try:
+ root = Path("/")
+ os.chdir(str(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")
+ finally:
+ os.chdir(str(old_cwd))
+
+ 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)
+
+ @pytest.mark.python2
+ def test_docstring_reformat_for_py27(self) -> None:
+ """
+ Check that stripping trailing whitespace from Python 2 docstrings
+ doesn't trigger a "not equivalent to source" error
+ """
+ source = (
+ b'def foo():\r\n """Testing\r\n Testing """\r\n print "Foo"\r\n'
+ )
+ expected = 'def foo():\n """Testing\n Testing"""\n print "Foo"\n'
+
+ result = CliRunner().invoke(
+ black.main,
+ ["-", "-q", "--target-version=py27"],
+ input=BytesIO(source),
+ )
+
+ self.assertEqual(result.exit_code, 0)
+ actual = result.output
+ self.assertFormatEqual(actual, expected)
+
+
+with open(black.__file__, "r", encoding="utf-8") as _bf:
+ black_source_lines = _bf.readlines()
+
+
+def tracefunc(frame: types.FrameType, event: str, arg: Any) -> Callable:
+ """Show function calls `from black/__init__.py` as they happen.
+
+ Register this with `sys.settrace()` in a test you're debugging.
+ """
+ if event != "call":
+ return tracefunc
+
+ stack = len(inspect.stack()) - 19
+ stack *= 2
+ filename = frame.f_code.co_filename
+ lineno = frame.f_lineno
+ func_sig_lineno = lineno - 1
+ funcname = black_source_lines[func_sig_lineno].strip()
+ while funcname.startswith("@"):
+ func_sig_lineno += 1
+ funcname = black_source_lines[func_sig_lineno].strip()
+ if "black/__init__.py" in filename:
+ print(f"{' ' * stack}{lineno}:{funcname}")
+ return tracefunc
+