Debian Codegraph @

tests/test_black.py

raw
1 #!/usr/bin/env python3
2
3 import asyncio
4 import inspect
5 import io
6 import itertools
7 import logging
8 import multiprocessing
9 import os
10 import re
11 import sys
12 import textwrap
13 import types
14 from collections.abc import Callable, Iterator, Sequence
15 from concurrent.futures import ThreadPoolExecutor
16 from contextlib import contextmanager, redirect_stderr
17 from dataclasses import fields, replace
18 from importlib.metadata import version as imp_version
19 from io import BytesIO
20 from pathlib import Path, WindowsPath
21 from platform import system
22 from tempfile import NamedTemporaryFile, TemporaryDirectory
23 from typing import Any, TypeVar
24 from unittest.mock import MagicMock, patch
25
26 import click
27 import pytest
28 from click import unstyle
29 from click.testing import CliRunner as _CliRunner
30 from packaging.version import Version
31 from pathspec import GitIgnoreSpec
32
33 import black
34 import black.files
35 from black import Feature, TargetVersion
36 from black import re_compile_maybe_verbose as compile_pattern
37 from black.cache import FileData, get_cache_dir, get_cache_file
38 from black.debug import DebugVisitor
39 from black.mode import Mode, Preview
40 from black.output import color_diff, diff
41 from black.parsing import ASTSafetyError, SourceASTParseError
42 from black.report import Report
43 from black.strings import lines_with_leading_tabs_expanded
44
45 # Import other test classes
46 from tests.util import (
47 DATA_DIR,
48 DEFAULT_MODE,
49 DETERMINISTIC_HEADER,
50 PROJECT_ROOT,
51 PY36_VERSIONS,
52 THIS_DIR,
53 BlackBaseTestCase,
54 assert_format,
55 change_directory,
56 dump_to_stderr,
57 ff,
58 fs,
59 get_case_path,
60 read_data,
61 read_data_from_file,
62 )
63
64 THIS_FILE = Path(__file__)
65 EMPTY_CONFIG = THIS_DIR / "data" / "empty_pyproject.toml"
66 PY36_ARGS = [f"--target-version={version.name.lower()}" for version in PY36_VERSIONS]
67 DEFAULT_EXCLUDE = black.re_compile_maybe_verbose(black.const.DEFAULT_EXCLUDES)
68 DEFAULT_INCLUDE = black.re_compile_maybe_verbose(black.const.DEFAULT_INCLUDES)
69 T = TypeVar("T")
70 R = TypeVar("R")
71
72 # Match the time output in a diff, but nothing else
73 DIFF_TIME = re.compile(r"\t[\d\-:+\. ]+")
74
75
76 @contextmanager
77 def cache_dir(exists: bool = True) -> Iterator[Path]:
78 with TemporaryDirectory() as workspace:
79 cache_dir = Path(workspace)
80 if not exists:
81 cache_dir = cache_dir / "new"
82 with patch("black.cache.CACHE_DIR", cache_dir):
83 yield cache_dir
84
85
86 @contextmanager
87 def event_loop() -> Iterator[None]:
88 loop = asyncio.new_event_loop()
89 asyncio.set_event_loop(loop)
90 try:
91 yield
92
93 finally:
94 loop.close()
95
96
97 class FakeContext(click.Context):
98 """A fake click Context for when calling functions that need it."""
99
100 def __init__(self) -> None:
101 self.default_map: dict[str, Any] = {}
102 self.params: dict[str, Any] = {}
103 self.command: click.Command = black.main
104 # Dummy root, since most of the tests don't care about it
105 self.obj: dict[str, Any] = {"root": PROJECT_ROOT}
106
107
108 class BlackRunner(_CliRunner):
109 """Make sure STDOUT and STDERR are kept separate when testing Black via its CLI."""
110
111 def __init__(self) -> None:
112 if Version(imp_version("click")) >= Version("8.2.0"):
113 super().__init__()
114 else:
115 super().__init__(mix_stderr=False) # type: ignore
116
117
118 def invokeBlack(
119 args: list[str], exit_code: int = 0, ignore_config: bool = True
120 ) -> None:
121 runner = BlackRunner()
122 if ignore_config:
123 args = ["--verbose", "--config", str(THIS_DIR / "empty.toml"), *args]
124 result = runner.invoke(black.main, args, catch_exceptions=False)
125 assert result.stdout_bytes is not None
126 assert result.stderr_bytes is not None
127 msg = (
128 f"Failed with args: {args}\n"
129 f"stdout: {result.stdout_bytes.decode()!r}\n"
130 f"stderr: {result.stderr_bytes.decode()!r}\n"
131 f"exception: {result.exception}"
132 )
133 assert result.exit_code == exit_code, msg
134
135
136 class BlackTestCase(BlackBaseTestCase):
137 invokeBlack = staticmethod(invokeBlack)
138
139 def test_empty_ff(self) -> None:
140 expected = ""
141 tmp_file = Path(black.dump_to_file())
142 try:
143 self.assertFalse(ff(tmp_file, write_back=black.WriteBack.YES))
144 actual = tmp_file.read_text(encoding="utf-8")
145 finally:
146 os.unlink(tmp_file)
147 self.assertFormatEqual(expected, actual)
148
149 @patch("black.dump_to_file", dump_to_stderr)
150 def test_one_empty_line(self) -> None:
151 for nl in ["\n", "\r\n"]:
152 source = expected = nl
153 assert_format(source, expected)
154
155 def test_one_empty_line_ff(self) -> None:
156 for nl in ["\n", "\r\n"]:
157 expected = nl
158 tmp_file = Path(black.dump_to_file(nl))
159 if system() == "Windows":
160 # Writing files in text mode automatically uses the system newline,
161 # but in this case we don't want this for testing reasons. See:
162 # https://github.com/psf/black/pull/3348
163 with open(tmp_file, "wb") as f:
164 f.write(nl.encode("utf-8"))
165 try:
166 self.assertFalse(ff(tmp_file, write_back=black.WriteBack.YES))
167 with open(tmp_file, "rb") as f:
168 actual = f.read().decode("utf-8")
169 finally:
170 os.unlink(tmp_file)
171 self.assertFormatEqual(expected, actual)
172
173 def test_piping(self) -> None:
174 _, source, expected = read_data_from_file(
175 PROJECT_ROOT / "src/black/__init__.py"
176 )
177 result = BlackRunner().invoke(
178 black.main,
179 [
180 "-",
181 "--fast",
182 f"--line-length={black.DEFAULT_LINE_LENGTH}",
183 f"--config={EMPTY_CONFIG}",
184 ],
185 input=BytesIO(source.encode("utf-8")),
186 )
187 self.assertEqual(result.exit_code, 0)
188 self.assertFormatEqual(expected, result.stdout)
189 if source != result.stdout:
190 black.assert_equivalent(source, result.stdout)
191 black.assert_stable(source, result.stdout, DEFAULT_MODE)
192
193 def test_piping_diff(self) -> None:
194 diff_header = re.compile(
195 r"(STDIN|STDOUT)\t\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d\.\d\d\d\d\d\d"
196 r"\+\d\d:\d\d"
197 )
198 source, _ = read_data("cases", "expression.py")
199 expected, _ = read_data("cases", "expression.diff")
200 args = [
201 "-",
202 "--fast",
203 f"--line-length={black.DEFAULT_LINE_LENGTH}",
204 "--diff",
205 f"--config={EMPTY_CONFIG}",
206 ]
207 result = BlackRunner().invoke(
208 black.main, args, input=BytesIO(source.encode("utf-8"))
209 )
210 self.assertEqual(result.exit_code, 0)
211 actual = diff_header.sub(DETERMINISTIC_HEADER, result.stdout)
212 actual = actual.rstrip() + "\n" # the diff output has a trailing space
213 self.assertEqual(expected, actual)
214
215 def test_piping_diff_with_color(self) -> None:
216 source, _ = read_data("cases", "expression.py")
217 args = [
218 "-",
219 "--fast",
220 f"--line-length={black.DEFAULT_LINE_LENGTH}",
221 "--diff",
222 "--color",
223 f"--config={EMPTY_CONFIG}",
224 ]
225 result = BlackRunner().invoke(
226 black.main, args, input=BytesIO(source.encode("utf-8"))
227 )
228 actual = result.output
229 # Again, the contents are checked in a different test, so only look for colors.
230 self.assertIn("\033[1m", actual)
231 self.assertIn("\033[36m", actual)
232 self.assertIn("\033[32m", actual)
233 self.assertIn("\033[31m", actual)
234 self.assertIn("\033[0m", actual)
235
236 def test_pep_572_version_detection(self) -> None:
237 source, _ = read_data("cases", "pep_572")
238 root = black.lib2to3_parse(source)
239 features = black.get_features_used(root)
240 self.assertIn(black.Feature.ASSIGNMENT_EXPRESSIONS, features)
241 versions = black.detect_target_versions(root)
242 self.assertIn(black.TargetVersion.PY38, versions)
243
244 def test_pep_695_version_detection(self) -> None:
245 for file in ("type_aliases", "type_params"):
246 source, _ = read_data("cases", file)
247 root = black.lib2to3_parse(source)
248 features = black.get_features_used(root)
249 self.assertIn(black.Feature.TYPE_PARAMS, features)
250 versions = black.detect_target_versions(root)
251 self.assertIn(black.TargetVersion.PY312, versions)
252
253 def test_pep_696_version_detection(self) -> None:
254 source, _ = read_data("cases", "type_param_defaults")
255 samples = [
256 source,
257 "type X[T=int] = float",
258 "type X[T:int=int]=int",
259 "type X[*Ts=int]=int",
260 "type X[*Ts=*int]=int",
261 "type X[**P=int]=int",
262 ]
263 for sample in samples:
264 root = black.lib2to3_parse(sample)
265 features = black.get_features_used(root)
266 self.assertIn(black.Feature.TYPE_PARAM_DEFAULTS, features)
267
268 def test_python315_version_detection(self) -> None:
269 source, _ = read_data("cases", "python315")
270 root = black.lib2to3_parse(source)
271 features = black.get_features_used(root)
272 self.assertIn(black.Feature.LAZY_IMPORTS, features)
273 self.assertIn(black.Feature.UNPACKING_IN_COMPREHENSIONS, features)
274 self.assertNotIn(
275 black.Feature.LAZY_IMPORTS,
276 black.get_features_used(black.lib2to3_parse("lazy = 1\n")),
277 )
278 versions = black.detect_target_versions(root)
279 self.assertIn(black.TargetVersion.PY315, versions)
280
281 def test_expression_ff(self) -> None:
282 source, expected = read_data("cases", "expression.py")
283 tmp_file = Path(black.dump_to_file(source))
284 try:
285 self.assertTrue(ff(tmp_file, write_back=black.WriteBack.YES))
286 actual = tmp_file.read_text(encoding="utf-8")
287 finally:
288 os.unlink(tmp_file)
289 self.assertFormatEqual(expected, actual)
290 with patch("black.dump_to_file", dump_to_stderr):
291 black.assert_equivalent(source, actual)
292 black.assert_stable(source, actual, DEFAULT_MODE)
293
294 def test_expression_diff(self) -> None:
295 source, _ = read_data("cases", "expression.py")
296 expected, _ = read_data("cases", "expression.diff")
297 tmp_file = Path(black.dump_to_file(source))
298 diff_header = re.compile(
299 rf"{re.escape(str(tmp_file))}\t\d\d\d\d-\d\d-\d\d "
300 r"\d\d:\d\d:\d\d\.\d\d\d\d\d\d\+\d\d:\d\d"
301 )
302 try:
303 result = BlackRunner().invoke(
304 black.main, ["--diff", str(tmp_file), f"--config={EMPTY_CONFIG}"]
305 )
306 self.assertEqual(result.exit_code, 0)
307 finally:
308 os.unlink(tmp_file)
309 actual = result.stdout
310 actual = diff_header.sub(DETERMINISTIC_HEADER, actual)
311 if expected != actual:
312 dump = black.dump_to_file(actual)
313 msg = (
314 "Expected diff isn't equal to the actual. If you made changes to"
315 " expression.py and this is an anticipated difference, overwrite"
316 f" tests/data/cases/expression.diff with {dump}"
317 )
318 self.assertEqual(expected, actual, msg)
319
320 def test_expression_diff_with_color(self) -> None:
321 source, _ = read_data("cases", "expression.py")
322 expected, _ = read_data("cases", "expression.diff")
323 tmp_file = Path(black.dump_to_file(source))
324 try:
325 result = BlackRunner().invoke(
326 black.main,
327 ["--diff", "--color", str(tmp_file), f"--config={EMPTY_CONFIG}"],
328 )
329 finally:
330 os.unlink(tmp_file)
331 actual = result.output
332 # We check the contents of the diff in `test_expression_diff`. All
333 # we need to check here is that color codes exist in the result.
334 self.assertIn("\033[1m", actual)
335 self.assertIn("\033[36m", actual)
336 self.assertIn("\033[32m", actual)
337 self.assertIn("\033[31m", actual)
338 self.assertIn("\033[0m", actual)
339
340 def test_detect_pos_only_arguments(self) -> None:
341 source, _ = read_data("cases", "pep_570")
342 root = black.lib2to3_parse(source)
343 features = black.get_features_used(root)
344 self.assertIn(black.Feature.POS_ONLY_ARGUMENTS, features)
345 versions = black.detect_target_versions(root)
346 self.assertIn(black.TargetVersion.PY38, versions)
347
348 def test_detect_debug_f_strings(self) -> None:
349 root = black.lib2to3_parse("""f"{x=}" """)
350 features = black.get_features_used(root)
351 self.assertIn(black.Feature.DEBUG_F_STRINGS, features)
352 versions = black.detect_target_versions(root)
353 self.assertIn(black.TargetVersion.PY38, versions)
354
355 root = black.lib2to3_parse(
356 """f"{x}"\nf'{"="}'\nf'{(x:=5)}'\nf'{f(a="3=")}'\nf'{x:=10}'\n"""
357 )
358 features = black.get_features_used(root)
359 self.assertNotIn(black.Feature.DEBUG_F_STRINGS, features)
360
361 root = black.lib2to3_parse(
362 """f"heard a rumour that { f'{1+1=}' } ... seems like it could be true" """
363 )
364 features = black.get_features_used(root)
365 self.assertIn(black.Feature.DEBUG_F_STRINGS, features)
366
367 @patch("black.dump_to_file", dump_to_stderr)
368 def test_string_quotes(self) -> None:
369 source, expected = read_data("miscellaneous", "string_quotes")
370 mode = black.Mode(unstable=True)
371 assert_format(source, expected, mode)
372 mode = replace(mode, string_normalization=False)
373 not_normalized = fs(source, mode=mode)
374 self.assertFormatEqual(source.replace("\\\n", ""), not_normalized)
375 black.assert_equivalent(source, not_normalized)
376 black.assert_stable(source, not_normalized, mode=mode)
377
378 def test_skip_source_first_line(self) -> None:
379 source, _ = read_data("miscellaneous", "invalid_header")
380 tmp_file = Path(black.dump_to_file(source))
381 # Full source should fail (invalid syntax at header)
382 self.invokeBlack([str(tmp_file), "--diff", "--check"], exit_code=123)
383 # So, skipping the first line should work
384 result = BlackRunner().invoke(
385 black.main, [str(tmp_file), "-x", f"--config={EMPTY_CONFIG}"]
386 )
387 self.assertEqual(result.exit_code, 0)
388 actual = tmp_file.read_text(encoding="utf-8")
389 self.assertFormatEqual(source, actual)
390
391 def test_skip_source_first_line_when_mixing_newlines(self) -> None:
392 code_mixing_newlines = b"Header will be skipped\r\ni = [1,2,3]\nj = [1,2,3]\n"
393 expected = b"Header will be skipped\r\ni = [1, 2, 3]\nj = [1, 2, 3]\n"
394 with TemporaryDirectory() as workspace:
395 test_file = Path(workspace) / "skip_header.py"
396 test_file.write_bytes(code_mixing_newlines)
397 mode = replace(DEFAULT_MODE, skip_source_first_line=True)
398 ff(test_file, mode=mode, write_back=black.WriteBack.YES)
399 self.assertEqual(test_file.read_bytes(), expected)
400
401 def test_skip_magic_trailing_comma(self) -> None:
402 source, _ = read_data("cases", "expression")
403 expected, _ = read_data(
404 "miscellaneous", "expression_skip_magic_trailing_comma.diff"
405 )
406 tmp_file = Path(black.dump_to_file(source))
407 diff_header = re.compile(
408 rf"{re.escape(str(tmp_file))}\t\d\d\d\d-\d\d-\d\d "
409 r"\d\d:\d\d:\d\d\.\d\d\d\d\d\d\+\d\d:\d\d"
410 )
411 try:
412 result = BlackRunner().invoke(
413 black.main, ["-C", "--diff", str(tmp_file), f"--config={EMPTY_CONFIG}"]
414 )
415 self.assertEqual(result.exit_code, 0)
416 finally:
417 os.unlink(tmp_file)
418 actual = result.stdout
419 actual = diff_header.sub(DETERMINISTIC_HEADER, actual)
420 actual = actual.rstrip() + "\n" # the diff output has a trailing space
421 if expected != actual:
422 dump = black.dump_to_file(actual)
423 msg = (
424 "Expected diff isn't equal to the actual. If you made changes to"
425 " expression.py and this is an anticipated difference, overwrite"
426 " tests/data/miscellaneous/expression_skip_magic_trailing_comma.diff"
427 f" with {dump}"
428 )
429 self.assertEqual(expected, actual, msg)
430
431 @patch("black.dump_to_file", dump_to_stderr)
432 def test_python37(self) -> None:
433 source_path = get_case_path("cases", "python37")
434 _, source, expected = read_data_from_file(source_path)
435 actual = fs(source)
436 self.assertFormatEqual(expected, actual)
437 black.assert_equivalent(source, actual)
438 black.assert_stable(source, actual, DEFAULT_MODE)
439 # ensure black can parse this when the target is 3.7
440 self.invokeBlack([str(source_path), "--target-version", "py37"])
441
442 @patch("black.dump_to_file", dump_to_stderr)
443 def test_python315(self) -> None:
444 source_path = get_case_path("cases", "python315")
445 _, source, expected = read_data_from_file(source_path)
446 actual = fs(source)
447 self.assertFormatEqual(expected, actual)
448 if sys.version_info >= (3, 15):
449 black.assert_equivalent(source, actual)
450 black.assert_stable(source, actual, DEFAULT_MODE)
451 self.invokeBlack([str(source_path), "--target-version", "py315", "--fast"])
452
453 def test_tab_comment_indentation(self) -> None:
454 contents_tab = "if 1:\n\tif 2:\n\t\tpass\n\t# comment\n\tpass\n"
455 contents_spc = "if 1:\n if 2:\n pass\n # comment\n pass\n"
456 self.assertFormatEqual(contents_spc, fs(contents_spc))
457 self.assertFormatEqual(contents_spc, fs(contents_tab))
458
459 contents_tab = "if 1:\n\tif 2:\n\t\tpass\n\t\t# comment\n\tpass\n"
460 contents_spc = "if 1:\n if 2:\n pass\n # comment\n pass\n"
461 self.assertFormatEqual(contents_spc, fs(contents_spc))
462 self.assertFormatEqual(contents_spc, fs(contents_tab))
463
464 def test_false_positive_symlink_output_issue_3384(self) -> None:
465 # Emulate the behavior when using the CLI (`black ./child --verbose`), which
466 # involves patching some `pathlib.Path` methods. In particular, `is_dir` is
467 # patched only on its first call: when checking if "./child" is a directory it
468 # should return True. The "./child" folder exists relative to the cwd when
469 # running from CLI, but fails when running the tests because cwd is different
470 project_root = Path(THIS_DIR / "data" / "nested_gitignore_tests")
471 working_directory = project_root / "root"
472
473 with change_directory(working_directory):
474 # Note that the root folder (project_root) isn't the folder
475 # named "root" (aka working_directory)
476 report = MagicMock(verbose=True)
477 black.get_sources(
478 root=project_root,
479 src=("./child",),
480 quiet=False,
481 verbose=True,
482 include=DEFAULT_INCLUDE,
483 exclude=None,
484 report=report,
485 extend_exclude=None,
486 force_exclude=None,
487 stdin_filename=None,
488 )
489 assert not any(
490 mock_args[1].startswith("is a symbolic link that points outside")
491 for _, mock_args, _ in report.path_ignored.mock_calls
492 ), "A symbolic link was reported."
493 report.path_ignored.assert_called_once_with(
494 Path(working_directory, "child", "b.py"),
495 "matches a .gitignore file content",
496 )
497
498 def test_report_verbose(self) -> None:
499 report = Report(verbose=True)
500 out_lines = []
501 err_lines = []
502
503 def out(msg: str, **kwargs: Any) -> None:
504 out_lines.append(msg)
505
506 def err(msg: str, **kwargs: Any) -> None:
507 err_lines.append(msg)
508
509 with patch("black.output._out", out), patch("black.output._err", err):
510 report.done(Path("f1"), black.Changed.NO)
511 self.assertEqual(len(out_lines), 1)
512 self.assertEqual(len(err_lines), 0)
513 self.assertEqual(out_lines[-1], "f1 already well formatted, good job.")
514 self.assertEqual(unstyle(str(report)), "1 file left unchanged.")
515 self.assertEqual(report.return_code, 0)
516 report.done(Path("f2"), black.Changed.YES)
517 self.assertEqual(len(out_lines), 2)
518 self.assertEqual(len(err_lines), 0)
519 self.assertEqual(out_lines[-1], "reformatted f2")
520 self.assertEqual(
521 unstyle(str(report)), "1 file reformatted, 1 file left unchanged."
522 )
523 report.done(Path("f3"), black.Changed.CACHED)
524 self.assertEqual(len(out_lines), 3)
525 self.assertEqual(len(err_lines), 0)
526 self.assertEqual(
527 out_lines[-1], "f3 wasn't modified on disk since last run."
528 )
529 self.assertEqual(
530 unstyle(str(report)), "1 file reformatted, 2 files left unchanged."
531 )
532 self.assertEqual(report.return_code, 0)
533 report.check = True
534 self.assertEqual(report.return_code, 1)
535 report.check = False
536 report.failed(Path("e1"), "boom")
537 self.assertEqual(len(out_lines), 3)
538 self.assertEqual(len(err_lines), 1)
539 self.assertEqual(err_lines[-1], "error: cannot format e1: boom")
540 self.assertEqual(
541 unstyle(str(report)),
542 "1 file reformatted, 2 files left unchanged, 1 file failed to"
543 " reformat.",
544 )
545 self.assertEqual(report.return_code, 123)
546 report.done(Path("f3"), black.Changed.YES)
547 self.assertEqual(len(out_lines), 4)
548 self.assertEqual(len(err_lines), 1)
549 self.assertEqual(out_lines[-1], "reformatted f3")
550 self.assertEqual(
551 unstyle(str(report)),
552 "2 files reformatted, 2 files left unchanged, 1 file failed to"
553 " reformat.",
554 )
555 self.assertEqual(report.return_code, 123)
556 report.failed(Path("e2"), "boom")
557 self.assertEqual(len(out_lines), 4)
558 self.assertEqual(len(err_lines), 2)
559 self.assertEqual(err_lines[-1], "error: cannot format e2: boom")
560 self.assertEqual(
561 unstyle(str(report)),
562 "2 files reformatted, 2 files left unchanged, 2 files failed to"
563 " reformat.",
564 )
565 self.assertEqual(report.return_code, 123)
566 report.path_ignored(Path("wat"), "no match")
567 self.assertEqual(len(out_lines), 5)
568 self.assertEqual(len(err_lines), 2)
569 self.assertEqual(out_lines[-1], "wat ignored: no match")
570 self.assertEqual(
571 unstyle(str(report)),
572 "2 files reformatted, 2 files left unchanged, 2 files failed to"
573 " reformat.",
574 )
575 self.assertEqual(report.return_code, 123)
576 report.done(Path("f4"), black.Changed.NO)
577 self.assertEqual(len(out_lines), 6)
578 self.assertEqual(len(err_lines), 2)
579 self.assertEqual(out_lines[-1], "f4 already well formatted, good job.")
580 self.assertEqual(
581 unstyle(str(report)),
582 "2 files reformatted, 3 files left unchanged, 2 files failed to"
583 " reformat.",
584 )
585 self.assertEqual(report.return_code, 123)
586 report.check = True
587 self.assertEqual(
588 unstyle(str(report)),
589 "2 files would be reformatted, 3 files would be left unchanged, 2"
590 " files would fail to reformat.",
591 )
592 report.check = False
593 report.diff = True
594 self.assertEqual(
595 unstyle(str(report)),
596 "2 files would be reformatted, 3 files would be left unchanged, 2"
597 " files would fail to reformat.",
598 )
599
600 def test_report_quiet(self) -> None:
601 report = Report(quiet=True)
602 out_lines = []
603 err_lines = []
604
605 def out(msg: str, **kwargs: Any) -> None:
606 out_lines.append(msg)
607
608 def err(msg: str, **kwargs: Any) -> None:
609 err_lines.append(msg)
610
611 with patch("black.output._out", out), patch("black.output._err", err):
612 report.done(Path("f1"), black.Changed.NO)
613 self.assertEqual(len(out_lines), 0)
614 self.assertEqual(len(err_lines), 0)
615 self.assertEqual(unstyle(str(report)), "1 file left unchanged.")
616 self.assertEqual(report.return_code, 0)
617 report.done(Path("f2"), black.Changed.YES)
618 self.assertEqual(len(out_lines), 0)
619 self.assertEqual(len(err_lines), 0)
620 self.assertEqual(
621 unstyle(str(report)), "1 file reformatted, 1 file left unchanged."
622 )
623 report.done(Path("f3"), black.Changed.CACHED)
624 self.assertEqual(len(out_lines), 0)
625 self.assertEqual(len(err_lines), 0)
626 self.assertEqual(
627 unstyle(str(report)), "1 file reformatted, 2 files left unchanged."
628 )
629 self.assertEqual(report.return_code, 0)
630 report.check = True
631 self.assertEqual(report.return_code, 1)
632 report.check = False
633 report.failed(Path("e1"), "boom")
634 self.assertEqual(len(out_lines), 0)
635 self.assertEqual(len(err_lines), 1)
636 self.assertEqual(err_lines[-1], "error: cannot format e1: boom")
637 self.assertEqual(
638 unstyle(str(report)),
639 "1 file reformatted, 2 files left unchanged, 1 file failed to"
640 " reformat.",
641 )
642 self.assertEqual(report.return_code, 123)
643 report.done(Path("f3"), black.Changed.YES)
644 self.assertEqual(len(out_lines), 0)
645 self.assertEqual(len(err_lines), 1)
646 self.assertEqual(
647 unstyle(str(report)),
648 "2 files reformatted, 2 files left unchanged, 1 file failed to"
649 " reformat.",
650 )
651 self.assertEqual(report.return_code, 123)
652 report.failed(Path("e2"), "boom")
653 self.assertEqual(len(out_lines), 0)
654 self.assertEqual(len(err_lines), 2)
655 self.assertEqual(err_lines[-1], "error: cannot format e2: boom")
656 self.assertEqual(
657 unstyle(str(report)),
658 "2 files reformatted, 2 files left unchanged, 2 files failed to"
659 " reformat.",
660 )
661 self.assertEqual(report.return_code, 123)
662 report.path_ignored(Path("wat"), "no match")
663 self.assertEqual(len(out_lines), 0)
664 self.assertEqual(len(err_lines), 2)
665 self.assertEqual(
666 unstyle(str(report)),
667 "2 files reformatted, 2 files left unchanged, 2 files failed to"
668 " reformat.",
669 )
670 self.assertEqual(report.return_code, 123)
671 report.done(Path("f4"), black.Changed.NO)
672 self.assertEqual(len(out_lines), 0)
673 self.assertEqual(len(err_lines), 2)
674 self.assertEqual(
675 unstyle(str(report)),
676 "2 files reformatted, 3 files left unchanged, 2 files failed to"
677 " reformat.",
678 )
679 self.assertEqual(report.return_code, 123)
680 report.check = True
681 self.assertEqual(
682 unstyle(str(report)),
683 "2 files would be reformatted, 3 files would be left unchanged, 2"
684 " files would fail to reformat.",
685 )
686 report.check = False
687 report.diff = True
688 self.assertEqual(
689 unstyle(str(report)),
690 "2 files would be reformatted, 3 files would be left unchanged, 2"
691 " files would fail to reformat.",
692 )
693
694 def test_report_normal(self) -> None:
695 report = black.Report()
696 out_lines = []
697 err_lines = []
698
699 def out(msg: str, **kwargs: Any) -> None:
700 out_lines.append(msg)
701
702 def err(msg: str, **kwargs: Any) -> None:
703 err_lines.append(msg)
704
705 with patch("black.output._out", out), patch("black.output._err", err):
706 report.done(Path("f1"), black.Changed.NO)
707 self.assertEqual(len(out_lines), 0)
708 self.assertEqual(len(err_lines), 0)
709 self.assertEqual(unstyle(str(report)), "1 file left unchanged.")
710 self.assertEqual(report.return_code, 0)
711 report.done(Path("f2"), black.Changed.YES)
712 self.assertEqual(len(out_lines), 1)
713 self.assertEqual(len(err_lines), 0)
714 self.assertEqual(out_lines[-1], "reformatted f2")
715 self.assertEqual(
716 unstyle(str(report)), "1 file reformatted, 1 file left unchanged."
717 )
718 report.done(Path("f3"), black.Changed.CACHED)
719 self.assertEqual(len(out_lines), 1)
720 self.assertEqual(len(err_lines), 0)
721 self.assertEqual(out_lines[-1], "reformatted f2")
722 self.assertEqual(
723 unstyle(str(report)), "1 file reformatted, 2 files left unchanged."
724 )
725 self.assertEqual(report.return_code, 0)
726 report.check = True
727 self.assertEqual(report.return_code, 1)
728 report.check = False
729 report.failed(Path("e1"), "boom")
730 self.assertEqual(len(out_lines), 1)
731 self.assertEqual(len(err_lines), 1)
732 self.assertEqual(err_lines[-1], "error: cannot format e1: boom")
733 self.assertEqual(
734 unstyle(str(report)),
735 "1 file reformatted, 2 files left unchanged, 1 file failed to"
736 " reformat.",
737 )
738 self.assertEqual(report.return_code, 123)
739 report.done(Path("f3"), black.Changed.YES)
740 self.assertEqual(len(out_lines), 2)
741 self.assertEqual(len(err_lines), 1)
742 self.assertEqual(out_lines[-1], "reformatted f3")
743 self.assertEqual(
744 unstyle(str(report)),
745 "2 files reformatted, 2 files left unchanged, 1 file failed to"
746 " reformat.",
747 )
748 self.assertEqual(report.return_code, 123)
749 report.failed(Path("e2"), "boom")
750 self.assertEqual(len(out_lines), 2)
751 self.assertEqual(len(err_lines), 2)
752 self.assertEqual(err_lines[-1], "error: cannot format e2: boom")
753 self.assertEqual(
754 unstyle(str(report)),
755 "2 files reformatted, 2 files left unchanged, 2 files failed to"
756 " reformat.",
757 )
758 self.assertEqual(report.return_code, 123)
759 report.path_ignored(Path("wat"), "no match")
760 self.assertEqual(len(out_lines), 2)
761 self.assertEqual(len(err_lines), 2)
762 self.assertEqual(
763 unstyle(str(report)),
764 "2 files reformatted, 2 files left unchanged, 2 files failed to"
765 " reformat.",
766 )
767 self.assertEqual(report.return_code, 123)
768 report.done(Path("f4"), black.Changed.NO)
769 self.assertEqual(len(out_lines), 2)
770 self.assertEqual(len(err_lines), 2)
771 self.assertEqual(
772 unstyle(str(report)),
773 "2 files reformatted, 3 files left unchanged, 2 files failed to"
774 " reformat.",
775 )
776 self.assertEqual(report.return_code, 123)
777 report.check = True
778 self.assertEqual(
779 unstyle(str(report)),
780 "2 files would be reformatted, 3 files would be left unchanged, 2"
781 " files would fail to reformat.",
782 )
783 report.check = False
784 report.diff = True
785 self.assertEqual(
786 unstyle(str(report)),
787 "2 files would be reformatted, 3 files would be left unchanged, 2"
788 " files would fail to reformat.",
789 )
790
791 def test_lib2to3_parse(self) -> None:
792 with self.assertRaises(black.InvalidInput):
793 black.lib2to3_parse("invalid syntax")
794
795 straddling = "x + y"
796 black.lib2to3_parse(straddling)
797 black.lib2to3_parse(straddling, {TargetVersion.PY36})
798
799 py2_only = "print x"
800 with self.assertRaises(black.InvalidInput):
801 black.lib2to3_parse(py2_only, {TargetVersion.PY36})
802
803 py3_only = "exec(x, end=y)"
804 black.lib2to3_parse(py3_only)
805 black.lib2to3_parse(py3_only, {TargetVersion.PY36})
806
807 def test_get_features_used_decorator(self) -> None:
808 # Test the feature detection of new decorator syntax
809 # since this makes some test cases of test_get_features_used()
810 # fails if it fails, this is tested first so that a useful case
811 # is identified
812 simples, relaxed = read_data("miscellaneous", "decorators")
813 # skip explanation comments at the top of the file
814 for simple_test in simples.split("##")[1:]:
815 node = black.lib2to3_parse(simple_test)
816 decorator = str(node.children[0].children[0]).strip()
817 self.assertNotIn(
818 Feature.RELAXED_DECORATORS,
819 black.get_features_used(node),
820 msg=(
821 f"decorator '{decorator}' follows python<=3.8 syntax"
822 "but is detected as 3.9+"
823 # f"The full node is\n{node!r}"
824 ),
825 )
826 # skip the '# output' comment at the top of the output part
827 for relaxed_test in relaxed.split("##")[1:]:
828 node = black.lib2to3_parse(relaxed_test)
829 decorator = str(node.children[0].children[0]).strip()
830 self.assertIn(
831 Feature.RELAXED_DECORATORS,
832 black.get_features_used(node),
833 msg=(
834 f"decorator '{decorator}' uses python3.9+ syntax"
835 "but is detected as python<=3.8"
836 # f"The full node is\n{node!r}"
837 ),
838 )
839
840 def test_get_features_used(self) -> None:
841 self.check_features_used("def f(*, arg): ...\n", set())
842 self.check_features_used(
843 "def f(*, arg,): ...\n", {Feature.TRAILING_COMMA_IN_DEF}
844 )
845 self.check_features_used("f(*arg,)\n", {Feature.TRAILING_COMMA_IN_CALL})
846 self.check_features_used("def f(*, arg): f'string'\n", {Feature.F_STRINGS})
847 self.check_features_used("123_456\n", {Feature.NUMERIC_UNDERSCORES})
848 self.check_features_used("123456\n", set())
849
850 source, expected = read_data("cases", "function")
851 expected_features = {
852 Feature.TRAILING_COMMA_IN_CALL,
853 Feature.TRAILING_COMMA_IN_DEF,
854 Feature.F_STRINGS,
855 }
856 self.check_features_used(source, expected_features)
857 self.check_features_used(expected, expected_features)
858
859 source, expected = read_data("cases", "expression")
860 self.check_features_used(source, set())
861 self.check_features_used(expected, set())
862
863 self.check_features_used("lambda a, /, b: ...\n", {Feature.POS_ONLY_ARGUMENTS})
864 self.check_features_used("def fn(a, /, b): ...", {Feature.POS_ONLY_ARGUMENTS})
865
866 self.check_features_used("def fn(): yield a, b", set())
867 self.check_features_used("def fn(): return a, b", set())
868 self.check_features_used("def fn(): yield *b, c", {Feature.UNPACKING_ON_FLOW})
869 self.check_features_used(
870 "def fn(): return a, *b, c", {Feature.UNPACKING_ON_FLOW}
871 )
872 self.check_features_used("x = a, *b, c", set())
873
874 self.check_features_used("x: Any = regular", set())
875 self.check_features_used("x: Any = (regular, regular)", set())
876 self.check_features_used("x: Any = Complex(Type(1))[something]", set())
877 self.check_features_used(
878 "x: Tuple[int, ...] = a, b, c", {Feature.ANN_ASSIGN_EXTENDED_RHS}
879 )
880
881 self.check_features_used("try: pass\nexcept Something: pass", set())
882 self.check_features_used("try: pass\nexcept (*Something,): pass", set())
883 self.check_features_used(
884 "try: pass\nexcept *Group: pass", {Feature.EXCEPT_STAR}
885 )
886
887 self.check_features_used("a[*b]", {Feature.VARIADIC_GENERICS})
888 self.check_features_used("a[x, *y(), z] = t", {Feature.VARIADIC_GENERICS})
889 self.check_features_used("def fn(*args: *T): pass", {Feature.VARIADIC_GENERICS})
890 self.check_features_used(
891 "def fn(*args: *tuple[*T]): pass", {Feature.VARIADIC_GENERICS}
892 )
893
894 self.check_features_used("with a: pass", set())
895 self.check_features_used("with a, b: pass", set())
896 self.check_features_used("with a as b: pass", set())
897 self.check_features_used("with a as b, c as d: pass", set())
898 self.check_features_used("with (a): pass", set())
899 self.check_features_used("with (a, b): pass", set())
900 self.check_features_used("with (a, b) as (c, d): pass", set())
901 self.check_features_used(
902 "with (a as b): pass", {Feature.PARENTHESIZED_CONTEXT_MANAGERS}
903 )
904 self.check_features_used(
905 "with ((a as b)): pass", {Feature.PARENTHESIZED_CONTEXT_MANAGERS}
906 )
907 self.check_features_used(
908 "with (a, b as c): pass", {Feature.PARENTHESIZED_CONTEXT_MANAGERS}
909 )
910 self.check_features_used(
911 "with (a, (b as c)): pass", {Feature.PARENTHESIZED_CONTEXT_MANAGERS}
912 )
913 self.check_features_used(
914 "with ((a, ((b as c)))): pass", {Feature.PARENTHESIZED_CONTEXT_MANAGERS}
915 )
916 self.check_features_used(
917 "x = t'foo {f'bar'}'", {Feature.T_STRINGS, Feature.F_STRINGS}
918 )
919
920 def check_features_used(self, source: str, expected: set[Feature]) -> None:
921 node = black.lib2to3_parse(source)
922 actual = black.get_features_used(node)
923 msg = f"Expected {expected} but got {actual} for {source!r}"
924 try:
925 self.assertEqual(actual, expected, msg=msg)
926 except AssertionError:
927 DebugVisitor.show(node)
928 raise
929
930 def test_get_features_used_for_future_flags(self) -> None:
931 for src, features in [
932 ("from __future__ import annotations", {Feature.FUTURE_ANNOTATIONS}),
933 (
934 "from __future__ import (other, annotations)",
935 {Feature.FUTURE_ANNOTATIONS},
936 ),
937 ("a = 1 + 2\nfrom something import annotations", set()),
938 ("from __future__ import x, y", set()),
939 ]:
940 with self.subTest(src=src, features=sorted(f.value for f in features)):
941 node = black.lib2to3_parse(src)
942 future_imports = black.get_future_imports(node)
943 self.assertEqual(
944 black.get_features_used(node, future_imports=future_imports),
945 features,
946 )
947
948 def test_get_future_imports(self) -> None:
949 node = black.lib2to3_parse("\n")
950 self.assertEqual(set(), black.get_future_imports(node))
951 node = black.lib2to3_parse("from __future__ import black\n")
952 self.assertEqual({"black"}, black.get_future_imports(node))
953 node = black.lib2to3_parse("from __future__ import multiple, imports\n")
954 self.assertEqual({"multiple", "imports"}, black.get_future_imports(node))
955 node = black.lib2to3_parse("from __future__ import (parenthesized, imports)\n")
956 self.assertEqual({"parenthesized", "imports"}, black.get_future_imports(node))
957 node = black.lib2to3_parse(
958 "from __future__ import multiple\nfrom __future__ import imports\n"
959 )
960 self.assertEqual({"multiple", "imports"}, black.get_future_imports(node))
961 node = black.lib2to3_parse("# comment\nfrom __future__ import black\n")
962 self.assertEqual({"black"}, black.get_future_imports(node))
963 node = black.lib2to3_parse('"""docstring"""\nfrom __future__ import black\n')
964 self.assertEqual({"black"}, black.get_future_imports(node))
965 node = black.lib2to3_parse("some(other, code)\nfrom __future__ import black\n")
966 self.assertEqual(set(), black.get_future_imports(node))
967 node = black.lib2to3_parse("from some.module import black\n")
968 self.assertEqual(set(), black.get_future_imports(node))
969 node = black.lib2to3_parse(
970 "from __future__ import unicode_literals as _unicode_literals"
971 )
972 self.assertEqual({"unicode_literals"}, black.get_future_imports(node))
973 node = black.lib2to3_parse(
974 "from __future__ import unicode_literals as _lol, print"
975 )
976 self.assertEqual({"unicode_literals", "print"}, black.get_future_imports(node))
977
978 @pytest.mark.incompatible_with_mypyc
979 def test_debug_visitor(self) -> None:
980 source, _ = read_data("miscellaneous", "debug_visitor")
981 expected, _ = read_data("miscellaneous", "debug_visitor.out")
982 out_lines = []
983 err_lines = []
984
985 def out(msg: str, **kwargs: Any) -> None:
986 out_lines.append(msg)
987
988 def err(msg: str, **kwargs: Any) -> None:
989 err_lines.append(msg)
990
991 with patch("black.debug.out", out):
992 DebugVisitor.show(source)
993 actual = "\n".join(out_lines) + "\n"
994 log_name = ""
995 if expected != actual:
996 log_name = black.dump_to_file(*out_lines)
997 self.assertEqual(
998 expected,
999 actual,
1000 f"AST print out is different. Actual version dumped to {log_name}",
1001 )
1002
1003 def test_format_file_contents(self) -> None:
1004 mode = DEFAULT_MODE
1005 empty = ""
1006 with self.assertRaises(black.NothingChanged):
1007 black.format_file_contents(empty, mode=mode, fast=False)
1008 just_nl = "\n"
1009 with self.assertRaises(black.NothingChanged):
1010 black.format_file_contents(just_nl, mode=mode, fast=False)
1011 same = "j = [1, 2, 3]\n"
1012 with self.assertRaises(black.NothingChanged):
1013 black.format_file_contents(same, mode=mode, fast=False)
1014 different = "j = [1,2,3]"
1015 expected = same
1016 actual = black.format_file_contents(different, mode=mode, fast=False)
1017 self.assertEqual(expected, actual)
1018 invalid = "return if you can"
1019 with self.assertRaises(black.InvalidInput) as e:
1020 black.format_file_contents(invalid, mode=mode, fast=False)
1021 self.assertEqual(
1022 str(e.exception),
1023 "Cannot parse: 1:7\n"
1024 " return if you can\n"
1025 " ^\n"
1026 "ParseError: bad input",
1027 )
1028 just_crlf = "\r\n"
1029 with self.assertRaises(black.NothingChanged):
1030 black.format_file_contents(just_crlf, mode=mode, fast=False)
1031 just_whitespace_nl = "\n\t\n \n\t \n \t\n\n"
1032 actual = black.format_file_contents(just_whitespace_nl, mode=mode, fast=False)
1033 self.assertEqual("\n", actual)
1034 just_whitespace_crlf = "\r\n\t\r\n \r\n\t \r\n \t\r\n\r\n"
1035 actual = black.format_file_contents(just_whitespace_crlf, mode=mode, fast=False)
1036 self.assertEqual("\r\n", actual)
1037
1038 def test_endmarker(self) -> None:
1039 n = black.lib2to3_parse("\n")
1040 self.assertEqual(n.type, black.syms.file_input)
1041 self.assertEqual(len(n.children), 1)
1042 self.assertEqual(n.children[0].type, black.token.ENDMARKER)
1043
1044 @patch("tests.conftest.PRINT_FULL_TREE", True)
1045 @patch("tests.conftest.PRINT_TREE_DIFF", False)
1046 @pytest.mark.incompatible_with_mypyc
1047 def test_assertFormatEqual_print_full_tree(self) -> None:
1048 out_lines = []
1049 err_lines = []
1050
1051 def out(msg: str, **kwargs: Any) -> None:
1052 out_lines.append(msg)
1053
1054 def err(msg: str, **kwargs: Any) -> None:
1055 err_lines.append(msg)
1056
1057 with patch("black.output._out", out), patch("black.output._err", err):
1058 with self.assertRaises(AssertionError):
1059 self.assertFormatEqual("j = [1, 2, 3]", "j = [1, 2, 3,]")
1060
1061 out_str = "".join(out_lines)
1062 self.assertIn("Expected tree:", out_str)
1063 self.assertIn("Actual tree:", out_str)
1064 self.assertEqual("".join(err_lines), "")
1065
1066 @patch("tests.conftest.PRINT_FULL_TREE", False)
1067 @patch("tests.conftest.PRINT_TREE_DIFF", True)
1068 @pytest.mark.incompatible_with_mypyc
1069 def test_assertFormatEqual_print_tree_diff(self) -> None:
1070 out_lines = []
1071 err_lines = []
1072
1073 def out(msg: str, **kwargs: Any) -> None:
1074 out_lines.append(msg)
1075
1076 def err(msg: str, **kwargs: Any) -> None:
1077 err_lines.append(msg)
1078
1079 with patch("black.output._out", out), patch("black.output._err", err):
1080 with self.assertRaises(AssertionError):
1081 self.assertFormatEqual("j = [1, 2, 3]\n", "j = [1, 2, 3,]\n")
1082
1083 out_str = "".join(out_lines)
1084 self.assertIn("Tree Diff:", out_str)
1085 self.assertIn("+ COMMA", out_str)
1086 self.assertIn("+ ','", out_str)
1087 self.assertEqual("".join(err_lines), "")
1088
1089 @event_loop()
1090 @patch("concurrent.futures.ProcessPoolExecutor", MagicMock(side_effect=OSError))
1091 def test_works_in_mono_process_only_environment(self) -> None:
1092 with cache_dir() as workspace:
1093 for f in [
1094 (workspace / "one.py").resolve(),
1095 (workspace / "two.py").resolve(),
1096 ]:
1097 f.write_text('print("hello")\n', encoding="utf-8")
1098 self.invokeBlack([str(workspace)])
1099
1100 @event_loop()
1101 def test_check_diff_use_together(self) -> None:
1102 with cache_dir():
1103 # Files which will be reformatted.
1104 src1 = get_case_path("miscellaneous", "string_quotes")
1105 self.invokeBlack([str(src1), "--diff", "--check"], exit_code=1)
1106 # Files which will not be reformatted.
1107 src2 = get_case_path("cases", "composition")
1108 self.invokeBlack([str(src2), "--diff", "--check"])
1109 # Multi file command.
1110 self.invokeBlack([str(src1), str(src2), "--diff", "--check"], exit_code=1)
1111
1112 def test_no_src_fails(self) -> None:
1113 with cache_dir():
1114 self.invokeBlack([], exit_code=1)
1115
1116 def test_src_and_code_fails(self) -> None:
1117 with cache_dir():
1118 self.invokeBlack([".", "-c", "0"], exit_code=1)
1119
1120 def test_broken_symlink(self) -> None:
1121 with cache_dir() as workspace:
1122 symlink = workspace / "broken_link.py"
1123 try:
1124 symlink.symlink_to("nonexistent.py")
1125 except (OSError, NotImplementedError) as e:
1126 self.skipTest(f"Can't create symlinks: {e}")
1127 self.invokeBlack([str(workspace.resolve())])
1128
1129 def test_single_file_force_pyi(self) -> None:
1130 pyi_mode = replace(DEFAULT_MODE, is_pyi=True)
1131 contents, expected = read_data("miscellaneous", "force_pyi")
1132 with cache_dir() as workspace:
1133 path = (workspace / "file.py").resolve()
1134 path.write_text(contents, encoding="utf-8")
1135 self.invokeBlack([str(path), "--pyi"])
1136 actual = path.read_text(encoding="utf-8")
1137 # verify cache with --pyi is separate
1138 pyi_cache = black.Cache.read(pyi_mode)
1139 assert not pyi_cache.is_changed(path)
1140 normal_cache = black.Cache.read(DEFAULT_MODE)
1141 assert normal_cache.is_changed(path)
1142 self.assertFormatEqual(expected, actual)
1143 black.assert_equivalent(contents, actual)
1144 black.assert_stable(contents, actual, pyi_mode)
1145
1146 @event_loop()
1147 def test_multi_file_force_pyi(self) -> None:
1148 reg_mode = DEFAULT_MODE
1149 pyi_mode = replace(DEFAULT_MODE, is_pyi=True)
1150 contents, expected = read_data("miscellaneous", "force_pyi")
1151 with cache_dir() as workspace:
1152 paths = [
1153 (workspace / "file1.py").resolve(),
1154 (workspace / "file2.py").resolve(),
1155 ]
1156 for path in paths:
1157 path.write_text(contents, encoding="utf-8")
1158 self.invokeBlack([str(p) for p in paths] + ["--pyi"])
1159 for path in paths:
1160 actual = path.read_text(encoding="utf-8")
1161 self.assertEqual(actual, expected)
1162 # verify cache with --pyi is separate
1163 pyi_cache = black.Cache.read(pyi_mode)
1164 normal_cache = black.Cache.read(reg_mode)
1165 for path in paths:
1166 assert not pyi_cache.is_changed(path)
1167 assert normal_cache.is_changed(path)
1168
1169 def test_pipe_force_pyi(self) -> None:
1170 source, expected = read_data("miscellaneous", "force_pyi")
1171 result = BlackRunner().invoke(
1172 black.main, ["-", "-q", "--pyi"], input=BytesIO(source.encode("utf-8"))
1173 )
1174 self.assertEqual(result.exit_code, 0)
1175 actual = result.output
1176 self.assertFormatEqual(actual, expected)
1177
1178 def test_single_file_force_py36(self) -> None:
1179 reg_mode = DEFAULT_MODE
1180 py36_mode = replace(DEFAULT_MODE, target_versions=PY36_VERSIONS)
1181 source, expected = read_data("miscellaneous", "force_py36")
1182 with cache_dir() as workspace:
1183 path = (workspace / "file.py").resolve()
1184 path.write_text(source, encoding="utf-8")
1185 self.invokeBlack([str(path), *PY36_ARGS])
1186 actual = path.read_text(encoding="utf-8")
1187 # verify cache with --target-version is separate
1188 py36_cache = black.Cache.read(py36_mode)
1189 assert not py36_cache.is_changed(path)
1190 normal_cache = black.Cache.read(reg_mode)
1191 assert normal_cache.is_changed(path)
1192 self.assertEqual(actual, expected)
1193
1194 @event_loop()
1195 def test_multi_file_force_py36(self) -> None:
1196 reg_mode = DEFAULT_MODE
1197 py36_mode = replace(DEFAULT_MODE, target_versions=PY36_VERSIONS)
1198 source, expected = read_data("miscellaneous", "force_py36")
1199 with cache_dir() as workspace:
1200 paths = [
1201 (workspace / "file1.py").resolve(),
1202 (workspace / "file2.py").resolve(),
1203 ]
1204 for path in paths:
1205 path.write_text(source, encoding="utf-8")
1206 self.invokeBlack([str(p) for p in paths] + PY36_ARGS)
1207 for path in paths:
1208 actual = path.read_text(encoding="utf-8")
1209 self.assertEqual(actual, expected)
1210 # verify cache with --target-version is separate
1211 pyi_cache = black.Cache.read(py36_mode)
1212 normal_cache = black.Cache.read(reg_mode)
1213 for path in paths:
1214 assert not pyi_cache.is_changed(path)
1215 assert normal_cache.is_changed(path)
1216
1217 def test_pipe_force_py36(self) -> None:
1218 source, expected = read_data("miscellaneous", "force_py36")
1219 result = BlackRunner().invoke(
1220 black.main,
1221 ["-", "-q", "--target-version=py36"],
1222 input=BytesIO(source.encode("utf-8")),
1223 )
1224 self.assertEqual(result.exit_code, 0)
1225 actual = result.output
1226 self.assertFormatEqual(actual, expected)
1227
1228 @pytest.mark.incompatible_with_mypyc
1229 def test_reformat_one_with_stdin(self) -> None:
1230 with patch(
1231 "black.format_stdin_to_stdout",
1232 return_value=lambda *args, **kwargs: black.Changed.YES,
1233 ) as fsts:
1234 report = MagicMock()
1235 path = Path("-")
1236 black.reformat_one(
1237 path,
1238 fast=True,
1239 write_back=black.WriteBack.YES,
1240 mode=DEFAULT_MODE,
1241 report=report,
1242 )
1243 fsts.assert_called_once()
1244 report.done.assert_called_with(path, black.Changed.YES)
1245
1246 @pytest.mark.incompatible_with_mypyc
1247 def test_reformat_one_with_stdin_filename(self) -> None:
1248 with patch(
1249 "black.format_stdin_to_stdout",
1250 return_value=lambda *args, **kwargs: black.Changed.YES,
1251 ) as fsts:
1252 report = MagicMock()
1253 p = "foo.py"
1254 path = Path(f"__BLACK_STDIN_FILENAME__{p}")
1255 expected = Path(p)
1256 black.reformat_one(
1257 path,
1258 fast=True,
1259 write_back=black.WriteBack.YES,
1260 mode=DEFAULT_MODE,
1261 report=report,
1262 )
1263 fsts.assert_called_once_with(
1264 fast=True, write_back=black.WriteBack.YES, mode=DEFAULT_MODE, lines=()
1265 )
1266 # __BLACK_STDIN_FILENAME__ should have been stripped
1267 report.done.assert_called_with(expected, black.Changed.YES)
1268
1269 @pytest.mark.incompatible_with_mypyc
1270 def test_reformat_one_with_stdin_filename_pyi(self) -> None:
1271 with patch(
1272 "black.format_stdin_to_stdout",
1273 return_value=lambda *args, **kwargs: black.Changed.YES,
1274 ) as fsts:
1275 report = MagicMock()
1276 p = "foo.pyi"
1277 path = Path(f"__BLACK_STDIN_FILENAME__{p}")
1278 expected = Path(p)
1279 black.reformat_one(
1280 path,
1281 fast=True,
1282 write_back=black.WriteBack.YES,
1283 mode=DEFAULT_MODE,
1284 report=report,
1285 )
1286 fsts.assert_called_once_with(
1287 fast=True,
1288 write_back=black.WriteBack.YES,
1289 mode=replace(DEFAULT_MODE, is_pyi=True),
1290 lines=(),
1291 )
1292 # __BLACK_STDIN_FILENAME__ should have been stripped
1293 report.done.assert_called_with(expected, black.Changed.YES)
1294
1295 @pytest.mark.incompatible_with_mypyc
1296 def test_reformat_one_with_stdin_filename_ipynb(self) -> None:
1297 with patch(
1298 "black.format_stdin_to_stdout",
1299 return_value=lambda *args, **kwargs: black.Changed.YES,
1300 ) as fsts:
1301 report = MagicMock()
1302 p = "foo.ipynb"
1303 path = Path(f"__BLACK_STDIN_FILENAME__{p}")
1304 expected = Path(p)
1305 black.reformat_one(
1306 path,
1307 fast=True,
1308 write_back=black.WriteBack.YES,
1309 mode=DEFAULT_MODE,
1310 report=report,
1311 )
1312 fsts.assert_called_once_with(
1313 fast=True,
1314 write_back=black.WriteBack.YES,
1315 mode=replace(DEFAULT_MODE, is_ipynb=True),
1316 lines=(),
1317 )
1318 # __BLACK_STDIN_FILENAME__ should have been stripped
1319 report.done.assert_called_with(expected, black.Changed.YES)
1320
1321 @pytest.mark.incompatible_with_mypyc
1322 def test_reformat_one_with_stdin_and_existing_path(self) -> None:
1323 with patch(
1324 "black.format_stdin_to_stdout",
1325 return_value=lambda *args, **kwargs: black.Changed.YES,
1326 ) as fsts:
1327 report = MagicMock()
1328 # Even with an existing file, since we are forcing stdin, black
1329 # should output to stdout and not modify the file inplace
1330 p = THIS_DIR / "data" / "cases" / "collections.py"
1331 # Make sure is_file actually returns True
1332 self.assertTrue(p.is_file())
1333 path = Path(f"__BLACK_STDIN_FILENAME__{p}")
1334 expected = Path(p)
1335 black.reformat_one(
1336 path,
1337 fast=True,
1338 write_back=black.WriteBack.YES,
1339 mode=DEFAULT_MODE,
1340 report=report,
1341 )
1342 fsts.assert_called_once()
1343 # __BLACK_STDIN_FILENAME__ should have been stripped
1344 report.done.assert_called_with(expected, black.Changed.YES)
1345
1346 def test_reformat_one_with_stdin_empty(self) -> None:
1347 cases = [
1348 ("", ""),
1349 ("\n", "\n"),
1350 ("\r\n", "\r\n"),
1351 (" \t", ""),
1352 (" \t\n\t ", "\n"),
1353 (" \t\r\n\t ", "\r\n"),
1354 ]
1355
1356 def _new_wrapper(
1357 output: io.StringIO, io_TextIOWrapper: type[io.TextIOWrapper]
1358 ) -> Callable[[Any, Any], io.StringIO | io.TextIOWrapper]:
1359 def get_output(*args: Any, **kwargs: Any) -> io.StringIO | io.TextIOWrapper:
1360 if args == (sys.stdout.buffer,):
1361 # It's `format_stdin_to_stdout()` calling `io.TextIOWrapper()`,
1362 # return our mock object.
1363 return output
1364 # It's something else (i.e. `decode_bytes()`) calling
1365 # `io.TextIOWrapper()`, pass through to the original implementation.
1366 # See discussion in https://github.com/psf/black/pull/2489
1367 return io_TextIOWrapper(*args, **kwargs)
1368
1369 return get_output
1370
1371 for content, expected in cases:
1372 output = io.StringIO()
1373 io_TextIOWrapper = io.TextIOWrapper
1374
1375 with patch("io.TextIOWrapper", _new_wrapper(output, io_TextIOWrapper)):
1376 try:
1377 black.format_stdin_to_stdout(
1378 fast=True,
1379 content=content,
1380 write_back=black.WriteBack.YES,
1381 mode=DEFAULT_MODE,
1382 )
1383 except io.UnsupportedOperation:
1384 pass # StringIO does not support detach
1385 assert output.getvalue() == expected
1386
1387 def test_cli_unstable(self) -> None:
1388 self.invokeBlack(["--unstable", "-c", "0"], exit_code=0)
1389 self.invokeBlack(["--preview", "-c", "0"], exit_code=0)
1390 # Must also pass --preview
1391 self.invokeBlack(
1392 ["--enable-unstable-feature", "string_processing", "-c", "0"], exit_code=1
1393 )
1394 self.invokeBlack(
1395 ["--preview", "--enable-unstable-feature", "string_processing", "-c", "0"],
1396 exit_code=0,
1397 )
1398 self.invokeBlack(
1399 ["--unstable", "--enable-unstable-feature", "string_processing", "-c", "0"],
1400 exit_code=0,
1401 )
1402
1403 def test_invalid_cli_regex(self) -> None:
1404 for option in ["--include", "--exclude", "--extend-exclude", "--force-exclude"]:
1405 self.invokeBlack(["-", option, "**()(!!*)"], exit_code=2)
1406
1407 def test_required_version_matches_version(self) -> None:
1408 self.invokeBlack(
1409 ["--required-version", black.__version__, "-c", "0"],
1410 exit_code=0,
1411 ignore_config=True,
1412 )
1413
1414 def test_required_version_matches_partial_version(self) -> None:
1415 self.invokeBlack(
1416 ["--required-version", black.__version__.split(".")[0], "-c", "0"],
1417 exit_code=0,
1418 ignore_config=True,
1419 )
1420
1421 def test_required_version_does_not_match_on_minor_version(self) -> None:
1422 self.invokeBlack(
1423 ["--required-version", black.__version__.split(".")[0] + ".999", "-c", "0"],
1424 exit_code=1,
1425 ignore_config=True,
1426 )
1427
1428 def test_required_version_does_not_match_version(self) -> None:
1429 result = BlackRunner().invoke(
1430 black.main,
1431 ["--required-version", "20.99b", "-c", "0"],
1432 )
1433 self.assertEqual(result.exit_code, 1)
1434 self.assertIn("required version", result.stderr)
1435
1436 def test_preserves_line_endings(self) -> None:
1437 with TemporaryDirectory() as workspace:
1438 test_file = Path(workspace) / "test.py"
1439 for nl in ["\n", "\r\n"]:
1440 contents = nl.join(["def f( ):", " pass"])
1441 test_file.write_bytes(contents.encode())
1442 ff(test_file, write_back=black.WriteBack.YES)
1443 updated_contents: bytes = test_file.read_bytes()
1444 self.assertIn(nl.encode(), updated_contents)
1445 if nl == "\n":
1446 self.assertNotIn(b"\r\n", updated_contents)
1447
1448 def test_preserves_line_endings_via_stdin(self) -> None:
1449 for nl in ["\n", "\r\n"]:
1450 contents = nl.join(["def f( ):", " pass"])
1451 runner = BlackRunner()
1452 result = runner.invoke(
1453 black.main, ["-", "--fast"], input=BytesIO(contents.encode("utf-8"))
1454 )
1455 self.assertEqual(result.exit_code, 0)
1456 output = result.stdout_bytes
1457 self.assertIn(nl.encode("utf-8"), output)
1458 if nl == "\n":
1459 self.assertNotIn(b"\r\n", output)
1460
1461 def test_normalize_line_endings(self) -> None:
1462 with TemporaryDirectory() as workspace:
1463 test_file = Path(workspace) / "test.py"
1464 for data, expected in (
1465 (b"c\r\nc\n ", b"c\r\nc\r\n"),
1466 (b"l\nl\r\n ", b"l\nl\n"),
1467 ):
1468 test_file.write_bytes(data)
1469 ff(test_file, write_back=black.WriteBack.YES)
1470 self.assertEqual(test_file.read_bytes(), expected)
1471
1472 def test_root_logger_not_used_directly(self) -> None:
1473 def fail(*args: Any, **kwargs: Any) -> None:
1474 self.fail("Record created with root logger")
1475
1476 with patch.multiple(
1477 logging.root,
1478 debug=fail,
1479 info=fail,
1480 warning=fail,
1481 error=fail,
1482 critical=fail,
1483 log=fail,
1484 ):
1485 ff(THIS_DIR / "util.py")
1486
1487 def test_invalid_config_return_code(self) -> None:
1488 tmp_file = Path(black.dump_to_file())
1489 try:
1490 tmp_config = Path(black.dump_to_file())
1491 tmp_config.unlink()
1492 args = ["--config", str(tmp_config), str(tmp_file)]
1493 self.invokeBlack(args, exit_code=2, ignore_config=False)
1494 finally:
1495 tmp_file.unlink()
1496
1497 def test_parse_pyproject_toml(self) -> None:
1498 test_toml_file = THIS_DIR / "test.toml"
1499 config = black.parse_pyproject_toml(str(test_toml_file))
1500 self.assertEqual(config["verbose"], 1)
1501 self.assertEqual(config["check"], "no")
1502 self.assertEqual(config["diff"], "y")
1503 self.assertEqual(config["color"], True)
1504 self.assertEqual(config["line_length"], 79)
1505 self.assertEqual(config["target_version"], ["py36", "py37", "py38"])
1506 self.assertEqual(config["python_cell_magics"], ["custom1", "custom2"])
1507 self.assertEqual(config["exclude"], r"\.pyi?$")
1508 self.assertEqual(config["include"], r"\.py?$")
1509
1510 def test_spellcheck_pyproject_toml(self) -> None:
1511 test_toml_file = THIS_DIR / "data" / "incorrect_spelling.toml"
1512 result = BlackRunner().invoke(
1513 black.main,
1514 [
1515 "--code=print('hello world')",
1516 "--verbose",
1517 f"--config={str(test_toml_file)}",
1518 ],
1519 )
1520
1521 assert (
1522 r"Invalid config keys detected: 'ine_length', 'target_ersion' (in"
1523 rf" {test_toml_file})" in result.stderr
1524 )
1525
1526 def test_parse_pyproject_toml_project_metadata(self) -> None:
1527 for test_toml, expected in [
1528 ("only_black_pyproject.toml", ["py310"]),
1529 ("only_metadata_pyproject.toml", ["py37", "py38", "py39", "py310"]),
1530 ("neither_pyproject.toml", None),
1531 ("both_pyproject.toml", ["py310"]),
1532 ]:
1533 test_toml_file = THIS_DIR / "data" / "project_metadata" / test_toml
1534 config = black.parse_pyproject_toml(str(test_toml_file))
1535 self.assertEqual(config.get("target_version"), expected)
1536
1537 def test_infer_target_version(self) -> None:
1538 for version, expected in [
1539 ("3.6", [TargetVersion.PY36]),
1540 ("3.11.0rc1", [TargetVersion.PY311]),
1541 (
1542 ">=3.10",
1543 [
1544 TargetVersion.PY310,
1545 TargetVersion.PY311,
1546 TargetVersion.PY312,
1547 TargetVersion.PY313,
1548 TargetVersion.PY314,
1549 TargetVersion.PY315,
1550 ],
1551 ),
1552 (
1553 ">=3.10.6",
1554 [
1555 TargetVersion.PY310,
1556 TargetVersion.PY311,
1557 TargetVersion.PY312,
1558 TargetVersion.PY313,
1559 TargetVersion.PY314,
1560 TargetVersion.PY315,
1561 ],
1562 ),
1563 ("<3.6", [TargetVersion.PY33, TargetVersion.PY34, TargetVersion.PY35]),
1564 (">3.7,<3.10", [TargetVersion.PY38, TargetVersion.PY39]),
1565 (
1566 ">3.7,!=3.8,!=3.9",
1567 [
1568 TargetVersion.PY310,
1569 TargetVersion.PY311,
1570 TargetVersion.PY312,
1571 TargetVersion.PY313,
1572 TargetVersion.PY314,
1573 TargetVersion.PY315,
1574 ],
1575 ),
1576 (
1577 "> 3.9.4, != 3.10.3",
1578 [
1579 TargetVersion.PY39,
1580 TargetVersion.PY310,
1581 TargetVersion.PY311,
1582 TargetVersion.PY312,
1583 TargetVersion.PY313,
1584 TargetVersion.PY314,
1585 TargetVersion.PY315,
1586 ],
1587 ),
1588 (
1589 "!=3.3,!=3.4",
1590 [
1591 TargetVersion.PY35,
1592 TargetVersion.PY36,
1593 TargetVersion.PY37,
1594 TargetVersion.PY38,
1595 TargetVersion.PY39,
1596 TargetVersion.PY310,
1597 TargetVersion.PY311,
1598 TargetVersion.PY312,
1599 TargetVersion.PY313,
1600 TargetVersion.PY314,
1601 TargetVersion.PY315,
1602 ],
1603 ),
1604 (
1605 "==3.*",
1606 [
1607 TargetVersion.PY33,
1608 TargetVersion.PY34,
1609 TargetVersion.PY35,
1610 TargetVersion.PY36,
1611 TargetVersion.PY37,
1612 TargetVersion.PY38,
1613 TargetVersion.PY39,
1614 TargetVersion.PY310,
1615 TargetVersion.PY311,
1616 TargetVersion.PY312,
1617 TargetVersion.PY313,
1618 TargetVersion.PY314,
1619 TargetVersion.PY315,
1620 ],
1621 ),
1622 ("==3.8.*", [TargetVersion.PY38]),
1623 (None, None),
1624 ("", None),
1625 ("invalid", None),
1626 ("==invalid", None),
1627 (">3.9,!=invalid", None),
1628 ("3", None),
1629 ("3.2", None),
1630 ("2.7.18", None),
1631 ("==2.7", None),
1632 (">3.10,<3.11", None),
1633 ]:
1634 test_toml = {"project": {"requires-python": version}}
1635 result = black.files.infer_target_version(test_toml)
1636 self.assertEqual(result, expected)
1637
1638 def test_read_pyproject_toml(self) -> None:
1639 test_toml_file = THIS_DIR / "test.toml"
1640 fake_ctx = FakeContext()
1641 black.read_pyproject_toml(fake_ctx, None, str(test_toml_file))
1642 config = fake_ctx.default_map
1643 self.assertEqual(config["verbose"], "1")
1644 self.assertEqual(config["check"], "no")
1645 self.assertEqual(config["diff"], "y")
1646 self.assertEqual(config["color"], "True")
1647 self.assertEqual(config["line_length"], "79")
1648 self.assertEqual(config["target_version"], ["py36", "py37", "py38"])
1649 self.assertEqual(config["exclude"], r"\.pyi?$")
1650 self.assertEqual(config["include"], r"\.py?$")
1651
1652 def test_read_pyproject_toml_from_stdin(self) -> None:
1653 with TemporaryDirectory() as workspace:
1654 root = Path(workspace)
1655
1656 src_dir = root / "src"
1657 src_dir.mkdir()
1658
1659 src_pyproject = src_dir / "pyproject.toml"
1660 src_pyproject.touch()
1661
1662 test_toml_content = (THIS_DIR / "test.toml").read_text(encoding="utf-8")
1663 src_pyproject.write_text(test_toml_content, encoding="utf-8")
1664
1665 src_python = src_dir / "foo.py"
1666 src_python.touch()
1667
1668 fake_ctx = FakeContext()
1669 fake_ctx.params["src"] = ("-",)
1670 fake_ctx.params["stdin_filename"] = str(src_python)
1671
1672 with change_directory(root):
1673 black.read_pyproject_toml(fake_ctx, None, None)
1674
1675 config = fake_ctx.default_map
1676 self.assertEqual(config["verbose"], "1")
1677 self.assertEqual(config["check"], "no")
1678 self.assertEqual(config["diff"], "y")
1679 self.assertEqual(config["color"], "True")
1680 self.assertEqual(config["line_length"], "79")
1681 self.assertEqual(config["target_version"], ["py36", "py37", "py38"])
1682 self.assertEqual(config["exclude"], r"\.pyi?$")
1683 self.assertEqual(config["include"], r"\.py?$")
1684
1685 @pytest.mark.incompatible_with_mypyc
1686 def test_find_project_root(self) -> None:
1687 with TemporaryDirectory() as workspace:
1688 root = Path(workspace)
1689 test_dir = root / "test"
1690 test_dir.mkdir()
1691
1692 src_dir = root / "src"
1693 src_dir.mkdir()
1694
1695 root_pyproject = root / "pyproject.toml"
1696 root_pyproject.write_text("[tool.black]", encoding="utf-8")
1697 src_pyproject = src_dir / "pyproject.toml"
1698 src_pyproject.write_text("[tool.black]", encoding="utf-8")
1699 src_python = src_dir / "foo.py"
1700 src_python.touch()
1701
1702 self.assertEqual(
1703 black.find_project_root((src_dir, test_dir)),
1704 (root.resolve(), "pyproject.toml"),
1705 )
1706 self.assertEqual(
1707 black.find_project_root((src_dir,)),
1708 (src_dir.resolve(), "pyproject.toml"),
1709 )
1710 self.assertEqual(
1711 black.find_project_root((src_python,)),
1712 (src_dir.resolve(), "pyproject.toml"),
1713 )
1714
1715 with change_directory(test_dir):
1716 self.assertEqual(
1717 black.find_project_root(("-",), stdin_filename="../src/a.py"),
1718 (src_dir.resolve(), "pyproject.toml"),
1719 )
1720
1721 src_sub = src_dir / "sub"
1722 src_sub.mkdir()
1723
1724 src_sub_pyproject = src_sub / "pyproject.toml"
1725 src_sub_pyproject.touch() # empty
1726
1727 src_sub_python = src_sub / "bar.py"
1728
1729 # we skip src_sub_pyproject since it is missing the [tool.black] section
1730 self.assertEqual(
1731 black.find_project_root((src_sub_python,)),
1732 (src_dir.resolve(), "pyproject.toml"),
1733 )
1734
1735 @patch(
1736 "black.files.find_user_pyproject_toml",
1737 )
1738 def test_find_pyproject_toml(self, find_user_pyproject_toml: MagicMock) -> None:
1739 find_user_pyproject_toml.side_effect = RuntimeError()
1740
1741 with redirect_stderr(io.StringIO()) as stderr:
1742 result = black.files.find_pyproject_toml(
1743 path_search_start=(str(Path.cwd().root),)
1744 )
1745
1746 assert result is None
1747 err = stderr.getvalue()
1748 assert "Ignoring user configuration" in err
1749
1750 @patch(
1751 "black.files.find_user_pyproject_toml",
1752 black.files.find_user_pyproject_toml.__wrapped__,
1753 )
1754 def test_find_user_pyproject_toml_linux(self) -> None:
1755 if system() == "Windows":
1756 return
1757
1758 # Test if XDG_CONFIG_HOME is checked
1759 with TemporaryDirectory() as workspace:
1760 tmp_user_config = Path(workspace) / "black"
1761 with patch.dict("os.environ", {"XDG_CONFIG_HOME": workspace}):
1762 self.assertEqual(
1763 black.files.find_user_pyproject_toml(), tmp_user_config.resolve()
1764 )
1765
1766 # Test fallback for XDG_CONFIG_HOME
1767 with patch.dict("os.environ"):
1768 os.environ.pop("XDG_CONFIG_HOME", None)
1769 fallback_user_config = Path("~/.config").expanduser() / "black"
1770 self.assertEqual(
1771 black.files.find_user_pyproject_toml(), fallback_user_config.resolve()
1772 )
1773
1774 def test_find_user_pyproject_toml_windows(self) -> None:
1775 if system() != "Windows":
1776 return
1777
1778 user_config_path = Path.home() / ".black"
1779 self.assertEqual(
1780 black.files.find_user_pyproject_toml(), user_config_path.resolve()
1781 )
1782
1783 def test_bpo_33660_workaround(self) -> None:
1784 if system() == "Windows":
1785 return
1786
1787 root = Path("/")
1788 path = Path("workspace") / "project"
1789 report = black.Report(verbose=True)
1790 resolves_outside = black.resolves_outside_root_or_cannot_stat(
1791 path, root, report
1792 )
1793 self.assertIs(resolves_outside, False)
1794
1795 def test_normalize_path_ignore_windows_junctions_outside_of_root(self) -> None:
1796 if system() != "Windows":
1797 return
1798
1799 with TemporaryDirectory() as workspace:
1800 root = Path(workspace)
1801 junction_dir = root / "junction"
1802 junction_target_outside_of_root = root / ".."
1803 os.system(f"mklink /J {junction_dir} {junction_target_outside_of_root}")
1804
1805 report = black.Report(verbose=True)
1806 resolves_outside = black.resolves_outside_root_or_cannot_stat(
1807 junction_dir, root, report
1808 )
1809 # Manually delete for Python < 3.8
1810 os.system(f"rmdir {junction_dir}")
1811
1812 self.assertIs(resolves_outside, True)
1813
1814 def test_newline_comment_interaction(self) -> None:
1815 source = "class A:\\\r\n# type: ignore\n pass\n"
1816 output = black.format_str(source, mode=DEFAULT_MODE)
1817 black.assert_stable(source, output, mode=DEFAULT_MODE)
1818
1819 def test_bpo_2142_workaround(self) -> None:
1820 # https://bugs.python.org/issue2142
1821
1822 source, _ = read_data("miscellaneous", "missing_final_newline")
1823 # read_data adds a trailing newline
1824 source = source.rstrip()
1825 expected, _ = read_data("miscellaneous", "missing_final_newline.diff")
1826 tmp_file = Path(black.dump_to_file(source, ensure_final_newline=False))
1827 diff_header = re.compile(
1828 rf"{re.escape(str(tmp_file))}\t\d\d\d\d-\d\d-\d\d "
1829 r"\d\d:\d\d:\d\d\.\d\d\d\d\d\d\+\d\d:\d\d"
1830 )
1831 try:
1832 result = BlackRunner().invoke(black.main, ["--diff", str(tmp_file)])
1833 self.assertEqual(result.exit_code, 0)
1834 finally:
1835 os.unlink(tmp_file)
1836 actual = result.stdout
1837 actual = diff_header.sub(DETERMINISTIC_HEADER, actual)
1838 self.assertEqual(actual, expected)
1839
1840 @staticmethod
1841 def compare_results(
1842 result: click.testing.Result, expected_value: str, expected_exit_code: int
1843 ) -> None:
1844 """Helper method to test the value and exit code of a click Result."""
1845 assert (
1846 result.stdout == expected_value
1847 ), "The output did not match the expected value."
1848 assert result.exit_code == expected_exit_code, "The exit code is incorrect."
1849
1850 def test_code_option(self) -> None:
1851 """Test the code option with no changes."""
1852 code = 'print("Hello world")\n'
1853 args = ["--code", code]
1854 result = BlackRunner().invoke(black.main, args)
1855
1856 self.compare_results(result, code, 0)
1857
1858 def test_code_option_changed(self) -> None:
1859 """Test the code option when changes are required."""
1860 code = "print('hello world')"
1861 formatted = black.format_str(code, mode=DEFAULT_MODE)
1862
1863 args = ["--code", code]
1864 result = BlackRunner().invoke(black.main, args)
1865
1866 self.compare_results(result, formatted, 0)
1867
1868 def test_code_option_check(self) -> None:
1869 """Test the code option when check is passed."""
1870 args = ["--check", "--code", 'print("Hello world")\n']
1871 result = BlackRunner().invoke(black.main, args)
1872 self.compare_results(result, "", 0)
1873
1874 def test_code_option_check_changed(self) -> None:
1875 """Test the code option when changes are required, and check is passed."""
1876 args = ["--check", "--code", "print('hello world')"]
1877 result = BlackRunner().invoke(black.main, args)
1878 self.compare_results(result, "", 1)
1879
1880 def test_code_option_diff(self) -> None:
1881 """Test the code option when diff is passed."""
1882 code = "print('hello world')"
1883 formatted = black.format_str(code, mode=DEFAULT_MODE)
1884 result_diff = diff(code, formatted, "STDIN", "STDOUT")
1885
1886 args = ["--diff", "--code", code]
1887 result = BlackRunner().invoke(black.main, args)
1888
1889 # Remove time from diff
1890 output = DIFF_TIME.sub("", result.output)
1891
1892 assert output == result_diff, "The output did not match the expected value."
1893 assert result.exit_code == 0, "The exit code is incorrect."
1894
1895 def test_code_option_color_diff(self) -> None:
1896 """Test the code option when color and diff are passed."""
1897 code = "print('hello world')"
1898 formatted = black.format_str(code, mode=DEFAULT_MODE)
1899
1900 result_diff = diff(code, formatted, "STDIN", "STDOUT")
1901 result_diff = color_diff(result_diff)
1902
1903 args = ["--diff", "--color", "--code", code]
1904 result = BlackRunner().invoke(black.main, args)
1905
1906 # Remove time from diff
1907 output = DIFF_TIME.sub("", result.output)
1908
1909 assert output == result_diff, "The output did not match the expected value."
1910 assert result.exit_code == 0, "The exit code is incorrect."
1911
1912 @pytest.mark.incompatible_with_mypyc
1913 def test_code_option_safe(self) -> None:
1914 """Test that the code option throws an error when the sanity checks fail."""
1915 # Patch black.assert_equivalent to ensure the sanity checks fail
1916 with patch.object(black, "assert_equivalent", side_effect=AssertionError):
1917 code = 'print("Hello world")'
1918 error_msg = f"{code}\nerror: cannot format <string>: \n"
1919
1920 args = ["--safe", "--code", code]
1921 result = BlackRunner().invoke(black.main, args)
1922
1923 assert error_msg == result.output
1924 assert result.exit_code == 123
1925
1926 def test_code_option_fast(self) -> None:
1927 """Test that the code option ignores errors when the sanity checks fail."""
1928 # Patch black.assert_equivalent to ensure the sanity checks fail
1929 with patch.object(black, "assert_equivalent", side_effect=AssertionError):
1930 code = 'print("Hello world")'
1931 formatted = black.format_str(code, mode=DEFAULT_MODE)
1932
1933 args = ["--fast", "--code", code]
1934 result = BlackRunner().invoke(black.main, args)
1935
1936 self.compare_results(result, formatted, 0)
1937
1938 @pytest.mark.incompatible_with_mypyc
1939 def test_code_option_config(self) -> None:
1940 """
1941 Test that the code option finds the pyproject.toml in the current directory.
1942 """
1943 with patch.object(black, "parse_pyproject_toml", return_value={}) as parse:
1944 args = ["--code", "print"]
1945 # This is the only directory known to contain a pyproject.toml
1946 with change_directory(PROJECT_ROOT):
1947 BlackRunner().invoke(black.main, args)
1948 pyproject_path = Path(Path.cwd(), "pyproject.toml").resolve()
1949
1950 assert (
1951 len(parse.mock_calls) >= 1
1952 ), "Expected config parse to be called with the current directory."
1953
1954 _, call_args, _ = parse.mock_calls[0]
1955 assert (
1956 call_args[0].lower() == str(pyproject_path).lower()
1957 ), "Incorrect config loaded."
1958
1959 @pytest.mark.incompatible_with_mypyc
1960 def test_code_option_parent_config(self) -> None:
1961 """
1962 Test that the code option finds the pyproject.toml in the parent directory.
1963 """
1964 with patch.object(black, "parse_pyproject_toml", return_value={}) as parse:
1965 with change_directory(THIS_DIR):
1966 args = ["--code", "print"]
1967 BlackRunner().invoke(black.main, args)
1968
1969 pyproject_path = Path(Path().cwd().parent, "pyproject.toml").resolve()
1970 assert (
1971 len(parse.mock_calls) >= 1
1972 ), "Expected config parse to be called with the current directory."
1973
1974 _, call_args, _ = parse.mock_calls[0]
1975 assert (
1976 call_args[0].lower() == str(pyproject_path).lower()
1977 ), "Incorrect config loaded."
1978
1979 def test_for_handled_unexpected_eof_error(self) -> None:
1980 """
1981 Test that an unexpected EOF SyntaxError is nicely presented.
1982 """
1983 with pytest.raises(black.parsing.InvalidInput) as exc_info:
1984 black.lib2to3_parse("print(", {})
1985
1986 exc_info.match(
1987 re.escape(
1988 "Cannot parse: 1:6\n"
1989 " print(\n"
1990 " ^\n"
1991 "TokenError: Unexpected EOF in multi-line statement"
1992 )
1993 )
1994
1995 def test_line_ranges_with_code_option(self) -> None:
1996 code = textwrap.dedent("""\
1997 if a == b:
1998 print ( "OK" )
1999 """)
2000 args = ["--line-ranges=1-1", "--code", code]
2001 result = BlackRunner().invoke(black.main, args)
2002
2003 expected = textwrap.dedent("""\
2004 if a == b:
2005 print ( "OK" )
2006 """)
2007 self.compare_results(result, expected, expected_exit_code=0)
2008
2009 def test_line_ranges_with_stdin(self) -> None:
2010 code = textwrap.dedent("""\
2011 if a == b:
2012 print ( "OK" )
2013 """)
2014 runner = BlackRunner()
2015 result = runner.invoke(
2016 black.main, ["--line-ranges=1-1", "-"], input=BytesIO(code.encode("utf-8"))
2017 )
2018
2019 expected = textwrap.dedent("""\
2020 if a == b:
2021 print ( "OK" )
2022 """)
2023 self.compare_results(result, expected, expected_exit_code=0)
2024
2025 def test_line_ranges_with_source(self) -> None:
2026 with TemporaryDirectory() as workspace:
2027 test_file = Path(workspace) / "test.py"
2028 test_file.write_text(
2029 textwrap.dedent("""\
2030 if a == b:
2031 print ( "OK" )
2032 """),
2033 encoding="utf-8",
2034 )
2035 args = ["--line-ranges=1-1", str(test_file)]
2036 result = BlackRunner().invoke(black.main, args)
2037 assert not result.exit_code
2038
2039 formatted = test_file.read_text(encoding="utf-8")
2040 expected = textwrap.dedent("""\
2041 if a == b:
2042 print ( "OK" )
2043 """)
2044 assert expected == formatted
2045
2046 def test_line_ranges_with_multiple_sources(self) -> None:
2047 with TemporaryDirectory() as workspace:
2048 test1_file = Path(workspace) / "test1.py"
2049 test1_file.write_text("", encoding="utf-8")
2050 test2_file = Path(workspace) / "test2.py"
2051 test2_file.write_text("", encoding="utf-8")
2052 args = ["--line-ranges=1-1", str(test1_file), str(test2_file)]
2053 result = BlackRunner().invoke(black.main, args)
2054 assert result.exit_code == 1
2055 assert result.stderr_bytes is not None
2056 assert (
2057 "Cannot use --line-ranges to format multiple files"
2058 in result.stderr_bytes.decode()
2059 )
2060
2061 def test_line_ranges_with_ipynb(self) -> None:
2062 with TemporaryDirectory() as workspace:
2063 test_file = Path(workspace) / "test.ipynb"
2064 test_file.write_text("{}", encoding="utf-8")
2065 args = ["--line-ranges=1-1", "--ipynb", str(test_file)]
2066 result = BlackRunner().invoke(black.main, args)
2067 assert result.stderr_bytes is not None
2068 assert (
2069 "Cannot use --line-ranges with ipynb files"
2070 in result.stderr_bytes.decode()
2071 )
2072 assert result.exit_code == 1
2073
2074 def test_line_ranges_in_pyproject_toml(self) -> None:
2075 config = THIS_DIR / "data" / "invalid_line_ranges.toml"
2076 result = BlackRunner().invoke(
2077 black.main, ["--code", "print()", "--config", str(config)]
2078 )
2079 assert result.exit_code == 2
2080 assert result.stderr_bytes is not None
2081 assert (
2082 b"Cannot use line-ranges in the pyproject.toml file." in result.stderr_bytes
2083 )
2084
2085 def test_lines_with_leading_tabs_expanded(self) -> None:
2086 # See CVE-2024-21503. Mostly test that this completes in a reasonable
2087 # time.
2088 payload = "\t" * 10_000
2089 assert lines_with_leading_tabs_expanded(payload) == [payload]
2090
2091 tab = " " * 8
2092 assert lines_with_leading_tabs_expanded("\tx") == [f"{tab}x"]
2093 assert lines_with_leading_tabs_expanded("\t\tx") == [f"{tab}{tab}x"]
2094 assert lines_with_leading_tabs_expanded("\tx\n y") == [f"{tab}x", " y"]
2095
2096 def test_carriage_return_edge_cases(self) -> None:
2097 # These tests are here instead of in the normal cases because
2098 # of git's newline normalization and because it's hard to
2099 # get `\r` vs `\r\n` vs `\n` to display properly
2100 assert (
2101 black.format_str(
2102 "try:\\\r# type: ignore\n pass\nfinally:\n pass\n",
2103 mode=black.FileMode(),
2104 )
2105 == "try: # type: ignore\r pass\rfinally:\r pass\r"
2106 )
2107 assert black.format_str("{\r}", mode=black.FileMode()) == "{}\r"
2108 assert black.format_str("pass #\r#\n", mode=black.FileMode()) == "pass #\r#\r"
2109
2110 assert black.format_str("x=\\\r\n1", mode=black.FileMode()) == "x = 1\r\n"
2111 assert black.format_str("x=\\\n1", mode=black.FileMode()) == "x = 1\n"
2112 assert black.format_str("x=\\\r1", mode=black.FileMode()) == "x = 1\r"
2113 assert (
2114 black.format_str("class A\\\r\n:...", mode=black.FileMode())
2115 == "class A: ...\r\n"
2116 )
2117 assert (
2118 black.format_str("class A\\\n:...", mode=black.FileMode())
2119 == "class A: ...\n"
2120 )
2121 assert (
2122 black.format_str("class A\\\r:...", mode=black.FileMode())
2123 == "class A: ...\r"
2124 )
2125
2126 def test_newline_type_detection(self) -> None:
2127 mode = Mode()
2128 newline_types = ["A\n", "A\r\n", "A\r"]
2129 for test_case in itertools.permutations(newline_types):
2130 assert black.format_str("".join(test_case), mode=mode) == test_case[0] * 3
2131
2132 def test_decode_with_encoding(self) -> None:
2133 # This uses temporary files since some editors (including GitHub)
2134 # struggle with displaying and/or editing non utf-8 data
2135 # \xfc is iso-8859-1 for ü
2136 with NamedTemporaryFile(delete=False) as first_line:
2137 first_line.write(
2138 b"# -*- coding: iso-8859-1 -*-\n"
2139 b"# 2002-11-22 J\xfcrgen Hermann <[email protected]>\n"
2140 )
2141 first_line.close()
2142 self.assertFalse(
2143 ff(Path(first_line.name)),
2144 "Failed to properly detect encoding",
2145 )
2146
2147 with NamedTemporaryFile(delete=False) as second_line:
2148 second_line.write(
2149 b"#! /usr/bin/env python3\n"
2150 b"# -*- coding: iso-8859-1 -*-\n"
2151 b"# 2002-11-22 J\xfcrgen Hermann <[email protected]>\n"
2152 )
2153 second_line.close()
2154 self.assertFalse(
2155 ff(Path(second_line.name)),
2156 "Failed to properly detect encoding on second line",
2157 )
2158
2159
2160 class TestCaching:
2161 def test_get_cache_dir(
2162 self,
2163 tmp_path: Path,
2164 monkeypatch: pytest.MonkeyPatch,
2165 ) -> None:
2166 # Create multiple cache directories
2167 workspace1 = tmp_path / "ws1"
2168 workspace1.mkdir()
2169 workspace2 = tmp_path / "ws2"
2170 workspace2.mkdir()
2171
2172 # Force user_cache_dir to use the temporary directory for easier assertions
2173 patch_user_cache_dir = patch(
2174 target="black.cache.user_cache_dir",
2175 autospec=True,
2176 return_value=str(workspace1),
2177 )
2178
2179 # If BLACK_CACHE_DIR is not set, use user_cache_dir
2180 monkeypatch.delenv("BLACK_CACHE_DIR", raising=False)
2181 with patch_user_cache_dir:
2182 assert get_cache_dir().parent == workspace1
2183
2184 # If it is set, use the path provided in the env var.
2185 monkeypatch.setenv("BLACK_CACHE_DIR", str(workspace2))
2186 assert get_cache_dir().parent == workspace2
2187
2188 def test_cache_file_length(self) -> None:
2189 cases = [
2190 DEFAULT_MODE,
2191 # all of the target versions
2192 Mode(target_versions=set(TargetVersion)),
2193 # all of the features
2194 Mode(enabled_features=set(Preview)),
2195 # all of the magics
2196 Mode(python_cell_magics={f"magic{i}" for i in range(500)}),
2197 # all of the things
2198 Mode(
2199 target_versions=set(TargetVersion),
2200 enabled_features=set(Preview),
2201 python_cell_magics={f"magic{i}" for i in range(500)},
2202 ),
2203 ]
2204 for case in cases:
2205 cache_file = get_cache_file(case)
2206 # Some common file systems enforce a maximum path length
2207 # of 143 (issue #4174). We can't do anything if the directory
2208 # path is too long, but ensure the name of the cache file itself
2209 # doesn't get too crazy.
2210 assert len(cache_file.name) <= 96
2211
2212 def test_cache_file_path_ignores_python_cell_magic_separators(self) -> None:
2213 mode = replace(DEFAULT_MODE, python_cell_magics={"../../../tmp/pwned"})
2214 with cache_dir() as workspace:
2215 cache_file = get_cache_file(mode)
2216 assert cache_file.parent == workspace
2217 assert "/" not in cache_file.name
2218 assert ".." not in cache_file.name
2219 assert "../../../tmp/pwned" not in mode.get_cache_key()
2220
2221 def test_cache_broken_file(self) -> None:
2222 mode = DEFAULT_MODE
2223 with cache_dir() as workspace:
2224 cache_file = get_cache_file(mode)
2225 cache_file.write_text("this is not a pickle", encoding="utf-8")
2226 assert black.Cache.read(mode).file_data == {}
2227 src = (workspace / "test.py").resolve()
2228 src.write_text("print('hello')", encoding="utf-8")
2229 invokeBlack([str(src)])
2230 cache = black.Cache.read(mode)
2231 assert not cache.is_changed(src)
2232
2233 def test_cache_single_file_already_cached(self) -> None:
2234 mode = DEFAULT_MODE
2235 with cache_dir() as workspace:
2236 src = (workspace / "test.py").resolve()
2237 src.write_text("print('hello')", encoding="utf-8")
2238 cache = black.Cache.read(mode)
2239 cache.write([src])
2240 invokeBlack([str(src)])
2241 assert src.read_text(encoding="utf-8") == "print('hello')"
2242
2243 @event_loop()
2244 def test_cache_multiple_files(self) -> None:
2245 mode = DEFAULT_MODE
2246 with (
2247 cache_dir() as workspace,
2248 patch("concurrent.futures.ProcessPoolExecutor", new=ThreadPoolExecutor),
2249 ):
2250 one = (workspace / "one.py").resolve()
2251 one.write_text("print('hello')", encoding="utf-8")
2252 two = (workspace / "two.py").resolve()
2253 two.write_text("print('hello')", encoding="utf-8")
2254 cache = black.Cache.read(mode)
2255 cache.write([one])
2256 invokeBlack([str(workspace)])
2257 assert one.read_text(encoding="utf-8") == "print('hello')"
2258 assert two.read_text(encoding="utf-8") == 'print("hello")\n'
2259 cache = black.Cache.read(mode)
2260 assert not cache.is_changed(one)
2261 assert not cache.is_changed(two)
2262
2263 @pytest.mark.incompatible_with_mypyc
2264 @pytest.mark.parametrize("color", [False, True], ids=["no-color", "with-color"])
2265 def test_no_cache_when_writeback_diff(self, color: bool) -> None:
2266 mode = DEFAULT_MODE
2267 with cache_dir() as workspace:
2268 src = (workspace / "test.py").resolve()
2269 src.write_text("print('hello')", encoding="utf-8")
2270 with (
2271 patch.object(black.Cache, "read") as read_cache,
2272 patch.object(black.Cache, "write") as write_cache,
2273 ):
2274 cmd = [str(src), "--diff"]
2275 if color:
2276 cmd.append("--color")
2277 invokeBlack(cmd)
2278 cache_file = get_cache_file(mode)
2279 assert cache_file.exists() is False
2280 read_cache.assert_called_once()
2281 write_cache.assert_not_called()
2282
2283 @pytest.mark.parametrize("color", [False, True], ids=["no-color", "with-color"])
2284 @event_loop()
2285 def test_output_locking_when_writeback_diff(self, color: bool) -> None:
2286 with cache_dir() as workspace:
2287 for tag in range(0, 4):
2288 src = (workspace / f"test{tag}.py").resolve()
2289 src.write_text("print('hello')", encoding="utf-8")
2290 with patch(
2291 "black.concurrency.Manager", wraps=multiprocessing.Manager
2292 ) as mgr:
2293 cmd = ["--diff", str(workspace)]
2294 if color:
2295 cmd.append("--color")
2296 invokeBlack(cmd, exit_code=0)
2297 # this isn't quite doing what we want, but if it _isn't_
2298 # called then we cannot be using the lock it provides
2299 mgr.assert_called()
2300
2301 def test_no_cache_when_stdin(self) -> None:
2302 mode = DEFAULT_MODE
2303 with cache_dir():
2304 result = BlackRunner().invoke(
2305 black.main, ["-"], input=BytesIO(b"print('hello')")
2306 )
2307 assert not result.exit_code
2308 cache_file = get_cache_file(mode)
2309 assert not cache_file.exists()
2310
2311 def test_no_cache_flag_prevents_writes(self) -> None:
2312 """--no-cache should neither read nor write the cache"""
2313 mode = DEFAULT_MODE
2314 with cache_dir() as workspace:
2315 src = (workspace / "test.py").resolve()
2316 src.write_text("print('hello')", encoding="utf-8")
2317 cache = black.Cache.read(mode)
2318 # Pre-populate cache so the file is considered cached
2319 cache.write([src])
2320 with (
2321 patch.object(black.Cache, "read") as read_cache,
2322 patch.object(black.Cache, "write") as write_cache,
2323 ):
2324 # Pass --no-cache; it should neither read nor write
2325 invokeBlack([str(src), "--no-cache"])
2326 read_cache.assert_not_called()
2327 write_cache.assert_not_called()
2328
2329 def test_no_cache_with_multiple_files(self) -> None:
2330 """Formatting multiple files with --no-cache should not read or write cache
2331 and should format files normally."""
2332 mode = DEFAULT_MODE
2333 with (cache_dir() as workspace,):
2334 one = (workspace / "one.py").resolve()
2335 one.write_text("print('hello')", encoding="utf-8")
2336 two = (workspace / "two.py").resolve()
2337 two.write_text("print('hello')", encoding="utf-8")
2338
2339 # Pre-populate cache for `one` so it would normally be skipped
2340 cache = black.Cache.read(mode)
2341 cache.write([one])
2342
2343 with (
2344 patch.object(black.Cache, "read") as read_cache,
2345 patch.object(black.Cache, "write") as write_cache,
2346 ):
2347 # Run Black over the directory with --no-cache
2348 invokeBlack([str(workspace), "--no-cache"])
2349
2350 # Cache should not be consulted or updated
2351 read_cache.assert_not_called()
2352 write_cache.assert_not_called()
2353
2354 # Both files should have been formatted (double quotes + newline)
2355 assert one.read_text(encoding="utf-8") == 'print("hello")\n'
2356 assert two.read_text(encoding="utf-8") == 'print("hello")\n'
2357
2358 def test_read_cache_no_cachefile(self) -> None:
2359 mode = DEFAULT_MODE
2360 with cache_dir():
2361 assert black.Cache.read(mode).file_data == {}
2362
2363 def test_write_cache_read_cache(self) -> None:
2364 mode = DEFAULT_MODE
2365 with cache_dir() as workspace:
2366 src = (workspace / "test.py").resolve()
2367 src.touch()
2368 write_cache = black.Cache.read(mode)
2369 write_cache.write([src])
2370 read_cache = black.Cache.read(mode)
2371 assert not read_cache.is_changed(src)
2372
2373 @pytest.mark.incompatible_with_mypyc
2374 def test_filter_cached(self) -> None:
2375 with TemporaryDirectory() as workspace:
2376 path = Path(workspace)
2377 uncached = (path / "uncached").resolve()
2378 cached = (path / "cached").resolve()
2379 cached_but_changed = (path / "changed").resolve()
2380 uncached.touch()
2381 cached.touch()
2382 cached_but_changed.touch()
2383 cache = black.Cache.read(DEFAULT_MODE)
2384
2385 orig_func = black.Cache.get_file_data
2386
2387 def wrapped_func(path: Path) -> FileData:
2388 if path == cached:
2389 return orig_func(path)
2390 if path == cached_but_changed:
2391 return FileData(0.0, 0, "")
2392 raise AssertionError
2393
2394 with patch.object(black.Cache, "get_file_data", side_effect=wrapped_func):
2395 cache.write([cached, cached_but_changed])
2396 todo, done = cache.filtered_cached({uncached, cached, cached_but_changed})
2397 assert todo == {uncached, cached_but_changed}
2398 assert done == {cached}
2399
2400 def test_filter_cached_hash(self) -> None:
2401 with TemporaryDirectory() as workspace:
2402 path = Path(workspace)
2403 src = (path / "test.py").resolve()
2404 src.write_text("print('hello')", encoding="utf-8")
2405 st = src.stat()
2406 cache = black.Cache.read(DEFAULT_MODE)
2407 cache.write([src])
2408 cached_file_data = cache.file_data[str(src)]
2409
2410 todo, done = cache.filtered_cached([src])
2411 assert todo == set()
2412 assert done == {src}
2413 assert cached_file_data.st_mtime == st.st_mtime
2414
2415 # Modify st_mtime
2416 cached_file_data = cache.file_data[str(src)] = FileData(
2417 cached_file_data.st_mtime - 1,
2418 cached_file_data.st_size,
2419 cached_file_data.hash,
2420 )
2421 todo, done = cache.filtered_cached([src])
2422 assert todo == set()
2423 assert done == {src}
2424 assert cached_file_data.st_mtime < st.st_mtime
2425 assert cached_file_data.st_size == st.st_size
2426 assert cached_file_data.hash == black.Cache.hash_digest(src)
2427
2428 # Modify contents
2429 src.write_text("print('hello world')", encoding="utf-8")
2430 new_st = src.stat()
2431 todo, done = cache.filtered_cached([src])
2432 assert todo == {src}
2433 assert done == set()
2434 assert cached_file_data.st_mtime < new_st.st_mtime
2435 assert cached_file_data.st_size != new_st.st_size
2436 assert cached_file_data.hash != black.Cache.hash_digest(src)
2437
2438 def test_write_cache_creates_directory_if_needed(self) -> None:
2439 mode = DEFAULT_MODE
2440 with cache_dir(exists=False) as workspace:
2441 assert not workspace.exists()
2442 cache = black.Cache.read(mode)
2443 cache.write([])
2444 assert workspace.exists()
2445
2446 @event_loop()
2447 def test_failed_formatting_does_not_get_cached(self) -> None:
2448 mode = DEFAULT_MODE
2449 with (
2450 cache_dir() as workspace,
2451 patch("concurrent.futures.ProcessPoolExecutor", new=ThreadPoolExecutor),
2452 ):
2453 failing = (workspace / "failing.py").resolve()
2454 failing.write_text("not actually python", encoding="utf-8")
2455 clean = (workspace / "clean.py").resolve()
2456 clean.write_text('print("hello")\n', encoding="utf-8")
2457 invokeBlack([str(workspace)], exit_code=123)
2458 cache = black.Cache.read(mode)
2459 assert cache.is_changed(failing)
2460 assert not cache.is_changed(clean)
2461
2462 def test_write_cache_write_fail(self) -> None:
2463 mode = DEFAULT_MODE
2464 with cache_dir():
2465 cache = black.Cache.read(mode)
2466 with patch.object(Path, "open") as mock:
2467 mock.side_effect = OSError
2468 cache.write([])
2469
2470 def test_read_cache_line_lengths(self) -> None:
2471 mode = DEFAULT_MODE
2472 short_mode = replace(DEFAULT_MODE, line_length=1)
2473 with cache_dir() as workspace:
2474 path = (workspace / "file.py").resolve()
2475 path.touch()
2476 cache = black.Cache.read(mode)
2477 cache.write([path])
2478 one = black.Cache.read(mode)
2479 assert not one.is_changed(path)
2480 two = black.Cache.read(short_mode)
2481 assert two.is_changed(path)
2482
2483 def test_cache_key(self) -> None:
2484 # Test that all members of the mode enum affect the cache key.
2485 for field in fields(Mode):
2486 values: list[Any]
2487 if field.name == "target_versions":
2488 values = [
2489 {TargetVersion.PY312},
2490 {TargetVersion.PY313},
2491 ]
2492 elif field.name == "python_cell_magics":
2493 values = [{"magic1"}, {"magic2"}]
2494 elif field.name == "enabled_features":
2495 # If you are looking to remove one of these features, just
2496 # replace it with any other feature.
2497 values = [
2498 {Preview.wrap_comprehension_in},
2499 {Preview.string_processing},
2500 ]
2501 elif field.type is bool:
2502 values = [True, False]
2503 elif field.type is int:
2504 values = [1, 2]
2505 else:
2506 raise AssertionError(
2507 f"Unhandled field type: {field.type} for field {field.name}"
2508 )
2509 modes = [replace(DEFAULT_MODE, **{field.name: value}) for value in values]
2510 keys = [mode.get_cache_key() for mode in modes]
2511 assert len(set(keys)) == len(modes)
2512
2513
2514 def assert_collected_sources(
2515 src: Sequence[str | Path],
2516 expected: Sequence[str | Path],
2517 *,
2518 root: Path | None = None,
2519 exclude: str | None = None,
2520 include: str | None = None,
2521 extend_exclude: str | None = None,
2522 force_exclude: str | None = None,
2523 stdin_filename: str | None = None,
2524 ) -> None:
2525 gs_src = tuple(str(Path(s)) for s in src)
2526 gs_expected = [Path(s) for s in expected]
2527 gs_exclude = None if exclude is None else compile_pattern(exclude)
2528 gs_include = DEFAULT_INCLUDE if include is None else compile_pattern(include)
2529 gs_extend_exclude = (
2530 None if extend_exclude is None else compile_pattern(extend_exclude)
2531 )
2532 gs_force_exclude = None if force_exclude is None else compile_pattern(force_exclude)
2533 collected = black.get_sources(
2534 root=root or THIS_DIR,
2535 src=gs_src,
2536 quiet=False,
2537 verbose=False,
2538 include=gs_include,
2539 exclude=gs_exclude,
2540 extend_exclude=gs_extend_exclude,
2541 force_exclude=gs_force_exclude,
2542 report=black.Report(),
2543 stdin_filename=stdin_filename,
2544 )
2545 assert sorted(collected) == sorted(gs_expected)
2546
2547
2548 class TestFileCollection:
2549 def test_include_exclude(self) -> None:
2550 path = THIS_DIR / "data" / "include_exclude_tests"
2551 src = [path]
2552 expected = [
2553 Path(path / "b/dont_exclude/a.py"),
2554 Path(path / "b/dont_exclude/a.pyi"),
2555 ]
2556 assert_collected_sources(
2557 src,
2558 expected,
2559 include=r"\.pyi?$",
2560 exclude=r"/exclude/|/\.definitely_exclude/",
2561 )
2562
2563 def test_gitignore_used_as_default(self) -> None:
2564 base = Path(DATA_DIR / "include_exclude_tests")
2565 expected = [
2566 base / "b/.definitely_exclude/a.py",
2567 base / "b/.definitely_exclude/a.pyi",
2568 ]
2569 src = [base / "b/"]
2570 assert_collected_sources(src, expected, root=base, extend_exclude=r"/exclude/")
2571
2572 def test_gitignore_used_on_multiple_sources(self) -> None:
2573 root = Path(DATA_DIR / "gitignore_used_on_multiple_sources")
2574 expected = [
2575 root / "dir1" / "b.py",
2576 root / "dir2" / "b.py",
2577 ]
2578 src = [root / "dir1", root / "dir2"]
2579 assert_collected_sources(src, expected, root=root)
2580
2581 @patch("black.find_project_root", lambda *args: (THIS_DIR.resolve(), None))
2582 def test_exclude_for_issue_1572(self) -> None:
2583 # Exclude shouldn't touch files that were explicitly given to Black through the
2584 # CLI. Exclude is supposed to only apply to the recursive discovery of files.
2585 # https://github.com/psf/black/issues/1572
2586 path = DATA_DIR / "include_exclude_tests"
2587 src = [path / "b/exclude/a.py"]
2588 expected = [path / "b/exclude/a.py"]
2589 assert_collected_sources(src, expected, include="", exclude=r"/exclude/|a\.py")
2590
2591 def test_gitignore_exclude(self) -> None:
2592 path = THIS_DIR / "data" / "include_exclude_tests"
2593 include = re.compile(r"\.pyi?$")
2594 exclude = re.compile(r"")
2595 report = black.Report()
2596 gitignore = GitIgnoreSpec.from_lines(
2597 ["exclude/", ".definitely_exclude", "!exclude/still_exclude/"]
2598 )
2599 sources: list[Path] = []
2600 expected = [
2601 Path(path / "b/dont_exclude/a.py"),
2602 Path(path / "b/dont_exclude/a.pyi"),
2603 ]
2604 this_abs = THIS_DIR.resolve()
2605 sources.extend(
2606 black.gen_python_files(
2607 path.iterdir(),
2608 this_abs,
2609 include,
2610 exclude,
2611 None,
2612 None,
2613 report,
2614 {path: gitignore},
2615 verbose=False,
2616 quiet=False,
2617 )
2618 )
2619 assert sorted(expected) == sorted(sources)
2620
2621 def test_gitignore_reinclude(self) -> None:
2622 path = THIS_DIR / "data" / "include_exclude_tests"
2623 include = re.compile(r"\.pyi?$")
2624 exclude = re.compile(r"")
2625 report = black.Report()
2626 gitignore = GitIgnoreSpec.from_lines(
2627 ["*/exclude/*", ".definitely_exclude", "!*/exclude/still_exclude/"]
2628 )
2629 sources: list[Path] = []
2630 expected = [
2631 Path(path / "b/dont_exclude/a.py"),
2632 Path(path / "b/dont_exclude/a.pyi"),
2633 Path(path / "b/exclude/still_exclude/a.py"),
2634 Path(path / "b/exclude/still_exclude/a.pyi"),
2635 ]
2636 this_abs = THIS_DIR.resolve()
2637 sources.extend(
2638 black.gen_python_files(
2639 path.iterdir(),
2640 this_abs,
2641 include,
2642 exclude,
2643 None,
2644 None,
2645 report,
2646 {path: gitignore},
2647 verbose=False,
2648 quiet=False,
2649 )
2650 )
2651 assert sorted(expected) == sorted(sources)
2652
2653 def test_gitignore_reinclude_root(self) -> None:
2654 path = THIS_DIR / "data" / "include_exclude_tests" / "b"
2655 include = re.compile(r"\.pyi?$")
2656 exclude = re.compile(r"")
2657 report = black.Report()
2658 gitignore = GitIgnoreSpec.from_lines(
2659 ["exclude/*", ".definitely_exclude", "!exclude/still_exclude/"]
2660 )
2661 sources: list[Path] = []
2662 expected = [
2663 Path(path / "dont_exclude/a.py"),
2664 Path(path / "dont_exclude/a.pyi"),
2665 Path(path / "exclude/still_exclude/a.py"),
2666 Path(path / "exclude/still_exclude/a.pyi"),
2667 ]
2668 this_abs = THIS_DIR.resolve()
2669 sources.extend(
2670 black.gen_python_files(
2671 path.iterdir(),
2672 this_abs,
2673 include,
2674 exclude,
2675 None,
2676 None,
2677 report,
2678 {path: gitignore},
2679 verbose=False,
2680 quiet=False,
2681 )
2682 )
2683 assert sorted(expected) == sorted(sources)
2684
2685 def test_nested_gitignore(self) -> None:
2686 path = Path(THIS_DIR / "data" / "nested_gitignore_tests")
2687 include = re.compile(r"\.pyi?$")
2688 exclude = re.compile(r"")
2689 root_gitignore = black.files.get_gitignore(path)
2690 report = black.Report()
2691 expected: list[Path] = [
2692 Path(path / "x.py"),
2693 Path(path / "root/b.py"),
2694 Path(path / "root/c.py"),
2695 Path(path / "root/child/c.py"),
2696 ]
2697 this_abs = THIS_DIR.resolve()
2698 sources = list(
2699 black.gen_python_files(
2700 path.iterdir(),
2701 this_abs,
2702 include,
2703 exclude,
2704 None,
2705 None,
2706 report,
2707 {path: root_gitignore},
2708 verbose=False,
2709 quiet=False,
2710 )
2711 )
2712 assert sorted(expected) == sorted(sources)
2713
2714 def test_nested_gitignore_directly_in_source_directory(self) -> None:
2715 # https://github.com/psf/black/issues/2598
2716 path = Path(DATA_DIR / "nested_gitignore_tests")
2717 src = Path(path / "root" / "child")
2718 expected = [src / "a.py", src / "c.py"]
2719 assert_collected_sources([src], expected)
2720
2721 def test_invalid_gitignore(self) -> None:
2722 path = THIS_DIR / "data" / "invalid_gitignore_tests"
2723 empty_config = path / "pyproject.toml"
2724 result = BlackRunner().invoke(
2725 black.main, ["--verbose", "--config", str(empty_config), str(path)]
2726 )
2727 assert result.exit_code == 1
2728 assert result.stderr_bytes is not None
2729
2730 gitignore = path / ".gitignore"
2731 assert re.search(
2732 f"Could not parse {gitignore}".replace("\\", "\\\\"),
2733 result.stderr_bytes.decode(),
2734 re.IGNORECASE if isinstance(gitignore, WindowsPath) else 0,
2735 )
2736
2737 def test_invalid_nested_gitignore(self) -> None:
2738 path = THIS_DIR / "data" / "invalid_nested_gitignore_tests"
2739 empty_config = path / "pyproject.toml"
2740 result = BlackRunner().invoke(
2741 black.main, ["--verbose", "--config", str(empty_config), str(path)]
2742 )
2743 assert result.exit_code == 1
2744 assert result.stderr_bytes is not None
2745
2746 gitignore = path / "a" / ".gitignore"
2747 assert re.search(
2748 f"Could not parse {gitignore}".replace("\\", "\\\\"),
2749 result.stderr_bytes.decode(),
2750 re.IGNORECASE if isinstance(gitignore, WindowsPath) else 0,
2751 )
2752
2753 def test_gitignore_that_ignores_subfolders(self) -> None:
2754 # If gitignore with */* is in root
2755 root = Path(DATA_DIR / "ignore_subfolders_gitignore_tests" / "subdir")
2756 expected = [root / "b.py"]
2757 assert_collected_sources([root], expected, root=root)
2758
2759 # If .gitignore with */* is nested
2760 root = Path(DATA_DIR / "ignore_subfolders_gitignore_tests")
2761 expected = [
2762 root / "a.py",
2763 root / "subdir" / "b.py",
2764 ]
2765 assert_collected_sources([root], expected, root=root)
2766
2767 # If command is executed from outer dir
2768 root = Path(DATA_DIR / "ignore_subfolders_gitignore_tests")
2769 target = root / "subdir"
2770 expected = [target / "b.py"]
2771 assert_collected_sources([target], expected, root=root)
2772
2773 def test_gitignore_that_ignores_directory(self) -> None:
2774 # If gitignore with a directory is in root
2775 root = Path(DATA_DIR, "ignore_directory_gitignore_tests")
2776 expected = [root / "z.py"]
2777 assert_collected_sources([root], expected, root=root)
2778
2779 def test_empty_include(self) -> None:
2780 path = DATA_DIR / "include_exclude_tests"
2781 src = [path]
2782 expected = [
2783 Path(path / "b/exclude/a.pie"),
2784 Path(path / "b/exclude/a.py"),
2785 Path(path / "b/exclude/a.pyi"),
2786 Path(path / "b/exclude/still_exclude/a.pie"),
2787 Path(path / "b/exclude/still_exclude/a.py"),
2788 Path(path / "b/exclude/still_exclude/a.pyi"),
2789 Path(path / "b/dont_exclude/a.pie"),
2790 Path(path / "b/dont_exclude/a.py"),
2791 Path(path / "b/dont_exclude/a.pyi"),
2792 Path(path / "b/.definitely_exclude/a.pie"),
2793 Path(path / "b/.definitely_exclude/a.py"),
2794 Path(path / "b/.definitely_exclude/a.pyi"),
2795 Path(path / ".gitignore"),
2796 Path(path / "pyproject.toml"),
2797 ]
2798 # Setting exclude explicitly to an empty string to block .gitignore usage.
2799 assert_collected_sources(src, expected, include="", exclude="")
2800
2801 def test_include_absolute_path(self) -> None:
2802 path = DATA_DIR / "include_exclude_tests"
2803 src = [path]
2804 expected = [
2805 Path(path / "b/dont_exclude/a.pie"),
2806 ]
2807 assert_collected_sources(
2808 src, expected, root=path, include=r"^/b/dont_exclude/a\.pie$", exclude=""
2809 )
2810
2811 def test_exclude_absolute_path(self) -> None:
2812 path = DATA_DIR / "include_exclude_tests"
2813 src = [path]
2814 expected = [
2815 Path(path / "b/dont_exclude/a.py"),
2816 Path(path / "b/exclude/still_exclude/a.py"),
2817 Path(path / "b/.definitely_exclude/a.py"),
2818 ]
2819 assert_collected_sources(
2820 src, expected, root=path, include=r"\.py$", exclude=r"^/b/exclude/a\.py$"
2821 )
2822
2823 def test_extend_exclude(self) -> None:
2824 path = DATA_DIR / "include_exclude_tests"
2825 src = [path]
2826 expected = [
2827 Path(path / "b/exclude/a.py"),
2828 Path(path / "b/exclude/still_exclude/a.py"),
2829 Path(path / "b/dont_exclude/a.py"),
2830 ]
2831 assert_collected_sources(
2832 src, expected, exclude=r"\.pyi$", extend_exclude=r"\.definitely_exclude"
2833 )
2834
2835 @pytest.mark.incompatible_with_mypyc
2836 def test_symlinks(self) -> None:
2837 root = THIS_DIR.resolve()
2838 include = re.compile(black.DEFAULT_INCLUDES)
2839 exclude = re.compile(black.DEFAULT_EXCLUDES)
2840 report = black.Report()
2841 gitignore = GitIgnoreSpec.from_lines([])
2842
2843 regular = MagicMock()
2844 regular.relative_to.return_value = Path("regular.py")
2845 regular.resolve.return_value = root / "regular.py"
2846 regular.is_dir.return_value = False
2847 regular.is_file.return_value = True
2848
2849 outside_root_symlink = MagicMock()
2850 outside_root_symlink.relative_to.return_value = Path("symlink.py")
2851 outside_root_symlink.resolve.return_value = Path("/nowhere")
2852 outside_root_symlink.is_dir.return_value = False
2853 outside_root_symlink.is_file.return_value = True
2854
2855 ignored_symlink = MagicMock()
2856 ignored_symlink.relative_to.return_value = Path(".mypy_cache") / "symlink.py"
2857 ignored_symlink.is_dir.return_value = False
2858 ignored_symlink.is_file.return_value = True
2859
2860 # A symlink that has an excluded name, but points to an included name
2861 symlink_excluded_name = MagicMock()
2862 symlink_excluded_name.relative_to.return_value = Path("excluded_name")
2863 symlink_excluded_name.resolve.return_value = root / "included_name.py"
2864 symlink_excluded_name.is_dir.return_value = False
2865 symlink_excluded_name.is_file.return_value = True
2866
2867 # A symlink that has an included name, but points to an excluded name
2868 symlink_included_name = MagicMock()
2869 symlink_included_name.relative_to.return_value = Path("included_name.py")
2870 symlink_included_name.resolve.return_value = root / "excluded_name"
2871 symlink_included_name.is_dir.return_value = False
2872 symlink_included_name.is_file.return_value = True
2873
2874 path = MagicMock()
2875 path.iterdir.return_value = [
2876 regular,
2877 outside_root_symlink,
2878 ignored_symlink,
2879 symlink_excluded_name,
2880 symlink_included_name,
2881 ]
2882
2883 files = list(
2884 black.gen_python_files(
2885 path.iterdir(),
2886 root,
2887 include,
2888 exclude,
2889 None,
2890 None,
2891 report,
2892 {path: gitignore},
2893 verbose=False,
2894 quiet=False,
2895 )
2896 )
2897 assert files == [regular, symlink_included_name]
2898
2899 path.iterdir.assert_called_once()
2900 outside_root_symlink.resolve.assert_called_once()
2901 ignored_symlink.resolve.assert_not_called()
2902
2903 def test_get_sources_symlink_and_force_exclude(self) -> None:
2904 with TemporaryDirectory() as tempdir:
2905 tmp = Path(tempdir).resolve()
2906 actual = tmp / "actual"
2907 actual.mkdir()
2908 symlink = tmp / "symlink"
2909 symlink.symlink_to(actual)
2910
2911 actual_proj = actual / "project"
2912 actual_proj.mkdir()
2913 (actual_proj / "module.py").write_text("print('hello')", encoding="utf-8")
2914
2915 symlink_proj = symlink / "project"
2916
2917 with change_directory(symlink_proj):
2918 assert_collected_sources(
2919 src=["module.py"],
2920 root=symlink_proj.resolve(),
2921 expected=["module.py"],
2922 )
2923
2924 absolute_module = symlink_proj / "module.py"
2925 assert_collected_sources(
2926 src=[absolute_module],
2927 root=symlink_proj.resolve(),
2928 expected=[absolute_module],
2929 )
2930
2931 # a few tricky tests for force_exclude
2932 flat_symlink = symlink_proj / "symlink_module.py"
2933 flat_symlink.symlink_to(actual_proj / "module.py")
2934 assert_collected_sources(
2935 src=[flat_symlink],
2936 root=symlink_proj.resolve(),
2937 force_exclude=r"/symlink_module.py",
2938 expected=[],
2939 )
2940
2941 target = actual_proj / "target"
2942 target.mkdir()
2943 (target / "another.py").write_text("print('hello')", encoding="utf-8")
2944 (symlink_proj / "nested").symlink_to(target)
2945
2946 assert_collected_sources(
2947 src=[symlink_proj / "nested" / "another.py"],
2948 root=symlink_proj.resolve(),
2949 force_exclude=r"nested",
2950 expected=[],
2951 )
2952 assert_collected_sources(
2953 src=[symlink_proj / "nested" / "another.py"],
2954 root=symlink_proj.resolve(),
2955 force_exclude=r"target",
2956 expected=[symlink_proj / "nested" / "another.py"],
2957 )
2958
2959 def test_get_sources_with_stdin_symlink_outside_root(
2960 self,
2961 ) -> None:
2962 with TemporaryDirectory() as tempdir:
2963 tmp = Path(tempdir).resolve()
2964
2965 root = tmp / "root"
2966 root.mkdir()
2967 (root / "pyproject.toml").write_text("[tool.black]", encoding="utf-8")
2968
2969 target = tmp / "outside_root" / "a.py"
2970 target.parent.mkdir()
2971 target.write_text("print('hello')", encoding="utf-8")
2972 (root / "a.py").symlink_to(target)
2973
2974 stdin_filename = str(root / "a.py")
2975 assert_collected_sources(
2976 root=root,
2977 src=["-"],
2978 expected=[],
2979 stdin_filename=stdin_filename,
2980 )
2981
2982 def test_get_sources_with_stdin(self) -> None:
2983 src = ["-"]
2984 expected = ["-"]
2985 assert_collected_sources(
2986 src,
2987 root=THIS_DIR.resolve(),
2988 expected=expected,
2989 include="",
2990 exclude=r"/exclude/|a\.py",
2991 )
2992
2993 def test_get_sources_with_stdin_filename(self) -> None:
2994 src = ["-"]
2995 stdin_filename = str(THIS_DIR / "data/collections.py")
2996 expected = [f"__BLACK_STDIN_FILENAME__{stdin_filename}"]
2997 assert_collected_sources(
2998 src,
2999 root=THIS_DIR.resolve(),
3000 expected=expected,
3001 exclude=r"/exclude/a\.py",
3002 stdin_filename=stdin_filename,
3003 )
3004
3005 def test_get_sources_with_stdin_filename_and_exclude(self) -> None:
3006 # Exclude shouldn't exclude stdin_filename since it is mimicking the
3007 # file being passed directly. This is the same as
3008 # test_exclude_for_issue_1572
3009 path = DATA_DIR / "include_exclude_tests"
3010 src = ["-"]
3011 stdin_filename = str(path / "b/exclude/a.py")
3012 expected = [f"__BLACK_STDIN_FILENAME__{stdin_filename}"]
3013 assert_collected_sources(
3014 src,
3015 root=THIS_DIR.resolve(),
3016 expected=expected,
3017 exclude=r"/exclude/|a\.py",
3018 stdin_filename=stdin_filename,
3019 )
3020
3021 def test_get_sources_with_stdin_filename_and_extend_exclude(self) -> None:
3022 # Extend exclude shouldn't exclude stdin_filename since it is mimicking the
3023 # file being passed directly. This is the same as
3024 # test_exclude_for_issue_1572
3025 src = ["-"]
3026 path = THIS_DIR / "data" / "include_exclude_tests"
3027 stdin_filename = str(path / "b/exclude/a.py")
3028 expected = [f"__BLACK_STDIN_FILENAME__{stdin_filename}"]
3029 assert_collected_sources(
3030 src,
3031 root=THIS_DIR.resolve(),
3032 expected=expected,
3033 extend_exclude=r"/exclude/|a\.py",
3034 stdin_filename=stdin_filename,
3035 )
3036
3037 def test_get_sources_with_stdin_filename_and_force_exclude(self) -> None:
3038 # Force exclude should exclude the file when passing it through
3039 # stdin_filename
3040 path = THIS_DIR / "data" / "include_exclude_tests"
3041 stdin_filename = str(path / "b/exclude/a.py")
3042 assert_collected_sources(
3043 src=["-"],
3044 root=THIS_DIR.resolve(),
3045 expected=[],
3046 force_exclude=r"/exclude/|a\.py",
3047 stdin_filename=stdin_filename,
3048 )
3049
3050 def test_get_sources_with_stdin_filename_and_force_exclude_and_symlink(
3051 self,
3052 ) -> None:
3053 # Force exclude should exclude a symlink based on the symlink, not its target
3054 with TemporaryDirectory() as tempdir:
3055 tmp = Path(tempdir).resolve()
3056 (tmp / "exclude").mkdir()
3057 (tmp / "exclude" / "a.py").write_text("print('hello')", encoding="utf-8")
3058 (tmp / "symlink.py").symlink_to(tmp / "exclude" / "a.py")
3059
3060 stdin_filename = str(tmp / "symlink.py")
3061 expected = [f"__BLACK_STDIN_FILENAME__{stdin_filename}"]
3062 with change_directory(tmp):
3063 assert_collected_sources(
3064 src=["-"],
3065 root=tmp,
3066 expected=expected,
3067 force_exclude=r"exclude/a\.py",
3068 stdin_filename=stdin_filename,
3069 )
3070
3071
3072 class TestDeFactoAPI:
3073 """Test that certain symbols that are commonly used externally keep working.
3074
3075 We don't (yet) formally expose an API (see issue #779), but we should endeavor to
3076 keep certain functions that external users commonly rely on working.
3077
3078 """
3079
3080 def test_format_str(self) -> None:
3081 # format_str and Mode should keep working
3082 assert (
3083 black.format_str("print('hello')", mode=black.Mode()) == 'print("hello")\n'
3084 )
3085
3086 # you can pass line length
3087 assert (
3088 black.format_str("print('hello')", mode=black.Mode(line_length=42))
3089 == 'print("hello")\n'
3090 )
3091
3092 # invalid input raises InvalidInput
3093 with pytest.raises(black.InvalidInput):
3094 black.format_str("syntax error", mode=black.Mode())
3095
3096 def test_format_file_contents(self) -> None:
3097 # You probably should be using format_str() instead, but let's keep
3098 # this one around since people do use it
3099 assert (
3100 black.format_file_contents("x=1", fast=True, mode=black.Mode()) == "x = 1\n"
3101 )
3102
3103 with pytest.raises(black.NothingChanged):
3104 black.format_file_contents("x = 1\n", fast=True, mode=black.Mode())
3105
3106
3107 class TestASTSafety(BlackBaseTestCase):
3108 def check_ast_equivalence(
3109 self, source: str, dest: str, *, should_fail: bool = False
3110 ) -> None:
3111 # If we get a failure, make sure it's not because the code itself
3112 # is invalid, since that will also cause assert_equivalent() to throw
3113 # ASTSafetyError.
3114 source = textwrap.dedent(source)
3115 dest = textwrap.dedent(dest)
3116 black.parse_ast(source)
3117 black.parse_ast(dest)
3118 if should_fail:
3119 with self.assertRaises(ASTSafetyError):
3120 black.assert_equivalent(source, dest)
3121 else:
3122 black.assert_equivalent(source, dest)
3123
3124 def test_assert_equivalent_basic(self) -> None:
3125 self.check_ast_equivalence("{}", "None", should_fail=True)
3126 self.check_ast_equivalence("1+2", "1 + 2")
3127 self.check_ast_equivalence("hi # comment", "hi")
3128
3129 def test_assert_equivalent_del(self) -> None:
3130 self.check_ast_equivalence("del (a, b)", "del a, b")
3131
3132 def test_assert_equivalent_strings(self) -> None:
3133 self.check_ast_equivalence('x = "x"', 'x = " x "', should_fail=True)
3134 self.check_ast_equivalence(
3135 '''
3136 """docstring """
3137 ''',
3138 '''
3139 """docstring"""
3140 ''',
3141 )
3142 self.check_ast_equivalence(
3143 '''
3144 """docstring """
3145 ''',
3146 '''
3147 """ddocstring"""
3148 ''',
3149 should_fail=True,
3150 )
3151 self.check_ast_equivalence(
3152 '''
3153 class A:
3154 """
3155
3156 docstring
3157
3158
3159 """
3160 ''',
3161 '''
3162 class A:
3163 """docstring"""
3164 ''',
3165 )
3166 self.check_ast_equivalence(
3167 """
3168 def f():
3169 " docstring "
3170 """,
3171 '''
3172 def f():
3173 """docstring"""
3174 ''',
3175 )
3176 self.check_ast_equivalence(
3177 """
3178 async def f():
3179 " docstring "
3180 """,
3181 '''
3182 async def f():
3183 """docstring"""
3184 ''',
3185 )
3186 self.check_ast_equivalence(
3187 """
3188 if __name__ == "__main__":
3189 " docstring-like "
3190 """,
3191 '''
3192 if __name__ == "__main__":
3193 """docstring-like"""
3194 ''',
3195 )
3196 self.check_ast_equivalence(r'def f(): r" \n "', r'def f(): "\\n"')
3197 self.check_ast_equivalence('try: pass\nexcept: " x "', 'try: pass\nexcept: "x"')
3198
3199 self.check_ast_equivalence(
3200 'def foo(): return " x "', 'def foo(): return "x"', should_fail=True
3201 )
3202
3203 def test_assert_equivalent_fstring(self) -> None:
3204 major, minor = sys.version_info[:2]
3205 if major < 3 or (major == 3 and minor < 12):
3206 pytest.skip("relies on 3.12+ syntax")
3207 # https://github.com/psf/black/issues/4268
3208 self.check_ast_equivalence(
3209 """print(f"{"|".join([a,b,c])}")""",
3210 """print(f"{" | ".join([a,b,c])}")""",
3211 should_fail=True,
3212 )
3213 self.check_ast_equivalence(
3214 """print(f"{"|".join(['a','b','c'])}")""",
3215 """print(f"{" | ".join(['a','b','c'])}")""",
3216 should_fail=True,
3217 )
3218
3219 def test_equivalency_ast_parse_failure_includes_error(self) -> None:
3220 with pytest.raises(SourceASTParseError) as err:
3221 black.assert_equivalent("a«»a = 1", "a«»a = 1")
3222
3223 err.match("--safe")
3224 # Unfortunately the SyntaxError message has changed in newer versions so we
3225 # can't match it directly.
3226 err.match("invalid character")
3227 err.match(r"\(<unknown>, line 1\)")
3228
3229 def test_target_version_exceeds_runtime_warning(self) -> None:
3230 max_target = max(TargetVersion, key=lambda tv: tv.value)
3231 if sys.version_info[1] >= max_target.value:
3232 pytest.skip("no target version higher than runtime available")
3233 target_name = f"py3{sys.version_info[1] + 1}"
3234 code = "x = 1\n"
3235 args = ["--target-version", target_name, "--code", code]
3236 result = BlackRunner().invoke(black.main, args)
3237 stderr = result.stderr_bytes.decode() if result.stderr_bytes else ""
3238 assert "Warning:" in stderr
3239
3240 def test_target_version_exceeds_runtime_no_warning_with_fast(self) -> None:
3241 max_target = max(TargetVersion, key=lambda tv: tv.value)
3242 if sys.version_info[1] >= max_target.value:
3243 pytest.skip("no target version higher than runtime available")
3244 target_name = f"py3{sys.version_info[1] + 1}"
3245 code = "x = 1\n"
3246 args = ["--fast", "--target-version", target_name, "--code", code]
3247 result = BlackRunner().invoke(black.main, args)
3248 stderr = result.stderr_bytes.decode() if result.stderr_bytes else ""
3249 assert "Warning:" not in stderr
3250
3251 def test_target_version_at_runtime_no_warning(self) -> None:
3252 current_minor = sys.version_info[1]
3253 target_name = f"py3{current_minor}"
3254 code = "x = 1\n"
3255 args = ["--target-version", target_name, "--code", code]
3256 result = BlackRunner().invoke(black.main, args)
3257 stderr = result.stderr_bytes.decode() if result.stderr_bytes else ""
3258 assert "Warning:" not in stderr
3259
3260 @pytest.mark.incompatible_with_mypyc
3261 def test_target_version_exceeds_runtime_clear_error_message(self) -> None:
3262 max_target = max(TargetVersion, key=lambda tv: tv.value)
3263 if sys.version_info[1] >= max_target.value:
3264 pytest.skip("no target version higher than runtime available")
3265 future_target = TargetVersion[f"PY3{sys.version_info[1] + 1}"]
3266 mode = Mode(target_versions={future_target})
3267 with patch.object(
3268 black,
3269 "assert_equivalent",
3270 side_effect=ASTSafetyError("mocked parse failure"),
3271 ):
3272 with pytest.raises(ASTSafetyError) as exc_info:
3273 black.check_stability_and_equivalence("x = 1\n", "x = 1\n", mode=mode)
3274 assert "INTERNAL ERROR" not in str(exc_info.value)
3275
3276
3277 try:
3278 with open(black.__file__, encoding="utf-8") as _bf:
3279 black_source_lines = _bf.readlines()
3280 except UnicodeDecodeError:
3281 if not black.COMPILED:
3282 raise
3283
3284
3285 def tracefunc(
3286 frame: types.FrameType, event: str, arg: Any
3287 ) -> Callable[[types.FrameType, str, Any], Any]:
3288 """Show function calls `from black/__init__.py` as they happen.
3289
3290 Register this with `sys.settrace()` in a test you're debugging.
3291 """
3292 if event != "call":
3293 return tracefunc
3294
3295 stack = len(inspect.stack()) - 19
3296 stack *= 2
3297 filename = frame.f_code.co_filename
3298 lineno = frame.f_lineno
3299 func_sig_lineno = lineno - 1
3300 funcname = black_source_lines[func_sig_lineno].strip()
3301 while funcname.startswith("@"):
3302 func_sig_lineno += 1
3303 funcname = black_source_lines[func_sig_lineno].strip()
3304 if "black/__init__.py" in filename:
3305 print(f"{' ' * stack}{lineno}:{funcname}")
3306 return tracefunc