+ 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 = runner.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_symlink_out_of_root_directory(self) -> None:
+ path = MagicMock()
+ root = THIS_DIR
+ child = MagicMock()
+ include = re.compile(black.DEFAULT_INCLUDES)
+ exclude = re.compile(black.DEFAULT_EXCLUDES)
+ report = black.Report()
+ # `child` should behave like a symlink which resolved path is clearly
+ # outside of the `root` directory.
+ path.iterdir.return_value = [child]
+ child.resolve.return_value = Path("/a/b/c")
+ child.is_symlink.return_value = True
+ try:
+ list(black.gen_python_files_in_dir(path, root, include, exclude, report))
+ except ValueError as ve:
+ self.fail("`get_python_files_in_dir()` failed: {ve}")
+ path.iterdir.assert_called_once()
+ child.resolve.assert_called_once()
+ child.is_symlink.assert_called_once()
+ # `child` should behave like a strange file which resolved path is clearly
+ # outside of the `root` directory.
+ child.is_symlink.return_value = False
+ with self.assertRaises(ValueError):
+ list(black.gen_python_files_in_dir(path, root, include, exclude, report))
+ path.iterdir.assert_called()
+ self.assertEqual(path.iterdir.call_count, 2)
+ child.resolve.assert_called()
+ self.assertEqual(child.resolve.call_count, 2)
+ child.is_symlink.assert_called()
+ self.assertEqual(child.is_symlink.call_count, 2)
+
+ 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}")
+
+ @unittest.skipUnless(has_blackd_deps, "blackd's dependencies are not installed")
+ @async_test
+ async def test_blackd_request_needs_formatting(self) -> None:
+ app = blackd.make_app()
+ async with TestClient(TestServer(app)) as client:
+ response = await client.post("/", data=b"print('hello world')")
+ self.assertEqual(response.status, 200)
+ self.assertEqual(response.charset, "utf8")
+ self.assertEqual(await response.read(), b'print("hello world")\n')
+
+ @unittest.skipUnless(has_blackd_deps, "blackd's dependencies are not installed")
+ @async_test
+ async def test_blackd_request_no_change(self) -> None:
+ app = blackd.make_app()
+ async with TestClient(TestServer(app)) as client:
+ response = await client.post("/", data=b'print("hello world")\n')
+ self.assertEqual(response.status, 204)
+ self.assertEqual(await response.read(), b"")
+
+ @unittest.skipUnless(has_blackd_deps, "blackd's dependencies are not installed")
+ @async_test
+ async def test_blackd_request_syntax_error(self) -> None:
+ app = blackd.make_app()
+ async with TestClient(TestServer(app)) as client:
+ response = await client.post("/", data=b"what even ( is")
+ self.assertEqual(response.status, 400)
+ content = await response.text()
+ self.assertTrue(
+ content.startswith("Cannot parse"),
+ msg=f"Expected error to start with 'Cannot parse', got {repr(content)}",
+ )
+
+ @unittest.skipUnless(has_blackd_deps, "blackd's dependencies are not installed")
+ @async_test
+ async def test_blackd_unsupported_version(self) -> None:
+ app = blackd.make_app()
+ async with TestClient(TestServer(app)) as client:
+ response = await client.post(
+ "/", data=b"what", headers={blackd.VERSION_HEADER: "2"}
+ )
+ self.assertEqual(response.status, 501)
+
+ @unittest.skipUnless(has_blackd_deps, "blackd's dependencies are not installed")
+ @async_test
+ async def test_blackd_supported_version(self) -> None:
+ app = blackd.make_app()
+ async with TestClient(TestServer(app)) as client:
+ response = await client.post(
+ "/", data=b"what", headers={blackd.VERSION_HEADER: "1"}
+ )
+ self.assertEqual(response.status, 200)
+
+ @unittest.skipUnless(has_blackd_deps, "blackd's dependencies are not installed")
+ @async_test
+ async def test_blackd_invalid_python_variant(self) -> None:
+ app = blackd.make_app()
+ async with TestClient(TestServer(app)) as client:
+ response = await client.post(
+ "/", data=b"what", headers={blackd.PYTHON_VARIANT_HEADER: "lol"}
+ )
+ self.assertEqual(response.status, 400)
+
+ @unittest.skipUnless(has_blackd_deps, "blackd's dependencies are not installed")
+ @async_test
+ async def test_blackd_pyi(self) -> None:
+ app = blackd.make_app()
+ async with TestClient(TestServer(app)) as client:
+ source, expected = read_data("stub.pyi")
+ response = await client.post(
+ "/", data=source, headers={blackd.PYTHON_VARIANT_HEADER: "pyi"}
+ )
+ self.assertEqual(response.status, 200)
+ self.assertEqual(await response.text(), expected)
+
+ @unittest.skipUnless(has_blackd_deps, "blackd's dependencies are not installed")
+ @async_test
+ async def test_blackd_py36(self) -> None:
+ app = blackd.make_app()
+ async with TestClient(TestServer(app)) as client:
+ response = await client.post(
+ "/",
+ data=(
+ "def f(\n"
+ " and_has_a_bunch_of,\n"
+ " very_long_arguments_too,\n"
+ " and_lots_of_them_as_well_lol,\n"
+ " **and_very_long_keyword_arguments\n"
+ "):\n"
+ " pass\n"
+ ),
+ headers={blackd.PYTHON_VARIANT_HEADER: "3.6"},
+ )
+ self.assertEqual(response.status, 200)
+ response = await client.post(
+ "/",
+ data=(
+ "def f(\n"
+ " and_has_a_bunch_of,\n"
+ " very_long_arguments_too,\n"
+ " and_lots_of_them_as_well_lol,\n"
+ " **and_very_long_keyword_arguments\n"
+ "):\n"
+ " pass\n"
+ ),
+ headers={blackd.PYTHON_VARIANT_HEADER: "3.5"},
+ )
+ self.assertEqual(response.status, 204)
+ response = await client.post(
+ "/",
+ data=(
+ "def f(\n"
+ " and_has_a_bunch_of,\n"
+ " very_long_arguments_too,\n"
+ " and_lots_of_them_as_well_lol,\n"
+ " **and_very_long_keyword_arguments\n"
+ "):\n"
+ " pass\n"
+ ),
+ headers={blackd.PYTHON_VARIANT_HEADER: "2"},
+ )
+ self.assertEqual(response.status, 204)
+
+ @unittest.skipUnless(has_blackd_deps, "blackd's dependencies are not installed")
+ @async_test
+ async def test_blackd_fast(self) -> None:
+ app = blackd.make_app()
+ async with TestClient(TestServer(app)) as client:
+ response = await client.post("/", data=b"ur'hello'")
+ self.assertEqual(response.status, 500)
+ self.assertIn("failed to parse source file", await response.text())
+ response = await client.post(
+ "/", data=b"ur'hello'", headers={blackd.FAST_OR_SAFE_HEADER: "fast"}
+ )
+ self.assertEqual(response.status, 200)
+
+ @unittest.skipUnless(has_blackd_deps, "blackd's dependencies are not installed")
+ @async_test
+ async def test_blackd_line_length(self) -> None:
+ app = blackd.make_app()
+ async with TestClient(TestServer(app)) as client:
+ response = await client.post(
+ "/", data=b'print("hello")\n', headers={blackd.LINE_LENGTH_HEADER: "7"}
+ )
+ self.assertEqual(response.status, 200)
+
+ @unittest.skipUnless(has_blackd_deps, "blackd's dependencies are not installed")
+ @async_test
+ async def test_blackd_invalid_line_length(self) -> None:
+ app = blackd.make_app()
+ async with TestClient(TestServer(app)) as client:
+ response = await client.post(
+ "/",
+ data=b'print("hello")\n',
+ headers={blackd.LINE_LENGTH_HEADER: "NaN"},
+ )
+ self.assertEqual(response.status, 400)
+
+ @unittest.skipUnless(has_blackd_deps, "blackd's dependencies are not installed")
+ def test_blackd_main(self) -> None:
+ with patch("blackd.web.run_app"):
+ result = CliRunner().invoke(blackd.main, [])
+ if result.exception is not None:
+ raise result.exception
+ self.assertEqual(result.exit_code, 0)