Debian Codegraph @

tests/unit/profiles/test_black.py

raw
1 from typing import Any
2
3 import black
4 from black.report import NothingChanged
5
6 import isort
7
8
9 def black_format(code: str, is_pyi: bool = False, line_length: int = 88) -> str:
10 """Formats the provided code snippet using black"""
11 try:
12 return black.format_file_contents(
13 code,
14 fast=True,
15 mode=black.FileMode(
16 is_pyi=is_pyi,
17 line_length=line_length,
18 ),
19 )
20 except NothingChanged:
21 return code
22
23
24 def black_test(
25 code: str, expected_output: str = "", *, is_pyi: bool = False, **config_kwargs: Any
26 ) -> None:
27 """Tests that the given code:
28 - Behaves the same when formatted multiple times with isort.
29 - Agrees with black formatting.
30 - Matches the desired output or itself if none is provided.
31 """
32 expected_output = expected_output or code
33 config_kwargs = {
34 "extension": "pyi" if is_pyi else None,
35 "profile": "black",
36 **config_kwargs,
37 }
38
39 # output should stay consistent over multiple runs
40 output = isort.code(code, **config_kwargs)
41 assert output == isort.code(code, **config_kwargs)
42
43 # output should agree with black
44 black_output = black_format(output, is_pyi=is_pyi)
45 assert output == black_output
46
47 # output should match expected output
48 assert output == expected_output
49
50
51 def test_black_snippet_one() -> None:
52 """Test consistent code formatting between isort and black for code snippet from black repository.
53 See: https://github.com/psf/black/blob/master/tests/test_black.py
54 """
55 black_test(
56 """#!/usr/bin/env python3
57 import asyncio
58 import logging
59 from concurrent.futures import ThreadPoolExecutor
60 from contextlib import contextmanager
61 from dataclasses import replace
62 from functools import partial
63 import inspect
64 from io import BytesIO, TextIOWrapper
65 import os
66 from pathlib import Path
67 from platform import system
68 import regex as re
69 import sys
70 from tempfile import TemporaryDirectory
71 import types
72 from typing import (
73 Any,
74 BinaryIO,
75 Callable,
76 Dict,
77 Generator,
78 List,
79 Tuple,
80 Iterator,
81 TypeVar,
82 )
83 import unittest
84 from unittest.mock import patch, MagicMock
85
86 import click
87 from click import unstyle
88 from click.testing import CliRunner
89
90 import black
91 from black import Feature, TargetVersion
92
93 try:
94 import blackd
95 from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
96 from aiohttp import web
97 except ImportError:
98 has_blackd_deps = False
99 else:
100 has_blackd_deps = True
101
102 from pathspec import PathSpec
103
104 # Import other test classes
105 from .test_primer import PrimerCLITests # noqa: F401
106
107
108 DEFAULT_MODE = black.FileMode(experimental_string_processing=True)
109 """,
110 """#!/usr/bin/env python3
111 import asyncio
112 import inspect
113 import logging
114 import os
115 import sys
116 import types
117 import unittest
118 from concurrent.futures import ThreadPoolExecutor
119 from contextlib import contextmanager
120 from dataclasses import replace
121 from functools import partial
122 from io import BytesIO, TextIOWrapper
123 from pathlib import Path
124 from platform import system
125 from tempfile import TemporaryDirectory
126 from typing import (
127 Any,
128 BinaryIO,
129 Callable,
130 Dict,
131 Generator,
132 Iterator,
133 List,
134 Tuple,
135 TypeVar,
136 )
137 from unittest.mock import MagicMock, patch
138
139 import black
140 import click
141 import regex as re
142 from black import Feature, TargetVersion
143 from click import unstyle
144 from click.testing import CliRunner
145
146 try:
147 import blackd
148 from aiohttp import web
149 from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
150 except ImportError:
151 has_blackd_deps = False
152 else:
153 has_blackd_deps = True
154
155 from pathspec import PathSpec
156
157 # Import other test classes
158 from .test_primer import PrimerCLITests # noqa: F401
159
160 DEFAULT_MODE = black.FileMode(experimental_string_processing=True)
161 """,
162 )
163
164
165 def test_black_snippet_two() -> None:
166 """Test consistent code formatting between isort and black for code snippet from black repository.
167 See: https://github.com/psf/black/blob/master/tests/test_primer.py
168 """
169 black_test(
170 '''#!/usr/bin/env python3
171
172 import asyncio
173 import sys
174 import unittest
175 from contextlib import contextmanager
176 from copy import deepcopy
177 from io import StringIO
178 from os import getpid
179 from pathlib import Path
180 from platform import system
181 from subprocess import CalledProcessError
182 from tempfile import TemporaryDirectory, gettempdir
183 from typing import Any, Callable, Generator, Iterator, Tuple
184 from unittest.mock import Mock, patch
185
186 from click.testing import CliRunner
187
188 from black_primer import cli, lib
189
190
191 EXPECTED_ANALYSIS_OUTPUT = """\
192 -- primer results 📊 --
193 68 / 69 succeeded (98.55%) ✅
194 1 / 69 FAILED (1.45%) 💩
195 - 0 projects disabled by config
196 - 0 projects skipped due to Python version
197 - 0 skipped due to long checkout
198 Failed projects:
199 ## black:
200 - Returned 69
201 - stdout:
202 Black didn't work
203 """
204 ''',
205 '''#!/usr/bin/env python3
206
207 import asyncio
208 import sys
209 import unittest
210 from contextlib import contextmanager
211 from copy import deepcopy
212 from io import StringIO
213 from os import getpid
214 from pathlib import Path
215 from platform import system
216 from subprocess import CalledProcessError
217 from tempfile import TemporaryDirectory, gettempdir
218 from typing import Any, Callable, Generator, Iterator, Tuple
219 from unittest.mock import Mock, patch
220
221 from black_primer import cli, lib
222 from click.testing import CliRunner
223
224 EXPECTED_ANALYSIS_OUTPUT = """-- primer results 📊 --
225 68 / 69 succeeded (98.55%) ✅
226 1 / 69 FAILED (1.45%) 💩
227 - 0 projects disabled by config
228 - 0 projects skipped due to Python version
229 - 0 skipped due to long checkout
230 Failed projects:
231 ## black:
232 - Returned 69
233 - stdout:
234 Black didn't work
235 """
236 ''',
237 )
238
239
240 def test_black_snippet_three() -> None:
241 """Test consistent code formatting between isort and black for code snippet from black repository.
242 See: https://github.com/psf/black/blob/master/src/black/__init__.py
243 """
244 black_test(
245 """import ast
246 import asyncio
247 from abc import ABC, abstractmethod
248 from collections import defaultdict
249 from concurrent.futures import Executor, ThreadPoolExecutor, ProcessPoolExecutor
250 from contextlib import contextmanager
251 from datetime import datetime
252 from enum import Enum
253 from functools import lru_cache, partial, wraps
254 import io
255 import itertools
256 import logging
257 from multiprocessing import Manager, freeze_support
258 import os
259 from pathlib import Path
260 import pickle
261 import regex as re
262 import signal
263 import sys
264 import tempfile
265 import tokenize
266 import traceback
267 from typing import (
268 Any,
269 Callable,
270 Collection,
271 Dict,
272 Generator,
273 Generic,
274 Iterable,
275 Iterator,
276 List,
277 Optional,
278 Pattern,
279 Sequence,
280 Set,
281 Sized,
282 Tuple,
283 Type,
284 TypeVar,
285 Union,
286 cast,
287 TYPE_CHECKING,
288 )
289 from typing_extensions import Final
290 from mypy_extensions import mypyc_attr
291
292 from appdirs import user_cache_dir
293 from dataclasses import dataclass, field, replace
294 import click
295 import toml
296 from typed_ast import ast3, ast27
297 from pathspec import PathSpec
298
299 # lib2to3 fork
300 from blib2to3.pytree import Node, Leaf, type_repr
301 from blib2to3 import pygram, pytree
302 from blib2to3.pgen2 import driver, token
303 from blib2to3.pgen2.grammar import Grammar
304 from blib2to3.pgen2.parse import ParseError
305
306 from _black_version import version as __version__
307
308 if TYPE_CHECKING:
309 import colorama # noqa: F401
310
311 DEFAULT_LINE_LENGTH = 88
312 """,
313 """import ast
314 import asyncio
315 import io
316 import itertools
317 import logging
318 import os
319 import pickle
320 import signal
321 import sys
322 import tempfile
323 import tokenize
324 import traceback
325 from abc import ABC, abstractmethod
326 from collections import defaultdict
327 from concurrent.futures import Executor, ProcessPoolExecutor, ThreadPoolExecutor
328 from contextlib import contextmanager
329 from dataclasses import dataclass, field, replace
330 from datetime import datetime
331 from enum import Enum
332 from functools import lru_cache, partial, wraps
333 from multiprocessing import Manager, freeze_support
334 from pathlib import Path
335 from typing import (
336 TYPE_CHECKING,
337 Any,
338 Callable,
339 Collection,
340 Dict,
341 Generator,
342 Generic,
343 Iterable,
344 Iterator,
345 List,
346 Optional,
347 Pattern,
348 Sequence,
349 Set,
350 Sized,
351 Tuple,
352 Type,
353 TypeVar,
354 Union,
355 cast,
356 )
357
358 import click
359 import regex as re
360 import toml
361 from _black_version import version as __version__
362 from appdirs import user_cache_dir
363 from blib2to3 import pygram, pytree
364 from blib2to3.pgen2 import driver, token
365 from blib2to3.pgen2.grammar import Grammar
366 from blib2to3.pgen2.parse import ParseError
367
368 # lib2to3 fork
369 from blib2to3.pytree import Leaf, Node, type_repr
370 from mypy_extensions import mypyc_attr
371 from pathspec import PathSpec
372 from typed_ast import ast3, ast27
373 from typing_extensions import Final
374
375 if TYPE_CHECKING:
376 import colorama # noqa: F401
377
378 DEFAULT_LINE_LENGTH = 88
379 """,
380 )
381
382
383 def test_black_pyi_file() -> None:
384 """Test consistent code formatting between isort and black for `.pyi` files.
385
386 black only allows no more than two consecutive blank lines in a `.pyi` file.
387 """
388
389 black_test(
390 """# comment
391
392
393 import math
394
395 from typing import Sequence
396 import numpy as np
397
398
399 def add(a: np.ndarray, b: np.ndarray) -> np.ndarray: ...
400
401
402 def sub(a: np.ndarray, b: np.ndarray) -> np.ndarray: ...
403 """,
404 """# comment
405
406
407 import math
408 from typing import Sequence
409
410 import numpy as np
411
412
413 def add(a: np.ndarray, b: np.ndarray) -> np.ndarray: ...
414
415
416 def sub(a: np.ndarray, b: np.ndarray) -> np.ndarray: ...
417 """,
418 is_pyi=False,
419 lines_before_imports=2,
420 lines_after_imports=2,
421 )
422
423 black_test(
424 """# comment
425
426
427 import math
428
429 from typing import Sequence
430 import numpy as np
431
432
433 def add(a: np.ndarray, b: np.ndarray) -> np.ndarray: ...
434 def sub(a: np.ndarray, b: np.ndarray) -> np.ndarray: ...
435 """,
436 """# comment
437
438 import math
439 from typing import Sequence
440
441 import numpy as np
442
443 def add(a: np.ndarray, b: np.ndarray) -> np.ndarray: ...
444 def sub(a: np.ndarray, b: np.ndarray) -> np.ndarray: ...
445 """,
446 is_pyi=True,
447 lines_before_imports=2, # will be ignored
448 lines_after_imports=2, # will be ignored
449 )
450
451
452 def test_black_trailing_comma() -> None:
453 black_test(
454 "from x import (a, b, c,)\n",
455 """\
456 from x import (
457 a,
458 b,
459 c,
460 )
461 """,
462 )