+DEFAULT_MODE = black.Mode()
+ff = partial(black.format_file_in_place, mode=DEFAULT_MODE, fast=True)
+fs = partial(black.format_str, mode=DEFAULT_MODE)
+
+
+def _assert_format_equal(expected: str, actual: str) -> None:
+ if actual != expected and (conftest.PRINT_FULL_TREE or conftest.PRINT_TREE_DIFF):
+ bdv: DebugVisitor[Any]
+ actual_out: str = ""
+ expected_out: str = ""
+ if conftest.PRINT_FULL_TREE:
+ out("Expected tree:", fg="green")
+ try:
+ exp_node = black.lib2to3_parse(expected)
+ bdv = DebugVisitor(print_output=conftest.PRINT_FULL_TREE)
+ list(bdv.visit(exp_node))
+ expected_out = "\n".join(bdv.list_output)
+ except Exception as ve:
+ err(str(ve))
+ if conftest.PRINT_FULL_TREE:
+ out("Actual tree:", fg="red")
+ try:
+ exp_node = black.lib2to3_parse(actual)
+ bdv = DebugVisitor(print_output=conftest.PRINT_FULL_TREE)
+ list(bdv.visit(exp_node))
+ actual_out = "\n".join(bdv.list_output)
+ except Exception as ve:
+ err(str(ve))
+ if conftest.PRINT_TREE_DIFF:
+ out("Tree Diff:")
+ out(
+ diff(expected_out, actual_out, "expected tree", "actual tree")
+ or "Trees do not differ"
+ )
+
+ if actual != expected:
+ out(diff(expected, actual, "expected", "actual"))
+
+ assert actual == expected
+
+
+class FormatFailure(Exception):
+ """Used to wrap failures when assert_format() runs in an extra mode."""
+
+
+def assert_format(
+ source: str,
+ expected: str,
+ mode: black.Mode = DEFAULT_MODE,
+ *,
+ fast: bool = False,
+ minimum_version: Optional[Tuple[int, int]] = None,
+) -> None:
+ """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.
+ """
+ _assert_format_inner(
+ source, expected, mode, fast=fast, minimum_version=minimum_version
+ )
+
+ # For both preview and non-preview tests, ensure that Black doesn't crash on
+ # this code, but don't pass "expected" because the precise output may differ.