+ 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_files(self) -> None:
+ with cache_dir():
+ # Without an argument, black exits with error code 0.
+ self.invokeBlack([])
+
+ def test_broken_symlink(self) -> None:
+ with cache_dir() as workspace:
+ symlink = workspace / "broken_link.py"
+ try:
+ symlink.symlink_to("nonexistent.py")
+ except OSError as e:
+ self.skipTest(f"Can't create symlinks: {e}")
+ self.invokeBlack([str(workspace.resolve())])
+
+ def test_read_cache_line_lengths(self) -> None:
+ mode = DEFAULT_MODE
+ short_mode = replace(DEFAULT_MODE, line_length=1)
+ with cache_dir() as workspace:
+ path = (workspace / "file.py").resolve()
+ path.touch()
+ black.write_cache({}, [path], mode)
+ one = black.read_cache(mode)
+ self.assertIn(path, one)
+ two = black.read_cache(short_mode)
+ self.assertNotIn(path, two)
+
+ 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(path, pyi_cache)
+ normal_cache = black.read_cache(DEFAULT_MODE)
+ self.assertNotIn(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(path, pyi_cache)
+ self.assertNotIn(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(path, py36_cache)
+ normal_cache = black.read_cache(reg_mode)
+ self.assertNotIn(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(path, pyi_cache)
+ self.assertNotIn(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)
+
+ def test_include_exclude(self) -> None:
+ path = THIS_DIR / "data" / "include_exclude_tests"
+ include = re.compile(r"\.pyi?$")
+ exclude = re.compile(r"/exclude/|/\.definitely_exclude/")
+ report = black.Report()
+ gitignore = PathSpec.from_lines("gitwildmatch", [])
+ sources: List[Path] = []
+ expected = [
+ Path(path / "b/dont_exclude/a.py"),
+ Path(path / "b/dont_exclude/a.pyi"),
+ ]
+ this_abs = THIS_DIR.resolve()
+ sources.extend(
+ black.gen_python_files(
+ path.iterdir(), this_abs, include, exclude, None, report, gitignore
+ )
+ )
+ self.assertEqual(sorted(expected), sorted(sources))
+
+ @patch("black.find_project_root", lambda *args: THIS_DIR.resolve())
+ def test_exclude_for_issue_1572(self) -> None:
+ # Exclude shouldn't touch files that were explicitly given to Black through the
+ # CLI. Exclude is supposed to only apply to the recursive discovery of files.
+ # https://github.com/psf/black/issues/1572
+ path = THIS_DIR / "data" / "include_exclude_tests"
+ include = ""
+ exclude = r"/exclude/|a\.py"
+ src = str(path / "b/exclude/a.py")
+ report = black.Report()
+ expected = [Path(path / "b/exclude/a.py")]
+ sources = list(
+ black.get_sources(
+ ctx=FakeContext(),
+ src=(src,),
+ quiet=True,
+ verbose=False,
+ include=include,
+ exclude=exclude,
+ force_exclude=None,
+ report=report,
+ stdin_filename=None,
+ )
+ )
+ self.assertEqual(sorted(expected), sorted(sources))
+
+ @patch("black.find_project_root", lambda *args: THIS_DIR.resolve())
+ def test_get_sources_with_stdin(self) -> None:
+ include = ""
+ exclude = r"/exclude/|a\.py"
+ src = "-"
+ report = black.Report()
+ expected = [Path("-")]
+ sources = list(
+ black.get_sources(
+ ctx=FakeContext(),
+ src=(src,),
+ quiet=True,
+ verbose=False,
+ include=include,
+ exclude=exclude,
+ force_exclude=None,
+ report=report,
+ stdin_filename=None,
+ )
+ )
+ self.assertEqual(sorted(expected), sorted(sources))
+
+ @patch("black.find_project_root", lambda *args: THIS_DIR.resolve())
+ def test_get_sources_with_stdin_filename(self) -> None:
+ include = ""
+ exclude = r"/exclude/|a\.py"
+ src = "-"
+ report = black.Report()
+ stdin_filename = str(THIS_DIR / "data/collections.py")
+ expected = [Path(f"__BLACK_STDIN_FILENAME__{stdin_filename}")]
+ sources = list(
+ black.get_sources(
+ ctx=FakeContext(),
+ src=(src,),
+ quiet=True,
+ verbose=False,
+ include=include,
+ exclude=exclude,
+ force_exclude=None,
+ report=report,
+ stdin_filename=stdin_filename,
+ )
+ )
+ self.assertEqual(sorted(expected), sorted(sources))
+
+ @patch("black.find_project_root", lambda *args: THIS_DIR.resolve())
+ def test_get_sources_with_stdin_filename_and_exclude(self) -> None:
+ # Exclude shouldn't exclude stdin_filename since it is mimicing the
+ # file being passed directly. This is the same as
+ # test_exclude_for_issue_1572
+ path = THIS_DIR / "data" / "include_exclude_tests"
+ include = ""
+ exclude = r"/exclude/|a\.py"
+ src = "-"
+ report = black.Report()
+ stdin_filename = str(path / "b/exclude/a.py")
+ expected = [Path(f"__BLACK_STDIN_FILENAME__{stdin_filename}")]
+ sources = list(
+ black.get_sources(
+ ctx=FakeContext(),
+ src=(src,),
+ quiet=True,
+ verbose=False,
+ include=include,
+ exclude=exclude,
+ force_exclude=None,
+ report=report,
+ stdin_filename=stdin_filename,
+ )
+ )
+ self.assertEqual(sorted(expected), sorted(sources))
+
+ @patch("black.find_project_root", lambda *args: THIS_DIR.resolve())
+ def test_get_sources_with_stdin_filename_and_force_exclude(self) -> None:
+ # Force exclude should exclude the file when passing it through
+ # stdin_filename
+ path = THIS_DIR / "data" / "include_exclude_tests"
+ include = ""
+ force_exclude = r"/exclude/|a\.py"
+ src = "-"
+ report = black.Report()
+ stdin_filename = str(path / "b/exclude/a.py")
+ sources = list(
+ black.get_sources(
+ ctx=FakeContext(),
+ src=(src,),
+ quiet=True,
+ verbose=False,
+ include=include,
+ exclude="",
+ force_exclude=force_exclude,
+ report=report,
+ stdin_filename=stdin_filename,
+ )
+ )
+ self.assertEqual([], sorted(sources))
+
+ 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)
+
+ 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()
+ # __BLACK_STDIN_FILENAME__ should have been striped
+ report.done.assert_called_with(expected, black.Changed.YES)
+
+ 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 striped
+ report.done.assert_called_with(expected, black.Changed.YES)
+
+ def test_gitignore_exclude(self) -> None:
+ path = THIS_DIR / "data" / "include_exclude_tests"
+ include = re.compile(r"\.pyi?$")
+ exclude = re.compile(r"")
+ report = black.Report()
+ gitignore = PathSpec.from_lines(
+ "gitwildmatch", ["exclude/", ".definitely_exclude"]
+ )
+ sources: List[Path] = []
+ expected = [
+ Path(path / "b/dont_exclude/a.py"),
+ Path(path / "b/dont_exclude/a.pyi"),
+ ]
+ this_abs = THIS_DIR.resolve()
+ sources.extend(
+ black.gen_python_files(
+ path.iterdir(), this_abs, include, exclude, None, report, gitignore
+ )
+ )
+ self.assertEqual(sorted(expected), sorted(sources))
+
+ def test_empty_include(self) -> None:
+ path = THIS_DIR / "data" / "include_exclude_tests"
+ report = black.Report()
+ gitignore = PathSpec.from_lines("gitwildmatch", [])
+ empty = re.compile(r"")
+ sources: List[Path] = []
+ expected = [
+ Path(path / "b/exclude/a.pie"),
+ Path(path / "b/exclude/a.py"),
+ Path(path / "b/exclude/a.pyi"),
+ Path(path / "b/dont_exclude/a.pie"),
+ Path(path / "b/dont_exclude/a.py"),
+ Path(path / "b/dont_exclude/a.pyi"),
+ Path(path / "b/.definitely_exclude/a.pie"),
+ Path(path / "b/.definitely_exclude/a.py"),
+ Path(path / "b/.definitely_exclude/a.pyi"),
+ ]
+ this_abs = THIS_DIR.resolve()
+ sources.extend(
+ black.gen_python_files(
+ path.iterdir(),
+ this_abs,
+ empty,
+ re.compile(black.DEFAULT_EXCLUDES),
+ None,
+ report,
+ gitignore,
+ )
+ )
+ self.assertEqual(sorted(expected), sorted(sources))
+
+ def test_empty_exclude(self) -> None:
+ path = THIS_DIR / "data" / "include_exclude_tests"
+ report = black.Report()
+ gitignore = PathSpec.from_lines("gitwildmatch", [])
+ empty = re.compile(r"")
+ sources: List[Path] = []
+ expected = [
+ Path(path / "b/dont_exclude/a.py"),
+ Path(path / "b/dont_exclude/a.pyi"),
+ Path(path / "b/exclude/a.py"),
+ Path(path / "b/exclude/a.pyi"),
+ Path(path / "b/.definitely_exclude/a.py"),
+ Path(path / "b/.definitely_exclude/a.pyi"),
+ ]
+ this_abs = THIS_DIR.resolve()
+ sources.extend(
+ black.gen_python_files(
+ path.iterdir(),
+ this_abs,
+ re.compile(black.DEFAULT_INCLUDES),
+ empty,
+ None,
+ report,
+ gitignore,
+ )
+ )
+ self.assertEqual(sorted(expected), sorted(sources))
+
+ def test_invalid_include_exclude(self) -> None:
+ for option in ["--include", "--exclude"]:
+ self.invokeBlack(["-", option, "**()(!!*)"], exit_code=2)
+
+ 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"))
+ )