Convenience function to check that Black formats as expected. You can pass @minimum_version if you're passing code with newer syntax to guard safety guards so they don't just crash with a SyntaxError. Please note this is separate from TargetVerson Mode configuration.
(
source: str,
expected: str,
mode: black.Mode = DEFAULT_MODE,
*,
fast: bool = False,
minimum_version: tuple[int, int] | None = None,
lines: Collection[tuple[int, int]] = (),
no_preview_line_length_1: bool = False,
)
| 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), |