| 1 |
import argparse |
| 2 |
import functools |
| 3 |
import os |
| 4 |
import shlex |
| 5 |
import sys |
| 6 |
import unittest |
| 7 |
from collections.abc import Collection, Iterator |
| 8 |
from contextlib import contextmanager |
| 9 |
from dataclasses import dataclass, field, replace |
| 10 |
from functools import partial |
| 11 |
from pathlib import Path |
| 12 |
from typing import Any |
| 13 |
|
| 14 |
import black |
| 15 |
from black.const import DEFAULT_LINE_LENGTH |
| 16 |
from black.debug import DebugVisitor |
| 17 |
from black.mode import TargetVersion |
| 18 |
from black.output import diff, err, out |
| 19 |
from black.ranges import parse_line_ranges |
| 20 |
|
| 21 |
from . import conftest |
| 22 |
|
| 23 |
PYTHON_SUFFIX = ".py" |
| 24 |
ALLOWED_SUFFIXES = (PYTHON_SUFFIX, ".pyi", ".out", ".diff", ".ipynb") |
| 25 |
|
| 26 |
THIS_DIR = Path(__file__).parent |
| 27 |
DATA_DIR = THIS_DIR / "data" |
| 28 |
PROJECT_ROOT = THIS_DIR.parent |
| 29 |
EMPTY_LINE = "# EMPTY LINE WITH WHITESPACE" + " (this comment will be removed)" |
| 30 |
DETERMINISTIC_HEADER = "[Deterministic header]" |
| 31 |
|
| 32 |
PY36_VERSIONS = { |
| 33 |
TargetVersion.PY36, |
| 34 |
TargetVersion.PY37, |
| 35 |
TargetVersion.PY38, |
| 36 |
TargetVersion.PY39, |
| 37 |
TargetVersion.PY315, |
| 38 |
} |
| 39 |
|
| 40 |
DEFAULT_MODE = black.Mode() |
| 41 |
ff = partial(black.format_file_in_place, mode=DEFAULT_MODE, fast=True) |
| 42 |
fs = partial(black.format_str, mode=DEFAULT_MODE) |
| 43 |
|
| 44 |
|
| 45 |
@dataclass |
| 46 |
class TestCaseArgs: |
| 47 |
mode: black.Mode = field(default_factory=black.Mode) |
| 48 |
fast: bool = False |
| 49 |
minimum_version: tuple[int, int] | None = None |
| 50 |
lines: Collection[tuple[int, int]] = () |
| 51 |
no_preview_line_length_1: bool = False |
| 52 |
|
| 53 |
|
| 54 |
def _assert_format_equal(expected: str, actual: str) -> None: |
| 55 |
if actual != expected and (conftest.PRINT_FULL_TREE or conftest.PRINT_TREE_DIFF): |
| 56 |
bdv: DebugVisitor[Any] |
| 57 |
actual_out: str = "" |
| 58 |
expected_out: str = "" |
| 59 |
if conftest.PRINT_FULL_TREE: |
| 60 |
out("Expected tree:", fg="green") |
| 61 |
try: |
| 62 |
exp_node = black.lib2to3_parse(expected) |
| 63 |
bdv = DebugVisitor(print_output=conftest.PRINT_FULL_TREE) |
| 64 |
list(bdv.visit(exp_node)) |
| 65 |
expected_out = "\n".join(bdv.list_output) |
| 66 |
except Exception as ve: |
| 67 |
err(str(ve)) |
| 68 |
if conftest.PRINT_FULL_TREE: |
| 69 |
out("Actual tree:", fg="red") |
| 70 |
try: |
| 71 |
exp_node = black.lib2to3_parse(actual) |
| 72 |
bdv = DebugVisitor(print_output=conftest.PRINT_FULL_TREE) |
| 73 |
list(bdv.visit(exp_node)) |
| 74 |
actual_out = "\n".join(bdv.list_output) |
| 75 |
except Exception as ve: |
| 76 |
err(str(ve)) |
| 77 |
if conftest.PRINT_TREE_DIFF: |
| 78 |
out("Tree Diff:") |
| 79 |
out( |
| 80 |
diff(expected_out, actual_out, "expected tree", "actual tree") |
| 81 |
or "Trees do not differ" |
| 82 |
) |
| 83 |
|
| 84 |
if actual != expected: |
| 85 |
out(diff(expected, actual, "expected", "actual")) |
| 86 |
|
| 87 |
assert actual == expected |
| 88 |
|
| 89 |
|
| 90 |
class FormatFailure(Exception): |
| 91 |
"""Used to wrap failures when assert_format() runs in an extra mode.""" |
| 92 |
|
| 93 |
|
| 94 |
def assert_format( |
| 95 |
source: str, |
| 96 |
expected: str, |
| 97 |
mode: black.Mode = DEFAULT_MODE, |
| 98 |
*, |
| 99 |
fast: bool = False, |
| 100 |
minimum_version: tuple[int, int] | None = None, |
| 101 |
lines: Collection[tuple[int, int]] = (), |
| 102 |
no_preview_line_length_1: bool = False, |
| 103 |
) -> None: |
| 104 |
"""Convenience function to check that Black formats as expected. |
| 105 |
|
| 106 |
You can pass @minimum_version if you're passing code with newer syntax to guard |
| 107 |
safety guards so they don't just crash with a SyntaxError. Please note this is |
| 108 |
separate from TargetVerson Mode configuration. |
| 109 |
""" |
| 110 |
_assert_format_inner( |
| 111 |
source, expected, mode, fast=fast, minimum_version=minimum_version, lines=lines |
| 112 |
) |
| 113 |
|
| 114 |
# For both preview and non-preview tests, ensure that Black doesn't crash on |
| 115 |
# this code, but don't pass "expected" because the precise output may differ. |
| 116 |
try: |
| 117 |
if mode.unstable: |
| 118 |
new_mode = replace(mode, unstable=False, preview=False) |
| 119 |
else: |
| 120 |
new_mode = replace(mode, preview=not mode.preview) |
| 121 |
_assert_format_inner( |
| 122 |
source, |
| 123 |
None, |
| 124 |
new_mode, |
| 125 |
fast=fast, |
| 126 |
minimum_version=minimum_version, |
| 127 |
lines=lines, |
| 128 |
) |
| 129 |
except Exception as e: |
| 130 |
text = ( |
| 131 |
"unstable" |
| 132 |
if mode.unstable |
| 133 |
else "non-preview" if mode.preview else "preview" |
| 134 |
) |
| 135 |
raise FormatFailure( |
| 136 |
f"Black crashed formatting this case in {text} mode." |
| 137 |
) from e |
| 138 |
# Similarly, setting line length to 1 is a good way to catch |
| 139 |
# stability bugs. Some tests are known to be broken in preview mode with line length |
| 140 |
# of 1 though, and have marked that with a flag --no-preview-line-length-1 |
| 141 |
preview_modes = [False] |
| 142 |
if not no_preview_line_length_1: |
| 143 |
preview_modes.append(True) |
| 144 |
|
| 145 |
for preview_mode in preview_modes: |
| 146 |
|
| 147 |
try: |
| 148 |
_assert_format_inner( |
| 149 |
source, |
| 150 |
None, |
| 151 |
replace(mode, preview=preview_mode, line_length=1, unstable=False), |
| 152 |
fast=fast, |
| 153 |
minimum_version=minimum_version, |
| 154 |
lines=lines, |
| 155 |
) |
| 156 |
except Exception as e: |
| 157 |
text = "preview" if preview_mode else "non-preview" |
| 158 |
raise FormatFailure( |
| 159 |
f"Black crashed formatting this case in {text} mode with line-length=1." |
| 160 |
) from e |
| 161 |
|
| 162 |
|
| 163 |
def _assert_format_inner( |
| 164 |
source: str, |
| 165 |
expected: str | None = None, |
| 166 |
mode: black.Mode = DEFAULT_MODE, |
| 167 |
*, |
| 168 |
fast: bool = False, |
| 169 |
minimum_version: tuple[int, int] | None = None, |
| 170 |
lines: Collection[tuple[int, int]] = (), |
| 171 |
) -> None: |
| 172 |
actual = black.format_str(source, mode=mode, lines=lines) |
| 173 |
if expected is not None: |
| 174 |
_assert_format_equal(expected, actual) |
| 175 |
# It's not useful to run safety checks if we're expecting no changes anyway. The |
| 176 |
# assertion right above will raise if reality does actually make changes. This just |
| 177 |
# avoids wasted CPU cycles. |
| 178 |
if not fast and source != actual: |
| 179 |
# Unfortunately the AST equivalence check relies on the built-in ast module |
| 180 |
# being able to parse the code being formatted. This doesn't always work out |
| 181 |
# when checking modern code on older versions. |
| 182 |
if minimum_version is None or sys.version_info >= minimum_version: |
| 183 |
black.assert_equivalent(source, actual) |
| 184 |
black.assert_stable(source, actual, mode=mode, lines=lines) |
| 185 |
|
| 186 |
|
| 187 |
def dump_to_stderr(*output: str) -> str: |
| 188 |
return "\n" + "\n".join(output) + "\n" |
| 189 |
|
| 190 |
|
| 191 |
class BlackBaseTestCase(unittest.TestCase): |
| 192 |
def assertFormatEqual(self, expected: str, actual: str) -> None: |
| 193 |
_assert_format_equal(expected, actual) |
| 194 |
|
| 195 |
|
| 196 |
def get_base_dir(data: bool) -> Path: |
| 197 |
return DATA_DIR if data else PROJECT_ROOT |
| 198 |
|
| 199 |
|
| 200 |
def all_data_cases(subdir_name: str, data: bool = True) -> list[str]: |
| 201 |
cases_dir = get_base_dir(data) / subdir_name |
| 202 |
assert cases_dir.is_dir() |
| 203 |
return [case_path.stem for case_path in cases_dir.iterdir()] |
| 204 |
|
| 205 |
|
| 206 |
def get_case_path( |
| 207 |
subdir_name: str, name: str, data: bool = True, suffix: str = PYTHON_SUFFIX |
| 208 |
) -> Path: |
| 209 |
"""Get case path from name""" |
| 210 |
case_path = get_base_dir(data) / subdir_name / name |
| 211 |
if not name.endswith(ALLOWED_SUFFIXES): |
| 212 |
case_path = case_path.with_suffix(suffix) |
| 213 |
assert case_path.is_file(), f"{case_path} is not a file." |
| 214 |
return case_path |
| 215 |
|
| 216 |
|
| 217 |
def read_data_with_mode( |
| 218 |
subdir_name: str, name: str, data: bool = True |
| 219 |
) -> tuple[TestCaseArgs, str, str]: |
| 220 |
"""read_data_with_mode('test_name') -> Mode(), 'input', 'output'""" |
| 221 |
return read_data_from_file(get_case_path(subdir_name, name, data)) |
| 222 |
|
| 223 |
|
| 224 |
def read_data(subdir_name: str, name: str, data: bool = True) -> tuple[str, str]: |
| 225 |
"""read_data('test_name') -> 'input', 'output'""" |
| 226 |
_, input, output = read_data_with_mode(subdir_name, name, data) |
| 227 |
return input, output |
| 228 |
|
| 229 |
|
| 230 |
def _parse_minimum_version(version: str) -> tuple[int, int]: |
| 231 |
major, minor = version.split(".") |
| 232 |
return int(major), int(minor) |
| 233 |
|
| 234 |
|
| 235 |
@functools.lru_cache |
| 236 |
def get_flags_parser() -> argparse.ArgumentParser: |
| 237 |
parser = argparse.ArgumentParser() |
| 238 |
parser.add_argument( |
| 239 |
"--target-version", |
| 240 |
action="store", |
| 241 |
type=lambda val: (TargetVersion[val.upper()],), |
| 242 |
default=(), |
| 243 |
) |
| 244 |
parser.add_argument("--line-length", default=DEFAULT_LINE_LENGTH, type=int) |
| 245 |
parser.add_argument( |
| 246 |
"--skip-string-normalization", default=False, action="store_true" |
| 247 |
) |
| 248 |
parser.add_argument("--pyi", default=False, action="store_true") |
| 249 |
parser.add_argument("--ipynb", default=False, action="store_true") |
| 250 |
parser.add_argument( |
| 251 |
"--skip-magic-trailing-comma", default=False, action="store_true" |
| 252 |
) |
| 253 |
parser.add_argument("--preview", default=False, action="store_true") |
| 254 |
parser.add_argument("--unstable", default=False, action="store_true") |
| 255 |
parser.add_argument("--fast", default=False, action="store_true") |
| 256 |
parser.add_argument( |
| 257 |
"--minimum-version", |
| 258 |
type=_parse_minimum_version, |
| 259 |
default=None, |
| 260 |
help=( |
| 261 |
"Minimum version of Python where this test case is parseable. If this is" |
| 262 |
" set, the test case will be run twice: once without the specified" |
| 263 |
" --target-version, and once with --target-version set to exactly the" |
| 264 |
" specified version. This ensures that Black's autodetection of the target" |
| 265 |
" version works correctly." |
| 266 |
), |
| 267 |
) |
| 268 |
parser.add_argument("--line-ranges", action="append") |
| 269 |
parser.add_argument( |
| 270 |
"--no-preview-line-length-1", |
| 271 |
default=False, |
| 272 |
action="store_true", |
| 273 |
help=( |
| 274 |
"Don't run in preview mode with --line-length=1, as that's known to cause a" |
| 275 |
" crash" |
| 276 |
), |
| 277 |
) |
| 278 |
return parser |
| 279 |
|
| 280 |
|
| 281 |
def parse_mode(flags_line: str) -> TestCaseArgs: |
| 282 |
parser = get_flags_parser() |
| 283 |
args = parser.parse_args(shlex.split(flags_line)) |
| 284 |
mode = black.Mode( |
| 285 |
target_versions=set(args.target_version), |
| 286 |
line_length=args.line_length, |
| 287 |
string_normalization=not args.skip_string_normalization, |
| 288 |
is_pyi=args.pyi, |
| 289 |
is_ipynb=args.ipynb, |
| 290 |
magic_trailing_comma=not args.skip_magic_trailing_comma, |
| 291 |
preview=args.preview, |
| 292 |
unstable=args.unstable, |
| 293 |
) |
| 294 |
if args.line_ranges: |
| 295 |
lines = parse_line_ranges(args.line_ranges) |
| 296 |
else: |
| 297 |
lines = [] |
| 298 |
return TestCaseArgs( |
| 299 |
mode=mode, |
| 300 |
fast=args.fast, |
| 301 |
minimum_version=args.minimum_version, |
| 302 |
lines=lines, |
| 303 |
no_preview_line_length_1=args.no_preview_line_length_1, |
| 304 |
) |
| 305 |
|
| 306 |
|
| 307 |
def read_data_from_file(file_name: Path) -> tuple[TestCaseArgs, str, str]: |
| 308 |
with open(file_name, encoding="utf8") as test: |
| 309 |
lines = test.readlines() |
| 310 |
_input: list[str] = [] |
| 311 |
_output: list[str] = [] |
| 312 |
result = _input |
| 313 |
mode = TestCaseArgs() |
| 314 |
for line in lines: |
| 315 |
if not _input and line.startswith("# flags: "): |
| 316 |
mode = parse_mode(line[len("# flags: ") :]) |
| 317 |
if mode.lines: |
| 318 |
# Retain the `# flags: ` line when using --line-ranges=. This requires |
| 319 |
# the `# output` section to also include this line, but retaining the |
| 320 |
# line is important to make the line ranges match what you see in the |
| 321 |
# test file. |
| 322 |
result.append(line) |
| 323 |
continue |
| 324 |
line = line.replace(EMPTY_LINE, "") |
| 325 |
if line.rstrip() == "# output": |
| 326 |
result = _output |
| 327 |
continue |
| 328 |
|
| 329 |
result.append(line) |
| 330 |
if _input and not _output: |
| 331 |
# If there's no output marker, treat the entire file as already pre-formatted. |
| 332 |
_output = _input[:] |
| 333 |
return mode, "".join(_input).strip() + "\n", "".join(_output).strip() + "\n" |
| 334 |
|
| 335 |
|
| 336 |
def read_jupyter_notebook(subdir_name: str, name: str, data: bool = True) -> str: |
| 337 |
return read_jupyter_notebook_from_file( |
| 338 |
get_case_path(subdir_name, name, data, suffix=".ipynb") |
| 339 |
) |
| 340 |
|
| 341 |
|
| 342 |
def read_jupyter_notebook_from_file(file_name: Path) -> str: |
| 343 |
with open(file_name, mode="rb") as fd: |
| 344 |
content_bytes = fd.read() |
| 345 |
return content_bytes.decode() |
| 346 |
|
| 347 |
|
| 348 |
@contextmanager |
| 349 |
def change_directory(path: Path) -> Iterator[None]: |
| 350 |
"""Context manager to temporarily chdir to a different directory.""" |
| 351 |
previous_dir = os.getcwd() |
| 352 |
try: |
| 353 |
os.chdir(path) |
| 354 |
yield |
| 355 |
finally: |
| 356 |
os.chdir(previous_dir) |