python -m venv .venv
source .venv/bin/activate
pip install -r test_requirements.txt
pip install -e .
pip install ipdb

    def test_pep_572_version_detection(self) -> None:
        source, _ = read_data("cases", "pep_572")
        root = black.lib2to3_parse(source)
        features = black.get_features_used(root)
        self.assertIn(black.Feature.ASSIGNMENT_EXPRESSIONS, features)
        versions = black.detect_target_versions(root)
        self.assertIn(black.TargetVersion.PY38, versions)

    def test_pep_572_version_detection(self) -> None:
        source, _ = read_data("cases", "pep_572")
        root = black.lib2to3_parse(source)
        features = black.get_features_used(root)
        self.assertIn(black.Feature.ASSIGNMENT_EXPRESSIONS, features)
        versions = black.detect_target_versions(root)
        <AssertPlaceHolder>

def detect_target_versions(
    node: Node, *, future_imports: Optional[set[str]] = None
) -> set[TargetVersion]:
    """Detect the version to target based on the nodes used."""
    features = get_features_used(node, future_imports=future_imports)
    return {
        version for version in TargetVersion if features <= VERSION_TO_FEATURES[version]
    }


    def test_detect_pos_only_arguments(self) -> None:
        source, _ = read_data("cases", "pep_570")
        root = black.lib2to3_parse(source)
        features = black.get_features_used(root)
        self.assertIn(black.Feature.POS_ONLY_ARGUMENTS, features)
        versions = black.detect_target_versions(root)
        self.assertIn(black.TargetVersion.PY38, versions)

    def test_detect_pos_only_arguments(self) -> None:
        source, _ = read_data("cases", "pep_570")
        root = black.lib2to3_parse(source)
        features = black.get_features_used(root)
        self.assertIn(black.Feature.POS_ONLY_ARGUMENTS, features)
        versions = black.detect_target_versions(root)
        <AssertPlaceHolder>


    def test_detect_debug_f_strings(self) -> None:
        root = black.lib2to3_parse("""f"{x=}" """)
        features = black.get_features_used(root)
        self.assertIn(black.Feature.DEBUG_F_STRINGS, features)
        versions = black.detect_target_versions(root)
        self.assertIn(black.TargetVersion.PY38, versions)

        root = black.lib2to3_parse(
            """f"{x}"\nf'{"="}'\nf'{(x:=5)}'\nf'{f(a="3=")}'\nf'{x:=10}'\n"""
        )
        features = black.get_features_used(root)
        self.assertNotIn(black.Feature.DEBUG_F_STRINGS, features)

        root = black.lib2to3_parse(
            """f"heard a rumour that { f'{1+1=}' } ... seems like it could be true" """
        )
        features = black.get_features_used(root)
        self.assertIn(black.Feature.DEBUG_F_STRINGS, features)

    def test_detect_debug_f_strings(self) -> None:
        root = black.lib2to3_parse("""f"{x=}" """)
        features = black.get_features_used(root)
        self.assertIn(black.Feature.DEBUG_F_STRINGS, features)
        versions = black.detect_target_versions(root)
        <AssertPlaceHolder>

        root = black.lib2to3_parse(
            """f"{x}"\nf'{"="}'\nf'{(x:=5)}'\nf'{f(a="3=")}'\nf'{x:=10}'\n"""
        )
        features = black.get_features_used(root)
        self.assertNotIn(black.Feature.DEBUG_F_STRINGS, features)

        root = black.lib2to3_parse(
            """f"heard a rumour that { f'{1+1=}' } ... seems like it could be true" """
        )
        features = black.get_features_used(root)
        self.assertIn(black.Feature.DEBUG_F_STRINGS, features)


    def test_get_future_imports(self) -> None:
        node = black.lib2to3_parse("\n")
        self.assertEqual(set(), black.get_future_imports(node))
        node = black.lib2to3_parse("from __future__ import black\n")
        self.assertEqual({"black"}, black.get_future_imports(node))
        node = black.lib2to3_parse("from __future__ import multiple, imports\n")
        self.assertEqual({"multiple", "imports"}, black.get_future_imports(node))
        node = black.lib2to3_parse("from __future__ import (parenthesized, imports)\n")
        self.assertEqual({"parenthesized", "imports"}, black.get_future_imports(node))
        node = black.lib2to3_parse(
            "from __future__ import multiple\nfrom __future__ import imports\n"
        )
        self.assertEqual({"multiple", "imports"}, black.get_future_imports(node))
        node = black.lib2to3_parse("# comment\nfrom __future__ import black\n")
        self.assertEqual({"black"}, black.get_future_imports(node))
        node = black.lib2to3_parse('"""docstring"""\nfrom __future__ import black\n')
        self.assertEqual({"black"}, black.get_future_imports(node))
        node = black.lib2to3_parse("some(other, code)\nfrom __future__ import black\n")
        self.assertEqual(set(), black.get_future_imports(node))
        node = black.lib2to3_parse("from some.module import black\n")
        self.assertEqual(set(), black.get_future_imports(node))
        node = black.lib2to3_parse(
            "from __future__ import unicode_literals as _unicode_literals"
        )
        self.assertEqual({"unicode_literals"}, black.get_future_imports(node))
        node = black.lib2to3_parse(
            "from __future__ import unicode_literals as _lol, print"
        )
        self.assertEqual({"unicode_literals", "print"}, black.get_future_imports(node))

    def test_get_future_imports(self) -> None:
        node = black.lib2to3_parse("\n")
        self.assertEqual(set(), black.get_future_imports(node))
        node = black.lib2to3_parse("from __future__ import black\n")
        self.assertEqual({"black"}, black.get_future_imports(node))
        node = black.lib2to3_parse("from __future__ import multiple, imports\n")
        <AssertPlaceHolder>
        node = black.lib2to3_parse("from __future__ import (parenthesized, imports)\n")
        self.assertEqual({"parenthesized", "imports"}, black.get_future_imports(node))
        node = black.lib2to3_parse(
            "from __future__ import multiple\nfrom __future__ import imports\n"
        )
        <AssertPlaceHolder>
        node = black.lib2to3_parse("# comment\nfrom __future__ import black\n")
        self.assertEqual({"black"}, black.get_future_imports(node))
        node = black.lib2to3_parse('"""docstring"""\nfrom __future__ import black\n')
        self.assertEqual({"black"}, black.get_future_imports(node))
        node = black.lib2to3_parse("some(other, code)\nfrom __future__ import black\n")
        self.assertEqual(set(), black.get_future_imports(node))
        node = black.lib2to3_parse("from some.module import black\n")
        self.assertEqual(set(), black.get_future_imports(node))
        node = black.lib2to3_parse(
            "from __future__ import unicode_literals as _unicode_literals"
        )
        self.assertEqual({"unicode_literals"}, black.get_future_imports(node))
        node = black.lib2to3_parse(
            "from __future__ import unicode_literals as _lol, print"
        )
        self.assertEqual({"unicode_literals", "print"}, black.get_future_imports(node))

def get_future_imports(node: Node) -> set[str]:
    """Return a set of __future__ imports in the file."""
    imports: set[str] = set()

    def get_imports_from_children(children: list[LN]) -> Generator[str, None, None]:
        for child in children:
            if isinstance(child, Leaf):
                if child.type == token.NAME:
                    yield child.value

            elif child.type == syms.import_as_name:
                orig_name = child.children[0]
                assert isinstance(orig_name, Leaf), "Invalid syntax parsing imports"
                assert orig_name.type == token.NAME, "Invalid syntax parsing imports"
                yield orig_name.value

            elif child.type == syms.import_as_names:
                yield from get_imports_from_children(child.children)

            else:
                raise AssertionError("Invalid syntax parsing imports")

    for child in node.children:
        if child.type != syms.simple_stmt:
            break

        first_child = child.children[0]
        if isinstance(first_child, Leaf):
            # Continue looking if we see a docstring; otherwise stop.
            if (
                len(child.children) == 2
                and first_child.type == token.STRING
                and child.children[1].type == token.NEWLINE
            ):
                continue

            break

        elif first_child.type == syms.import_from:
            module_name = first_child.children[1]
            if not isinstance(module_name, Leaf) or module_name.value != "__future__":
                break

            imports |= set(get_imports_from_children(first_child.children[3:]))
        else:
            break

    return imports


    def test_endmarker(self) -> None:
        n = black.lib2to3_parse("\n")
        self.assertEqual(n.type, black.syms.file_input)
        self.assertEqual(len(n.children), 1)
        self.assertEqual(n.children[0].type, black.token.ENDMARKER)

    def test_endmarker(self) -> None:
        n = black.lib2to3_parse("\n")
        self.assertEqual(n.type, black.syms.file_input)
        <AssertPlaceHolder>
        self.assertEqual(n.children[0].type, black.token.ENDMARKER)

def lib2to3_parse(
    src_txt: str, target_versions: Collection[TargetVersion] = ()
) -> Node:
    """Given a string with source, return the lib2to3 Node."""
    if not src_txt.endswith("\n"):
        src_txt += "\n"

    grammars = get_grammars(set(target_versions))
    if target_versions:
        max_tv = max(target_versions, key=lambda tv: tv.value)
        tv_str = f" for target version {max_tv.pretty()}"
    else:
        tv_str = ""

    errors = {}
    for grammar in grammars:
        drv = driver.Driver(grammar)
        try:
            result = drv.parse_string(src_txt, False)
            break

        except ParseError as pe:
            lineno, column = pe.context[1]
            lines = src_txt.splitlines()
            try:
                faulty_line = lines[lineno - 1]
            except IndexError:
                faulty_line = "<line number missing in source>"
            errors[grammar.version] = InvalidInput(
                f"Cannot parse{tv_str}: {lineno}:{column}: {faulty_line}"
            )

        except TokenError as te:
            # In edge cases these are raised; and typically don't have a "faulty_line".
            lineno, column = te.args[1]
            errors[grammar.version] = InvalidInput(
                f"Cannot parse{tv_str}: {lineno}:{column}: {te.args[0]}"
            )

    else:
        # Choose the latest version when raising the actual parsing error.
        assert len(errors) >= 1
        exc = errors[max(errors)]
        raise exc from None

    if isinstance(result, Leaf):
        result = Node(syms.file_input, [result])
    return result


    def test_single_file_force_pyi(self) -> None:
        pyi_mode = replace(DEFAULT_MODE, is_pyi=True)
        contents, expected = read_data("miscellaneous", "force_pyi")
        with cache_dir() as workspace:
            path = (workspace / "file.py").resolve()
            path.write_text(contents, encoding="utf-8")
            self.invokeBlack([str(path), "--pyi"])
            actual = path.read_text(encoding="utf-8")
            # verify cache with --pyi is separate
            pyi_cache = black.Cache.read(pyi_mode)
            assert not pyi_cache.is_changed(path)
            normal_cache = black.Cache.read(DEFAULT_MODE)
            assert normal_cache.is_changed(path)
        self.assertFormatEqual(expected, actual)
        black.assert_equivalent(contents, actual)
        black.assert_stable(contents, actual, pyi_mode)

    def test_single_file_force_pyi(self) -> None:
        pyi_mode = replace(DEFAULT_MODE, is_pyi=True)
        contents, expected = read_data("miscellaneous", "force_pyi")
        with cache_dir() as workspace:
            path = (workspace / "file.py").resolve()
            path.write_text(contents, encoding="utf-8")
            self.invokeBlack([str(path), "--pyi"])
            actual = path.read_text(encoding="utf-8")
            # verify cache with --pyi is separate
            pyi_cache = black.Cache.read(pyi_mode)
            assert not pyi_cache.is_changed(path)
            normal_cache = black.Cache.read(DEFAULT_MODE)
            assert normal_cache.is_changed(path)
        <AssertPlaceHolder>
        black.assert_equivalent(contents, actual)
        black.assert_stable(contents, actual, pyi_mode)

    @classmethod
    def read(cls, mode: Mode) -> Self:
        """Read the cache if it exists and is well-formed.

        If it is not well-formed, the call to write later should
        resolve the issue.
        """
        cache_file = get_cache_file(mode)
        try:
            exists = cache_file.exists()
        except OSError as e:
            # Likely file too long; see #4172 and #4174
            err(f"Unable to read cache file {cache_file} due to {e}")
            return cls(mode, cache_file)
        if not exists:
            return cls(mode, cache_file)

        with cache_file.open("rb") as fobj:
            try:
                data: dict[str, tuple[float, int, str]] = pickle.load(fobj)
                file_data = {k: FileData(*v) for k, v in data.items()}
            except (pickle.UnpicklingError, ValueError, IndexError):
                return cls(mode, cache_file)

        return cls(mode, cache_file, file_data)


    @event_loop()
    def test_multi_file_force_pyi(self) -> None:
        reg_mode = DEFAULT_MODE
        pyi_mode = replace(DEFAULT_MODE, is_pyi=True)
        contents, expected = read_data("miscellaneous", "force_pyi")
        with cache_dir() as workspace:
            paths = [
                (workspace / "file1.py").resolve(),
                (workspace / "file2.py").resolve(),
            ]
            for path in paths:
                path.write_text(contents, encoding="utf-8")
            self.invokeBlack([str(p) for p in paths] + ["--pyi"])
            for path in paths:
                actual = path.read_text(encoding="utf-8")
                self.assertEqual(actual, expected)
            # verify cache with --pyi is separate
            pyi_cache = black.Cache.read(pyi_mode)
            normal_cache = black.Cache.read(reg_mode)
            for path in paths:
                assert not pyi_cache.is_changed(path)
                assert normal_cache.is_changed(path)

    @event_loop()
    def test_multi_file_force_pyi(self) -> None:
        reg_mode = DEFAULT_MODE
        pyi_mode = replace(DEFAULT_MODE, is_pyi=True)
        contents, expected = read_data("miscellaneous", "force_pyi")
        with cache_dir() as workspace:
            paths = [
                (workspace / "file1.py").resolve(),
                (workspace / "file2.py").resolve(),
            ]
            for path in paths:
                path.write_text(contents, encoding="utf-8")
            self.invokeBlack([str(p) for p in paths] + ["--pyi"])
            for path in paths:
                actual = path.read_text(encoding="utf-8")
                self.assertEqual(actual, expected)
            # verify cache with --pyi is separate
            pyi_cache = black.Cache.read(pyi_mode)
            normal_cache = black.Cache.read(reg_mode)
            for path in paths:
                <AssertPlaceHolder>
                assert normal_cache.is_changed(path)

    def is_changed(self, source: Path) -> bool:
        """Check if source has changed compared to cached version."""
        res_src = source.resolve()
        old = self.file_data.get(str(res_src))
        if old is None:
            return True

        st = res_src.stat()
        if st.st_size != old.st_size:
            return True
        if st.st_mtime != old.st_mtime:
            new_hash = Cache.hash_digest(res_src)
            if new_hash != old.hash:
                return True
        return False


    def test_single_file_force_py36(self) -> None:
        reg_mode = DEFAULT_MODE
        py36_mode = replace(DEFAULT_MODE, target_versions=PY36_VERSIONS)
        source, expected = read_data("miscellaneous", "force_py36")
        with cache_dir() as workspace:
            path = (workspace / "file.py").resolve()
            path.write_text(source, encoding="utf-8")
            self.invokeBlack([str(path), *PY36_ARGS])
            actual = path.read_text(encoding="utf-8")
            # verify cache with --target-version is separate
            py36_cache = black.Cache.read(py36_mode)
            assert not py36_cache.is_changed(path)
            normal_cache = black.Cache.read(reg_mode)
            assert normal_cache.is_changed(path)
        self.assertEqual(actual, expected)

    def test_single_file_force_py36(self) -> None:
        reg_mode = DEFAULT_MODE
        py36_mode = replace(DEFAULT_MODE, target_versions=PY36_VERSIONS)
        source, expected = read_data("miscellaneous", "force_py36")
        with cache_dir() as workspace:
            path = (workspace / "file.py").resolve()
            path.write_text(source, encoding="utf-8")
            self.invokeBlack([str(path), *PY36_ARGS])
            actual = path.read_text(encoding="utf-8")
            # verify cache with --target-version is separate
            py36_cache = black.Cache.read(py36_mode)
            assert not py36_cache.is_changed(path)
            normal_cache = black.Cache.read(reg_mode)
            assert normal_cache.is_changed(path)
        <AssertPlaceHolder>


    def test_parse_pyproject_toml(self) -> None:
        test_toml_file = THIS_DIR / "test.toml"
        config = black.parse_pyproject_toml(str(test_toml_file))
        self.assertEqual(config["verbose"], 1)
        self.assertEqual(config["check"], "no")
        self.assertEqual(config["diff"], "y")
        self.assertEqual(config["color"], True)
        self.assertEqual(config["line_length"], 79)
        self.assertEqual(config["target_version"], ["py36", "py37", "py38"])
        self.assertEqual(config["python_cell_magics"], ["custom1", "custom2"])
        self.assertEqual(config["exclude"], r"\.pyi?$")
        self.assertEqual(config["include"], r"\.py?$")

    def test_parse_pyproject_toml(self) -> None:
        test_toml_file = THIS_DIR / "test.toml"
        config = black.parse_pyproject_toml(str(test_toml_file))
        self.assertEqual(config["verbose"], 1)
        self.assertEqual(config["check"], "no")
        self.assertEqual(config["diff"], "y")
        self.assertEqual(config["color"], True)
        <AssertPlaceHolder>
        self.assertEqual(config["target_version"], ["py36", "py37", "py38"])
        self.assertEqual(config["python_cell_magics"], ["custom1", "custom2"])
        self.assertEqual(config["exclude"], r"\.pyi?$")
        self.assertEqual(config["include"], r"\.py?$")

@mypyc_attr(patchable=True)
def parse_pyproject_toml(path_config: str) -> dict[str, Any]:
    """Parse a pyproject toml file, pulling out relevant parts for Black.

    If parsing fails, will raise a tomllib.TOMLDecodeError.
    """
    pyproject_toml = _load_toml(path_config)
    config: dict[str, Any] = pyproject_toml.get("tool", {}).get("black", {})
    config = {k.replace("--", "").replace("-", "_"): v for k, v in config.items()}

    if "target_version" not in config:
        inferred_target_version = infer_target_version(pyproject_toml)
        if inferred_target_version is not None:
            config["target_version"] = [v.name.lower() for v in inferred_target_version]

    return config


    @patch(
        "black.files.find_user_pyproject_toml",
    )
    def test_find_pyproject_toml(self, find_user_pyproject_toml: MagicMock) -> None:
        find_user_pyproject_toml.side_effect = RuntimeError()

        with redirect_stderr(io.StringIO()) as stderr:
            result = black.files.find_pyproject_toml(
                path_search_start=(str(Path.cwd().root),)
            )

        assert result is None
        err = stderr.getvalue()
        assert "Ignoring user configuration" in err

    @patch(
        "black.files.find_user_pyproject_toml",
    )
    def test_find_pyproject_toml(self, find_user_pyproject_toml: MagicMock) -> None:
        find_user_pyproject_toml.side_effect = RuntimeError()

        with redirect_stderr(io.StringIO()) as stderr:
            result = black.files.find_pyproject_toml(
                path_search_start=(str(Path.cwd().root),)
            )

        <AssertPlaceHolder>
        err = stderr.getvalue()
        assert "Ignoring user configuration" in err

def find_pyproject_toml(
    path_search_start: tuple[str, ...], stdin_filename: Optional[str] = None
) -> Optional[str]:
    """Find the absolute filepath to a pyproject.toml if it exists"""
    path_project_root, _ = find_project_root(path_search_start, stdin_filename)
    path_pyproject_toml = path_project_root / "pyproject.toml"
    if path_pyproject_toml.is_file():
        return str(path_pyproject_toml)

    try:
        path_user_pyproject_toml = find_user_pyproject_toml()
        return (
            str(path_user_pyproject_toml)
            if path_user_pyproject_toml.is_file()
            else None
        )
    except (PermissionError, RuntimeError) as e:
        # We do not have access to the user-level config directory, so ignore it.
        err(f"Ignoring user configuration directory due to {e!r}")
        return None


    def test_bpo_33660_workaround(self) -> None:
        if system() == "Windows":
            return

        # https://bugs.python.org/issue33660
        # Can be removed when we drop support for Python 3.8.5
        root = Path("/")
        with change_directory(root):
            path = Path("workspace") / "project"
            report = black.Report(verbose=True)
            resolves_outside = black.resolves_outside_root_or_cannot_stat(
                path, root, report
            )
            self.assertIs(resolves_outside, False)

    def test_bpo_33660_workaround(self) -> None:
        if system() == "Windows":
            return

        # https://bugs.python.org/issue33660
        # Can be removed when we drop support for Python 3.8.5
        root = Path("/")
        with change_directory(root):
            path = Path("workspace") / "project"
            report = black.Report(verbose=True)
            resolves_outside = black.resolves_outside_root_or_cannot_stat(
                path, root, report
            )
            <AssertPlaceHolder>

def resolves_outside_root_or_cannot_stat(
    path: Path,
    root: Path,
    report: Optional[Report] = None,
) -> bool:
    """
    Returns whether the path is a symbolic link that points outside the
    root directory. Also returns True if we failed to resolve the path.
    """
    try:
        resolved_path = _cached_resolve(path)
    except OSError as e:
        if report:
            report.path_ignored(path, f"cannot be read because {e}")
        return True
    try:
        resolved_path.relative_to(root)
    except ValueError:
        if report:
            report.path_ignored(path, f"is a symbolic link that points outside {root}")
        return True
    return False


    def test_lines_with_leading_tabs_expanded(self) -> None:
        # See CVE-2024-21503. Mostly test that this completes in a reasonable
        # time.
        payload = "\t" * 10_000
        assert lines_with_leading_tabs_expanded(payload) == [payload]

        tab = " " * 8
        assert lines_with_leading_tabs_expanded("\tx") == [f"{tab}x"]
        assert lines_with_leading_tabs_expanded("\t\tx") == [f"{tab}{tab}x"]
        assert lines_with_leading_tabs_expanded("\tx\n  y") == [f"{tab}x", "  y"]

    def test_lines_with_leading_tabs_expanded(self) -> None:
        # See CVE-2024-21503. Mostly test that this completes in a reasonable
        # time.
        payload = "\t" * 10_000
        assert lines_with_leading_tabs_expanded(payload) == [payload]

        tab = " " * 8
        assert lines_with_leading_tabs_expanded("\tx") == [f"{tab}x"]
        assert lines_with_leading_tabs_expanded("\t\tx") == [f"{tab}{tab}x"]
        <AssertPlaceHolder>

def lines_with_leading_tabs_expanded(s: str) -> list[str]:
    """
    Splits string into lines and expands only leading tabs (following the normal
    Python rules)
    """
    lines = []
    for line in s.splitlines():
        stripped_line = line.lstrip()
        if not stripped_line or stripped_line == line:
            lines.append(line)
        else:
            prefix_length = len(line) - len(stripped_line)
            prefix = line[:prefix_length].expandtabs()
            lines.append(prefix + stripped_line)
    if s.endswith("\n"):
        lines.append("")
    return lines


    def test_preview_newline_type_detection(self) -> None:
        mode = Mode(enabled_features={Preview.normalize_cr_newlines})
        newline_types = ["A\n", "A\r\n", "A\r"]
        for test_case in itertools.permutations(newline_types):
            assert black.format_str("".join(test_case), mode=mode) == test_case[0] * 3

    def test_preview_newline_type_detection(self) -> None:
        mode = Mode(enabled_features={Preview.normalize_cr_newlines})
        newline_types = ["A\n", "A\r\n", "A\r"]
        for test_case in itertools.permutations(newline_types):
            <AssertPlaceHolder>

def format_str(
    src_contents: str, *, mode: Mode, lines: Collection[tuple[int, int]] = ()
) -> str:
    """Reformat a string and return new contents.

    `mode` determines formatting options, such as how many characters per line are
    allowed.  Example:

    >>> import black
    >>> print(black.format_str("def f(arg:str='')->None:...", mode=black.Mode()))
    def f(arg: str = "") -> None:
        ...

    A more complex example:

    >>> print(
    ...   black.format_str(
    ...     "def f(arg:str='')->None: hey",
    ...     mode=black.Mode(
    ...       target_versions={black.TargetVersion.PY36},
    ...       line_length=10,
    ...       string_normalization=False,
    ...       is_pyi=False,
    ...     ),
    ...   ),
    ... )
    def f(
        arg: str = '',
    ) -> None:
        hey

    """
    if lines:
        lines = sanitized_lines(lines, src_contents)
        if not lines:
            return src_contents  # Nothing to format
    dst_contents = _format_str_once(src_contents, mode=mode, lines=lines)
    # Forced second pass to work around optional trailing commas (becoming
    # forced trailing commas on pass 2) interacting differently with optional
    # parentheses.  Admittedly ugly.
    if src_contents != dst_contents:
        if lines:
            lines = adjusted_lines(lines, src_contents, dst_contents)
        return _format_str_once(dst_contents, mode=mode, lines=lines)
    return dst_contents


    def test_get_cache_dir(
        self,
        tmp_path: Path,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        # Create multiple cache directories
        workspace1 = tmp_path / "ws1"
        workspace1.mkdir()
        workspace2 = tmp_path / "ws2"
        workspace2.mkdir()

        # Force user_cache_dir to use the temporary directory for easier assertions
        patch_user_cache_dir = patch(
            target="black.cache.user_cache_dir",
            autospec=True,
            return_value=str(workspace1),
        )

        # If BLACK_CACHE_DIR is not set, use user_cache_dir
        monkeypatch.delenv("BLACK_CACHE_DIR", raising=False)
        with patch_user_cache_dir:
            assert get_cache_dir().parent == workspace1

        # If it is set, use the path provided in the env var.
        monkeypatch.setenv("BLACK_CACHE_DIR", str(workspace2))
        assert get_cache_dir().parent == workspace2

    def test_get_cache_dir(
        self,
        tmp_path: Path,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        # Create multiple cache directories
        workspace1 = tmp_path / "ws1"
        workspace1.mkdir()
        workspace2 = tmp_path / "ws2"
        workspace2.mkdir()

        # Force user_cache_dir to use the temporary directory for easier assertions
        patch_user_cache_dir = patch(
            target="black.cache.user_cache_dir",
            autospec=True,
            return_value=str(workspace1),
        )

        # If BLACK_CACHE_DIR is not set, use user_cache_dir
        monkeypatch.delenv("BLACK_CACHE_DIR", raising=False)
        with patch_user_cache_dir:
            assert get_cache_dir().parent == workspace1

        # If it is set, use the path provided in the env var.
        monkeypatch.setenv("BLACK_CACHE_DIR", str(workspace2))
        <AssertPlaceHolder>

def get_cache_dir() -> Path:
    """Get the cache directory used by black.

    Users can customize this directory on all systems using `BLACK_CACHE_DIR`
    environment variable. By default, the cache directory is the user cache directory
    under the black application.

    This result is immediately set to a constant `black.cache.CACHE_DIR` as to avoid
    repeated calls.
    """
    # NOTE: Function mostly exists as a clean way to test getting the cache directory.
    default_cache_dir = user_cache_dir("black")
    cache_dir = Path(os.environ.get("BLACK_CACHE_DIR", default_cache_dir))
    cache_dir = cache_dir / __version__
    return cache_dir


    def test_cache_file_length(self) -> None:
        cases = [
            DEFAULT_MODE,
            # all of the target versions
            Mode(target_versions=set(TargetVersion)),
            # all of the features
            Mode(enabled_features=set(Preview)),
            # all of the magics
            Mode(python_cell_magics={f"magic{i}" for i in range(500)}),
            # all of the things
            Mode(
                target_versions=set(TargetVersion),
                enabled_features=set(Preview),
                python_cell_magics={f"magic{i}" for i in range(500)},
            ),
        ]
        for case in cases:
            cache_file = get_cache_file(case)
            # Some common file systems enforce a maximum path length
            # of 143 (issue #4174). We can't do anything if the directory
            # path is too long, but ensure the name of the cache file itself
            # doesn't get too crazy.
            assert len(cache_file.name) <= 96

    def test_cache_file_length(self) -> None:
        cases = [
            DEFAULT_MODE,
            # all of the target versions
            Mode(target_versions=set(TargetVersion)),
            # all of the features
            Mode(enabled_features=set(Preview)),
            # all of the magics
            Mode(python_cell_magics={f"magic{i}" for i in range(500)}),
            # all of the things
            Mode(
                target_versions=set(TargetVersion),
                enabled_features=set(Preview),
                python_cell_magics={f"magic{i}" for i in range(500)},
            ),
        ]
        for case in cases:
            cache_file = get_cache_file(case)
            # Some common file systems enforce a maximum path length
            # of 143 (issue #4174). We can't do anything if the directory
            # path is too long, but ensure the name of the cache file itself
            # doesn't get too crazy.
            <AssertPlaceHolder>

def get_cache_file(mode: Mode) -> Path:
    return CACHE_DIR / f"cache.{mode.get_cache_key()}.pickle"


    def test_cache_broken_file(self) -> None:
        mode = DEFAULT_MODE
        with cache_dir() as workspace:
            cache_file = get_cache_file(mode)
            cache_file.write_text("this is not a pickle", encoding="utf-8")
            assert black.Cache.read(mode).file_data == {}
            src = (workspace / "test.py").resolve()
            src.write_text("print('hello')", encoding="utf-8")
            invokeBlack([str(src)])
            cache = black.Cache.read(mode)
            assert not cache.is_changed(src)

    def test_cache_broken_file(self) -> None:
        mode = DEFAULT_MODE
        with cache_dir() as workspace:
            cache_file = get_cache_file(mode)
            cache_file.write_text("this is not a pickle", encoding="utf-8")
            assert black.Cache.read(mode).file_data == {}
            src = (workspace / "test.py").resolve()
            src.write_text("print('hello')", encoding="utf-8")
            invokeBlack([str(src)])
            cache = black.Cache.read(mode)
            <AssertPlaceHolder>


    def test_read_cache_no_cachefile(self) -> None:
        mode = DEFAULT_MODE
        with cache_dir():
            assert black.Cache.read(mode).file_data == {}

    def test_read_cache_no_cachefile(self) -> None:
        mode = DEFAULT_MODE
        with cache_dir():
            <AssertPlaceHolder>


    def test_write_cache_read_cache(self) -> None:
        mode = DEFAULT_MODE
        with cache_dir() as workspace:
            src = (workspace / "test.py").resolve()
            src.touch()
            write_cache = black.Cache.read(mode)
            write_cache.write([src])
            read_cache = black.Cache.read(mode)
            assert not read_cache.is_changed(src)

    def test_write_cache_read_cache(self) -> None:
        mode = DEFAULT_MODE
        with cache_dir() as workspace:
            src = (workspace / "test.py").resolve()
            src.touch()
            write_cache = black.Cache.read(mode)
            write_cache.write([src])
            read_cache = black.Cache.read(mode)
            <AssertPlaceHolder>


    @pytest.mark.incompatible_with_mypyc
    def test_filter_cached(self) -> None:
        with TemporaryDirectory() as workspace:
            path = Path(workspace)
            uncached = (path / "uncached").resolve()
            cached = (path / "cached").resolve()
            cached_but_changed = (path / "changed").resolve()
            uncached.touch()
            cached.touch()
            cached_but_changed.touch()
            cache = black.Cache.read(DEFAULT_MODE)

            orig_func = black.Cache.get_file_data

            def wrapped_func(path: Path) -> FileData:
                if path == cached:
                    return orig_func(path)
                if path == cached_but_changed:
                    return FileData(0.0, 0, "")
                raise AssertionError

            with patch.object(black.Cache, "get_file_data", side_effect=wrapped_func):
                cache.write([cached, cached_but_changed])
            todo, done = cache.filtered_cached({uncached, cached, cached_but_changed})
            assert todo == {uncached, cached_but_changed}
            assert done == {cached}

    @pytest.mark.incompatible_with_mypyc
    def test_filter_cached(self) -> None:
        with TemporaryDirectory() as workspace:
            path = Path(workspace)
            uncached = (path / "uncached").resolve()
            cached = (path / "cached").resolve()
            cached_but_changed = (path / "changed").resolve()
            uncached.touch()
            cached.touch()
            cached_but_changed.touch()
            cache = black.Cache.read(DEFAULT_MODE)

            orig_func = black.Cache.get_file_data

            def wrapped_func(path: Path) -> FileData:
                if path == cached:
                    return orig_func(path)
                if path == cached_but_changed:
                    return FileData(0.0, 0, "")
                raise AssertionError

            with patch.object(black.Cache, "get_file_data", side_effect=wrapped_func):
                cache.write([cached, cached_but_changed])
            todo, done = cache.filtered_cached({uncached, cached, cached_but_changed})
            <AssertPlaceHolder>
            assert done == {cached}

    def filtered_cached(self, sources: Iterable[Path]) -> tuple[set[Path], set[Path]]:
        """Split an iterable of paths in `sources` into two sets.

        The first contains paths of files that modified on disk or are not in the
        cache. The other contains paths to non-modified files.
        """
        changed: set[Path] = set()
        done: set[Path] = set()
        for src in sources:
            if self.is_changed(src):
                changed.add(src)
            else:
                done.add(src)
        return changed, done


    def test_filter_cached_hash(self) -> None:
        with TemporaryDirectory() as workspace:
            path = Path(workspace)
            src = (path / "test.py").resolve()
            src.write_text("print('hello')", encoding="utf-8")
            st = src.stat()
            cache = black.Cache.read(DEFAULT_MODE)
            cache.write([src])
            cached_file_data = cache.file_data[str(src)]

            todo, done = cache.filtered_cached([src])
            assert todo == set()
            assert done == {src}
            assert cached_file_data.st_mtime == st.st_mtime

            # Modify st_mtime
            cached_file_data = cache.file_data[str(src)] = FileData(
                cached_file_data.st_mtime - 1,
                cached_file_data.st_size,
                cached_file_data.hash,
            )
            todo, done = cache.filtered_cached([src])
            assert todo == set()
            assert done == {src}
            assert cached_file_data.st_mtime < st.st_mtime
            assert cached_file_data.st_size == st.st_size
            assert cached_file_data.hash == black.Cache.hash_digest(src)

            # Modify contents
            src.write_text("print('hello world')", encoding="utf-8")
            new_st = src.stat()
            todo, done = cache.filtered_cached([src])
            assert todo == {src}
            assert done == set()
            assert cached_file_data.st_mtime < new_st.st_mtime
            assert cached_file_data.st_size != new_st.st_size
            assert cached_file_data.hash != black.Cache.hash_digest(src)

    def test_filter_cached_hash(self) -> None:
        with TemporaryDirectory() as workspace:
            path = Path(workspace)
            src = (path / "test.py").resolve()
            src.write_text("print('hello')", encoding="utf-8")
            st = src.stat()
            cache = black.Cache.read(DEFAULT_MODE)
            cache.write([src])
            cached_file_data = cache.file_data[str(src)]

            todo, done = cache.filtered_cached([src])
            assert todo == set()
            assert done == {src}
            <AssertPlaceHolder>

            # Modify st_mtime
            cached_file_data = cache.file_data[str(src)] = FileData(
                cached_file_data.st_mtime - 1,
                cached_file_data.st_size,
                cached_file_data.hash,
            )
            todo, done = cache.filtered_cached([src])
            assert todo == set()
            assert done == {src}
            assert cached_file_data.st_mtime < st.st_mtime
            assert cached_file_data.st_size == st.st_size
            assert cached_file_data.hash == black.Cache.hash_digest(src)

            # Modify contents
            src.write_text("print('hello world')", encoding="utf-8")
            new_st = src.stat()
            todo, done = cache.filtered_cached([src])
            assert todo == {src}
            assert done == set()
            assert cached_file_data.st_mtime < new_st.st_mtime
            assert cached_file_data.st_size != new_st.st_size
            assert cached_file_data.hash != black.Cache.hash_digest(src)


    def test_write_cache_creates_directory_if_needed(self) -> None:
        mode = DEFAULT_MODE
        with cache_dir(exists=False) as workspace:
            assert not workspace.exists()
            cache = black.Cache.read(mode)
            cache.write([])
            assert workspace.exists()

    def test_write_cache_creates_directory_if_needed(self) -> None:
        mode = DEFAULT_MODE
        with cache_dir(exists=False) as workspace:
            assert not workspace.exists()
            cache = black.Cache.read(mode)
            cache.write([])
            <AssertPlaceHolder>


    @event_loop()
    def test_failed_formatting_does_not_get_cached(self) -> None:
        mode = DEFAULT_MODE
        with (
            cache_dir() as workspace,
            patch("concurrent.futures.ProcessPoolExecutor", new=ThreadPoolExecutor),
        ):
            failing = (workspace / "failing.py").resolve()
            failing.write_text("not actually python", encoding="utf-8")
            clean = (workspace / "clean.py").resolve()
            clean.write_text('print("hello")\n', encoding="utf-8")
            invokeBlack([str(workspace)], exit_code=123)
            cache = black.Cache.read(mode)
            assert cache.is_changed(failing)
            assert not cache.is_changed(clean)

    @event_loop()
    def test_failed_formatting_does_not_get_cached(self) -> None:
        mode = DEFAULT_MODE
        with (
            cache_dir() as workspace,
            patch("concurrent.futures.ProcessPoolExecutor", new=ThreadPoolExecutor),
        ):
            failing = (workspace / "failing.py").resolve()
            failing.write_text("not actually python", encoding="utf-8")
            clean = (workspace / "clean.py").resolve()
            clean.write_text('print("hello")\n', encoding="utf-8")
            invokeBlack([str(workspace)], exit_code=123)
            cache = black.Cache.read(mode)
            assert cache.is_changed(failing)
            <AssertPlaceHolder>


    def test_read_cache_line_lengths(self) -> None:
        mode = DEFAULT_MODE
        short_mode = replace(DEFAULT_MODE, line_length=1)
        with cache_dir() as workspace:
            path = (workspace / "file.py").resolve()
            path.touch()
            cache = black.Cache.read(mode)
            cache.write([path])
            one = black.Cache.read(mode)
            assert not one.is_changed(path)
            two = black.Cache.read(short_mode)
            assert two.is_changed(path)

    def test_read_cache_line_lengths(self) -> None:
        mode = DEFAULT_MODE
        short_mode = replace(DEFAULT_MODE, line_length=1)
        with cache_dir() as workspace:
            path = (workspace / "file.py").resolve()
            path.touch()
            cache = black.Cache.read(mode)
            cache.write([path])
            one = black.Cache.read(mode)
            <AssertPlaceHolder>
            two = black.Cache.read(short_mode)
            assert two.is_changed(path)


    def test_cache_key(self) -> None:
        # Test that all members of the mode enum affect the cache key.
        for field in fields(Mode):
            values: list[Any]
            if field.name == "target_versions":
                values = [
                    {TargetVersion.PY312},
                    {TargetVersion.PY313},
                ]
            elif field.name == "python_cell_magics":
                values = [{"magic1"}, {"magic2"}]
            elif field.name == "enabled_features":
                # If you are looking to remove one of these features, just
                # replace it with any other feature.
                values = [
                    {Preview.multiline_string_handling},
                    {Preview.string_processing},
                ]
            elif field.type is bool:
                values = [True, False]
            elif field.type is int:
                values = [1, 2]
            else:
                raise AssertionError(
                    f"Unhandled field type: {field.type} for field {field.name}"
                )
            modes = [replace(DEFAULT_MODE, **{field.name: value}) for value in values]
            keys = [mode.get_cache_key() for mode in modes]
            assert len(set(keys)) == len(modes)

    def test_cache_key(self) -> None:
        # Test that all members of the mode enum affect the cache key.
        for field in fields(Mode):
            values: list[Any]
            if field.name == "target_versions":
                values = [
                    {TargetVersion.PY312},
                    {TargetVersion.PY313},
                ]
            elif field.name == "python_cell_magics":
                values = [{"magic1"}, {"magic2"}]
            elif field.name == "enabled_features":
                # If you are looking to remove one of these features, just
                # replace it with any other feature.
                values = [
                    {Preview.multiline_string_handling},
                    {Preview.string_processing},
                ]
            elif field.type is bool:
                values = [True, False]
            elif field.type is int:
                values = [1, 2]
            else:
                raise AssertionError(
                    f"Unhandled field type: {field.type} for field {field.name}"
                )
            modes = [replace(DEFAULT_MODE, **{field.name: value}) for value in values]
            keys = [mode.get_cache_key() for mode in modes]
            <AssertPlaceHolder>

    def get_cache_key(self) -> str:
        if self.target_versions:
            version_str = ",".join(
                str(version.value)
                for version in sorted(self.target_versions, key=attrgetter("value"))
            )
        else:
            version_str = "-"
        if len(version_str) > _MAX_CACHE_KEY_PART_LENGTH:
            version_str = sha256(version_str.encode()).hexdigest()[
                :_MAX_CACHE_KEY_PART_LENGTH
            ]
        features_and_magics = (
            ",".join(sorted(f.name for f in self.enabled_features))
            + "@"
            + ",".join(sorted(self.python_cell_magics))
        )
        if len(features_and_magics) > _MAX_CACHE_KEY_PART_LENGTH:
            features_and_magics = sha256(features_and_magics.encode()).hexdigest()[
                :_MAX_CACHE_KEY_PART_LENGTH
            ]
        parts = [
            version_str,
            str(self.line_length),
            str(int(self.string_normalization)),
            str(int(self.is_pyi)),
            str(int(self.is_ipynb)),
            str(int(self.skip_source_first_line)),
            str(int(self.magic_trailing_comma)),
            str(int(self.preview)),
            str(int(self.unstable)),
            features_and_magics,
        ]
        return ".".join(parts)


assert len(spans) == len(expected_slices)

def iter_fexpr_spans(s: str) -> Iterator[tuple[int, int]]:
    """
    Yields spans corresponding to expressions in a given f-string.
    Spans are half-open ranges (left inclusive, right exclusive).
    Assumes the input string is a valid f-string, but will not crash if the input
    string is invalid.
    """
    stack: list[int] = []  # our curly paren stack
    i = 0
    while i < len(s):
        if s[i] == "{":
            # if we're in a string part of the f-string, ignore escaped curly braces
            if not stack and i + 1 < len(s) and s[i + 1] == "{":
                i += 2
                continue
            stack.append(i)
            i += 1
            continue

        if s[i] == "}":
            if not stack:
                i += 1
                continue
            j = stack.pop()
            # we've made it back out of the expression! yield the span
            if not stack:
                yield (j, i + 1)
            i += 1
            continue

        # if we're in an expression part of the f-string, fast-forward through strings
        # note that backslashes are not legal in the expression portion of f-strings
        if stack:
            delim = None
            if s[i : i + 3] in ("'''", '"""'):
                delim = s[i : i + 3]
            elif s[i] in ("'", '"'):
                delim = s[i]
            if delim:
                i += len(delim)
                while i < len(s) and s[i : i + len(delim)] != delim:
                    i += 1
                i += len(delim)
                continue
        i += 1


python -m venv .venv
source .venv/bin/activate
pip install -e ".[test]"
pip install ipdb

    def test_buffer_protocol(self, backend):
        prk = binascii.unhexlify(
            b"52169af5c485dcc2321eb8d26d5efa21fb9b93c98e38412ee2484cf14f0d0d23"
        )

        okm = binascii.unhexlify(b"1c3bc9e7c4547c5191c0d478cccaed55")

        oinfo = binascii.unhexlify(
            b"a1b2c3d4e53728157e634612c12d6d5223e204aeea4341565369647bd184bcd2"
            b"46f72971f292badaa2fe4124612cba"
        )

        ckdf = ConcatKDFHash(hashes.SHA256(), 16, oinfo, backend)

        assert ckdf.derive(bytearray(prk)) == okm

    def test_buffer_protocol(self, backend):
        prk = binascii.unhexlify(
            b"52169af5c485dcc2321eb8d26d5efa21fb9b93c98e38412ee2484cf14f0d0d23"
        )

        okm = binascii.unhexlify(b"1c3bc9e7c4547c5191c0d478cccaed55")

        oinfo = binascii.unhexlify(
            b"a1b2c3d4e53728157e634612c12d6d5223e204aeea4341565369647bd184bcd2"
            b"46f72971f292badaa2fe4124612cba"
        )

        ckdf = ConcatKDFHash(hashes.SHA256(), 16, oinfo, backend)

        <AssertPlaceHolder>

    def derive(self, key_material: utils.Buffer) -> bytes:
        if self._used:
            raise AlreadyFinalized
        self._used = True
        return _concatkdf_derive(
            key_material, self._length, self._hash, self._otherinfo
        )


    def test_eq(self):
        nr = x509.NoticeReference("org", [1, 2])
        nr2 = x509.NoticeReference("org", [1, 2])
        un = x509.UserNotice(nr, "text")
        un2 = x509.UserNotice(nr2, "text")
        assert un == un2

    def test_eq(self):
        nr = x509.NoticeReference("org", [1, 2])
        nr2 = x509.NoticeReference("org", [1, 2])
        un = x509.UserNotice(nr, "text")
        un2 = x509.UserNotice(nr2, "text")
        <AssertPlaceHolder>

class UserNotice:
    def __init__(
        self,
        notice_reference: NoticeReference | None,
        explicit_text: str | None,
    ) -> None:
        if notice_reference and not isinstance(
            notice_reference, NoticeReference
        ):
            raise TypeError(
                "notice_reference must be None or a NoticeReference"
            )

        self._notice_reference = notice_reference
        self._explicit_text = explicit_text

    def __repr__(self) -> str:
        return (
            f"<UserNotice(notice_reference={self.notice_reference}, "
            f"explicit_text={self.explicit_text!r})>"
        )

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, UserNotice):
            return NotImplemented

        return (
            self.notice_reference == other.notice_reference
            and self.explicit_text == other.explicit_text
        )

    def __hash__(self) -> int:
        return hash((self.notice_reference, self.explicit_text))

    @property
    def notice_reference(self) -> NoticeReference | None:
        return self._notice_reference

    @property
    def explicit_text(self) -> str | None:
        return self._explicit_text


    def test_add_multiple_extensions(self, backend):
        serial_number = 333
        revocation_date = datetime.datetime(2002, 1, 1, 12, 1)
        invalidity_date = x509.InvalidityDate(
            datetime.datetime(2015, 1, 1, 0, 0)
        )
        certificate_issuer = x509.CertificateIssuer(
            [x509.DNSName("cryptography.io")]
        )
        crl_reason = x509.CRLReason(x509.ReasonFlags.aa_compromise)
        builder = (
            x509.RevokedCertificateBuilder()
            .serial_number(serial_number)
            .revocation_date(revocation_date)
            .add_extension(invalidity_date, True)
            .add_extension(crl_reason, True)
            .add_extension(certificate_issuer, True)
        )

        revoked_certificate = builder.build(backend)
        assert len(revoked_certificate.extensions) == 3
        for ext_data in [invalidity_date, certificate_issuer, crl_reason]:
            ext = revoked_certificate.extensions.get_extension_for_class(
                type(ext_data)
            )
            assert ext.critical is True
            assert ext.value == ext_data

    def test_add_multiple_extensions(self, backend):
        serial_number = 333
        revocation_date = datetime.datetime(2002, 1, 1, 12, 1)
        invalidity_date = x509.InvalidityDate(
            datetime.datetime(2015, 1, 1, 0, 0)
        )
        certificate_issuer = x509.CertificateIssuer(
            [x509.DNSName("cryptography.io")]
        )
        crl_reason = x509.CRLReason(x509.ReasonFlags.aa_compromise)
        builder = (
            x509.RevokedCertificateBuilder()
            .serial_number(serial_number)
            .revocation_date(revocation_date)
            .add_extension(invalidity_date, True)
            .add_extension(crl_reason, True)
            .add_extension(certificate_issuer, True)
        )

        revoked_certificate = builder.build(backend)
        assert len(revoked_certificate.extensions) == 3
        for ext_data in [invalidity_date, certificate_issuer, crl_reason]:
            ext = revoked_certificate.extensions.get_extension_for_class(
                type(ext_data)
            )
            <AssertPlaceHolder>
            assert ext.value == ext_data

    def get_extension_for_class(
        self, extclass: type[ExtensionTypeVar]
    ) -> Extension[ExtensionTypeVar]:
        if extclass is UnrecognizedExtension:
            raise TypeError(
                "UnrecognizedExtension can't be used with "
                "get_extension_for_class because more than one instance of the"
                " class may be present."
            )

        for ext in self:
            if isinstance(ext.value, extclass):
                return ext

        raise ExtensionNotFound(
            f"No {extclass} extension was found", extclass.oid
        )


    def test_ipaddress(self, backend):
        cert = _load_cert(
            os.path.join("x509", "custom", "san_ipaddr.pem"),
            x509.load_pem_x509_certificate,
        )
        ext = cert.extensions.get_extension_for_class(
            x509.SubjectAlternativeName
        )
        assert ext is not None
        assert ext.critical is False

        san = ext.value

        ip = san.get_values_for_type(x509.IPAddress)
        assert [
            ipaddress.ip_address("127.0.0.1"),
            ipaddress.ip_address("ff::"),
        ] == ip

    def test_ipaddress(self, backend):
        cert = _load_cert(
            os.path.join("x509", "custom", "san_ipaddr.pem"),
            x509.load_pem_x509_certificate,
        )
        ext = cert.extensions.get_extension_for_class(
            x509.SubjectAlternativeName
        )
        assert ext is not None
        <AssertPlaceHolder>

        san = ext.value

        ip = san.get_values_for_type(x509.IPAddress)
        assert [
            ipaddress.ip_address("127.0.0.1"),
            ipaddress.ip_address("ff::"),
        ] == ip


    def test_hash(self):
        gn = x509.OtherName(x509.ObjectIdentifier("1.2.3.4"), b"derdata")
        gn2 = x509.OtherName(x509.ObjectIdentifier("1.2.3.4"), b"derdata")
        gn3 = x509.OtherName(x509.ObjectIdentifier("1.2.3.5"), b"derdata")
        assert hash(gn) == hash(gn2)
        assert hash(gn) != hash(gn3)

    def test_hash(self):
        gn = x509.OtherName(x509.ObjectIdentifier("1.2.3.4"), b"derdata")
        gn2 = x509.OtherName(x509.ObjectIdentifier("1.2.3.4"), b"derdata")
        gn3 = x509.OtherName(x509.ObjectIdentifier("1.2.3.5"), b"derdata")
        <AssertPlaceHolder>
        assert hash(gn) != hash(gn3)

class OtherName(GeneralName):
    def __init__(self, type_id: ObjectIdentifier, value: bytes) -> None:
        if not isinstance(type_id, ObjectIdentifier):
            raise TypeError("type_id must be an ObjectIdentifier")
        if not isinstance(value, bytes):
            raise TypeError("value must be a binary string")

        self._type_id = type_id
        self._value = value

    @property
    def type_id(self) -> ObjectIdentifier:
        return self._type_id

    @property
    def value(self) -> bytes:
        return self._value

    def __repr__(self) -> str:
        return f"<OtherName(type_id={self.type_id}, value={self.value!r})>"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, OtherName):
            return NotImplemented

        return self.type_id == other.type_id and self.value == other.value

    def __hash__(self) -> int:
        return hash((self.type_id, self.value))


    def test_hash(self):
        g1 = x509.UniformResourceIdentifier("http://host.com")
        g2 = x509.UniformResourceIdentifier("http://host.com")
        g3 = x509.UniformResourceIdentifier("http://other.com")

        assert hash(g1) == hash(g2)
        assert hash(g1) != hash(g3)

    def test_hash(self):
        g1 = x509.UniformResourceIdentifier("http://host.com")
        g2 = x509.UniformResourceIdentifier("http://host.com")
        g3 = x509.UniformResourceIdentifier("http://other.com")

        <AssertPlaceHolder>
        assert hash(g1) != hash(g3)

class UniformResourceIdentifier(GeneralName):
    def __init__(self, value: str) -> None:
        if isinstance(value, str):
            try:
                value.encode("ascii")
            except UnicodeEncodeError:
                raise ValueError(
                    "URI values should be passed as an A-label string. "
                    "This means unicode characters should be encoded via "
                    "a library like idna."
                )
        else:
            raise TypeError("value must be string")

        self._value = value

    @property
    def value(self) -> str:
        return self._value

    @classmethod
    def _init_without_validation(cls, value: str) -> UniformResourceIdentifier:
        instance = cls.__new__(cls)
        instance._value = value
        return instance

    def __repr__(self) -> str:
        return f"<UniformResourceIdentifier(value={self.value!r})>"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, UniformResourceIdentifier):
            return NotImplemented

        return self.value == other.value

    def __hash__(self) -> int:
        return hash(self.value)


    def test_eq(self):
        ski = x509.SubjectKeyIdentifier(
            binascii.unhexlify(b"092384932230498bc980aa8098456f6ff7ff3ac9")
        )
        ski2 = x509.SubjectKeyIdentifier(
            binascii.unhexlify(b"092384932230498bc980aa8098456f6ff7ff3ac9")
        )
        assert ski == ski2

    def test_eq(self):
        ski = x509.SubjectKeyIdentifier(
            binascii.unhexlify(b"092384932230498bc980aa8098456f6ff7ff3ac9")
        )
        ski2 = x509.SubjectKeyIdentifier(
            binascii.unhexlify(b"092384932230498bc980aa8098456f6ff7ff3ac9")
        )
        <AssertPlaceHolder>

class SubjectKeyIdentifier(ExtensionType):
    oid = ExtensionOID.SUBJECT_KEY_IDENTIFIER

    def __init__(self, digest: bytes) -> None:
        self._digest = digest

    @classmethod
    def from_public_key(
        cls, public_key: CertificatePublicKeyTypes
    ) -> SubjectKeyIdentifier:
        return cls(_key_identifier_from_public_key(public_key))

    @property
    def digest(self) -> bytes:
        return self._digest

    @property
    def key_identifier(self) -> bytes:
        return self._digest

    def __repr__(self) -> str:
        return f"<SubjectKeyIdentifier(digest={self.digest!r})>"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, SubjectKeyIdentifier):
            return NotImplemented

        return constant_time.bytes_eq(self.digest, other.digest)

    def __hash__(self) -> int:
        return hash(self.digest)

    def public_bytes(self) -> bytes:
        return rust_x509.encode_extension_value(self)


    def test_iter_input(self):
        numbers = [1, 3, 4]
        nr = x509.NoticeReference("org", iter(numbers))
        assert list(nr.notice_numbers) == numbers

    def test_iter_input(self):
        numbers = [1, 3, 4]
        nr = x509.NoticeReference("org", iter(numbers))
        <AssertPlaceHolder>

class NoticeReference:
    def __init__(
        self,
        organization: str | None,
        notice_numbers: Iterable[int],
    ) -> None:
        self._organization = organization
        notice_numbers = list(notice_numbers)
        if not all(isinstance(x, int) for x in notice_numbers):
            raise TypeError("notice_numbers must be a list of integers")

        self._notice_numbers = notice_numbers

    def __repr__(self) -> str:
        return (
            f"<NoticeReference(organization={self.organization!r}, "
            f"notice_numbers={self.notice_numbers})>"
        )

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, NoticeReference):
            return NotImplemented

        return (
            self.organization == other.organization
            and self.notice_numbers == other.notice_numbers
        )

    def __hash__(self) -> int:
        return hash((self.organization, tuple(self.notice_numbers)))

    @property
    def organization(self) -> str | None:
        return self._organization

    @property
    def notice_numbers(self) -> list[int]:
        return self._notice_numbers


@pytest.mark.supported(
    only_if=lambda backend: backend.x25519_supported(),
    skip_message="Requires OpenSSL with X25519 support",
)
def test_public_key_equality(backend):
    key_bytes = load_vectors_from_file(
        os.path.join("asymmetric", "X25519", "x25519-pkcs8.der"),
        lambda derfile: derfile.read(),
        mode="rb",
    )
    key1 = serialization.load_der_private_key(key_bytes, None).public_key()
    key2 = serialization.load_der_private_key(key_bytes, None).public_key()
    key3 = X25519PrivateKey.generate().public_key()
    assert key1 == key2
    assert key1 != key3
    assert key1 != object()
    with pytest.raises(TypeError):
        key1 < key2  # type: ignore[operator]

@pytest.mark.supported(
    only_if=lambda backend: backend.x25519_supported(),
    skip_message="Requires OpenSSL with X25519 support",
)
def test_public_key_equality(backend):
    key_bytes = load_vectors_from_file(
        os.path.join("asymmetric", "X25519", "x25519-pkcs8.der"),
        lambda derfile: derfile.read(),
        mode="rb",
    )
    key1 = serialization.load_der_private_key(key_bytes, None).public_key()
    key2 = serialization.load_der_private_key(key_bytes, None).public_key()
    key3 = X25519PrivateKey.generate().public_key()
    assert key1 == key2
    <AssertPlaceHolder>
    assert key1 != object()
    with pytest.raises(TypeError):
        key1 < key2  # type: ignore[operator]

    @abc.abstractmethod
    def public_key(self) -> X25519PublicKey:
        """
        Returns the public key associated with this private key
        """


    def test_ne(self):
        delta1 = x509.DeltaCRLIndicator(1)
        delta2 = x509.DeltaCRLIndicator(2)
        assert delta1 != delta2
        assert delta1 != object()

    def test_ne(self):
        delta1 = x509.DeltaCRLIndicator(1)
        delta2 = x509.DeltaCRLIndicator(2)
        <AssertPlaceHolder>
        assert delta1 != object()

class DeltaCRLIndicator(ExtensionType):
    oid = ExtensionOID.DELTA_CRL_INDICATOR

    def __init__(self, crl_number: int) -> None:
        if not isinstance(crl_number, int):
            raise TypeError("crl_number must be an integer")

        self._crl_number = crl_number

    @property
    def crl_number(self) -> int:
        return self._crl_number

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, DeltaCRLIndicator):
            return NotImplemented

        return self.crl_number == other.crl_number

    def __hash__(self) -> int:
        return hash(self.crl_number)

    def __repr__(self) -> str:
        return f"<DeltaCRLIndicator(crl_number={self.crl_number})>"

    def public_bytes(self) -> bytes:
        return rust_x509.encode_extension_value(self)


    def test_zany_py2_bytes_subclass(self):
        class mybytes(bytes):  # noqa: N801
            def __str__(self):
                return "broken"

        str(mybytes())
        padder = padding.PKCS7(128).padder()
        data = padder.update(mybytes(b"abc")) + padder.finalize()
        unpadder = padding.PKCS7(128).unpadder()
        unpadder.update(mybytes(data))
        assert unpadder.finalize() == b"abc"

    def test_zany_py2_bytes_subclass(self):
        class mybytes(bytes):  # noqa: N801
            def __str__(self):
                return "broken"

        str(mybytes())
        padder = padding.PKCS7(128).padder()
        data = padder.update(mybytes(b"abc")) + padder.finalize()
        unpadder = padding.PKCS7(128).unpadder()
        unpadder.update(mybytes(data))
        <AssertPlaceHolder>

    @abc.abstractmethod
    def finalize(self) -> bytes:
        """
        Finalize the padding, returns bytes.
        """


    def test_get_revoked_certificate_doesnt_reorder(
        self, rsa_key_2048: rsa.RSAPrivateKey, backend
    ):
        private_key = rsa_key_2048
        last_update = datetime.datetime(2002, 1, 1, 12, 1)
        next_update = datetime.datetime(2030, 1, 1, 12, 1)
        builder = (
            x509.CertificateRevocationListBuilder()
            .issuer_name(
                x509.Name(
                    [
                        x509.NameAttribute(
                            NameOID.COMMON_NAME, "cryptography.io CA"
                        )
                    ]
                )
            )
            .last_update(last_update)
            .next_update(next_update)
        )
        for i in [2, 500, 3, 49, 7, 1]:
            revoked_cert = (
                x509.RevokedCertificateBuilder()
                .serial_number(i)
                .revocation_date(datetime.datetime(2012, 1, 1, 1, 1))
                .build(backend)
            )
            builder = builder.add_revoked_certificate(revoked_cert)
        crl = builder.sign(private_key, hashes.SHA256(), backend)
        assert crl[0].serial_number == 2
        assert crl[2].serial_number == 3
        # make sure get_revoked_certificate_by_serial_number doesn't affect
        # ordering after being invoked
        crl.get_revoked_certificate_by_serial_number(500)
        assert crl[0].serial_number == 2
        assert crl[2].serial_number == 3

    def test_get_revoked_certificate_doesnt_reorder(
        self, rsa_key_2048: rsa.RSAPrivateKey, backend
    ):
        private_key = rsa_key_2048
        last_update = datetime.datetime(2002, 1, 1, 12, 1)
        next_update = datetime.datetime(2030, 1, 1, 12, 1)
        builder = (
            x509.CertificateRevocationListBuilder()
            .issuer_name(
                x509.Name(
                    [
                        x509.NameAttribute(
                            NameOID.COMMON_NAME, "cryptography.io CA"
                        )
                    ]
                )
            )
            .last_update(last_update)
            .next_update(next_update)
        )
        for i in [2, 500, 3, 49, 7, 1]:
            revoked_cert = (
                x509.RevokedCertificateBuilder()
                .serial_number(i)
                .revocation_date(datetime.datetime(2012, 1, 1, 1, 1))
                .build(backend)
            )
            builder = builder.add_revoked_certificate(revoked_cert)
        crl = builder.sign(private_key, hashes.SHA256(), backend)
        <AssertPlaceHolder>
        assert crl[2].serial_number == 3
        # make sure get_revoked_certificate_by_serial_number doesn't affect
        # ordering after being invoked
        crl.get_revoked_certificate_by_serial_number(500)
        <AssertPlaceHolder>
        assert crl[2].serial_number == 3

    def sign(
        self,
        private_key: CertificateIssuerPrivateKeyTypes,
        algorithm: _AllowedHashTypes | None,
        backend: typing.Any = None,
        *,
        rsa_padding: padding.PSS | padding.PKCS1v15 | None = None,
        ecdsa_deterministic: bool | None = None,
    ) -> CertificateRevocationList:
        if self._issuer_name is None:
            raise ValueError("A CRL must have an issuer name")

        if self._last_update is None:
            raise ValueError("A CRL must have a last update time")

        if self._next_update is None:
            raise ValueError("A CRL must have a next update time")

        if rsa_padding is not None:
            if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)):
                raise TypeError("Padding must be PSS or PKCS1v15")
            if not isinstance(private_key, rsa.RSAPrivateKey):
                raise TypeError("Padding is only supported for RSA keys")

        if ecdsa_deterministic is not None:
            if not isinstance(private_key, ec.EllipticCurvePrivateKey):
                raise TypeError(
                    "Deterministic ECDSA is only supported for EC keys"
                )

        return rust_x509.create_x509_crl(
            self,
            private_key,
            algorithm,
            rsa_padding,
            ecdsa_deterministic,
        )


    def test_hash(self, backend):
        sct1 = (
            _load_data(
                os.path.join("x509", "ocsp", "resp-sct-extension.der"),
                ocsp.load_der_ocsp_response,
            )
            .single_extensions.get_extension_for_class(
                x509.SignedCertificateTimestamps
            )
            .value
        )
        sct2 = (
            _load_data(
                os.path.join("x509", "ocsp", "resp-sct-extension.der"),
                ocsp.load_der_ocsp_response,
            )
            .single_extensions.get_extension_for_class(
                x509.SignedCertificateTimestamps
            )
            .value
        )
        sct3 = x509.SignedCertificateTimestamps([])
        assert hash(sct1) == hash(sct2)
        assert hash(sct1) != hash(sct3)

    def test_hash(self, backend):
        sct1 = (
            _load_data(
                os.path.join("x509", "ocsp", "resp-sct-extension.der"),
                ocsp.load_der_ocsp_response,
            )
            .single_extensions.get_extension_for_class(
                x509.SignedCertificateTimestamps
            )
            .value
        )
        sct2 = (
            _load_data(
                os.path.join("x509", "ocsp", "resp-sct-extension.der"),
                ocsp.load_der_ocsp_response,
            )
            .single_extensions.get_extension_for_class(
                x509.SignedCertificateTimestamps
            )
            .value
        )
        sct3 = x509.SignedCertificateTimestamps([])
        assert hash(sct1) == hash(sct2)
        <AssertPlaceHolder>

class SignedCertificateTimestamps(ExtensionType):
    oid = ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS

    def __init__(
        self,
        signed_certificate_timestamps: Iterable[SignedCertificateTimestamp],
    ) -> None:
        signed_certificate_timestamps = list(signed_certificate_timestamps)
        if not all(
            isinstance(sct, SignedCertificateTimestamp)
            for sct in signed_certificate_timestamps
        ):
            raise TypeError(
                "Every item in the signed_certificate_timestamps list must be "
                "a SignedCertificateTimestamp"
            )
        self._signed_certificate_timestamps = signed_certificate_timestamps

    __len__, __iter__, __getitem__ = _make_sequence_methods(
        "_signed_certificate_timestamps"
    )

    def __repr__(self) -> str:
        return f"<SignedCertificateTimestamps({list(self)})>"

    def __hash__(self) -> int:
        return hash(tuple(self._signed_certificate_timestamps))

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, SignedCertificateTimestamps):
            return NotImplemented

        return (
            self._signed_certificate_timestamps
            == other._signed_certificate_timestamps
        )

    def public_bytes(self) -> bytes:
        return rust_x509.encode_extension_value(self)


    def test_ne(self, backend):
        sct1 = (
            _load_data(
                os.path.join("x509", "ocsp", "resp-sct-extension.der"),
                ocsp.load_der_ocsp_response,
            )
            .single_extensions.get_extension_for_class(
                x509.SignedCertificateTimestamps
            )
            .value
        )
        sct2 = x509.SignedCertificateTimestamps([])
        assert sct1 != sct2
        assert sct1 != object()

    def test_ne(self, backend):
        sct1 = (
            _load_data(
                os.path.join("x509", "ocsp", "resp-sct-extension.der"),
                ocsp.load_der_ocsp_response,
            )
            .single_extensions.get_extension_for_class(
                x509.SignedCertificateTimestamps
            )
            .value
        )
        sct2 = x509.SignedCertificateTimestamps([])
        <AssertPlaceHolder>
        assert sct1 != object()


    def test_public_bytes(self):
        ext = x509.DeltaCRLIndicator(2)
        assert ext.public_bytes() == b"\x02\x01\x02"

    def test_public_bytes(self):
        ext = x509.DeltaCRLIndicator(2)
        <AssertPlaceHolder>

    def public_bytes(self) -> bytes:
        return rust_x509.encode_extension_value(self)


    def test_no_parsed_hostname(self):
        gn = x509.UniformResourceIdentifier("singlelabel")
        assert gn.value == "singlelabel"

    def test_no_parsed_hostname(self):
        gn = x509.UniformResourceIdentifier("singlelabel")
        <AssertPlaceHolder>


    def test_repr(self):
        gn = x509.IPAddress(ipaddress.IPv4Address("127.0.0.1"))
        assert repr(gn) == "<IPAddress(value=127.0.0.1)>"

        gn2 = x509.IPAddress(ipaddress.IPv6Address("ff::"))
        assert repr(gn2) == "<IPAddress(value=ff::)>"

        gn3 = x509.IPAddress(ipaddress.IPv4Network("192.168.0.0/24"))
        assert repr(gn3) == "<IPAddress(value=192.168.0.0/24)>"

        gn4 = x509.IPAddress(ipaddress.IPv6Network("ff::/96"))
        assert repr(gn4) == "<IPAddress(value=ff::/96)>"

    def test_repr(self):
        gn = x509.IPAddress(ipaddress.IPv4Address("127.0.0.1"))
        assert repr(gn) == "<IPAddress(value=127.0.0.1)>"

        gn2 = x509.IPAddress(ipaddress.IPv6Address("ff::"))
        assert repr(gn2) == "<IPAddress(value=ff::)>"

        gn3 = x509.IPAddress(ipaddress.IPv4Network("192.168.0.0/24"))
        <AssertPlaceHolder>

        gn4 = x509.IPAddress(ipaddress.IPv6Network("ff::/96"))
        assert repr(gn4) == "<IPAddress(value=ff::/96)>"

class IPAddress(GeneralName):
    def __init__(self, value: _IPAddressTypes) -> None:
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network,
            ),
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value

    @property
    def value(self) -> _IPAddressTypes:
        return self._value

    def _packed(self) -> bytes:
        if isinstance(
            self.value, (ipaddress.IPv4Address, ipaddress.IPv6Address)
        ):
            return self.value.packed
        else:
            return (
                self.value.network_address.packed + self.value.netmask.packed
            )

    def __repr__(self) -> str:
        return f"<IPAddress(value={self.value})>"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, IPAddress):
            return NotImplemented

        return self.value == other.value

    def __hash__(self) -> int:
        return hash(self.value)


    def test_rsa_padding_supported_pkcs1v15(self):
        assert backend.rsa_padding_supported(padding.PKCS1v15()) is True

    def test_rsa_padding_supported_pkcs1v15(self):
        <AssertPlaceHolder>

    def rsa_padding_supported(self, padding: AsymmetricPadding) -> bool:
        if isinstance(padding, PKCS1v15):
            return True
        elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1):
            # FIPS 186-4 only allows salt length == digest length for PSS
            # It is technically acceptable to set an explicit salt length
            # equal to the digest length and this will incorrectly fail, but
            # since we don't do that in the tests and this method is
            # private, we'll ignore that until we need to do otherwise.
            if (
                self._fips_enabled
                and padding._salt_length != PSS.DIGEST_LENGTH
            ):
                return False
            return self.hash_supported(padding._mgf._algorithm)
        elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1):
            return self._oaep_hash_supported(
                padding._mgf._algorithm
            ) and self._oaep_hash_supported(padding._algorithm)
        else:
            return False


    def test_block_size_padding(self):
        padder = padding.ANSIX923(64).padder()
        data = padder.update(b"a" * 8) + padder.finalize()
        assert data == b"a" * 8 + b"\x00" * 7 + b"\x08"

    def test_block_size_padding(self):
        padder = padding.ANSIX923(64).padder()
        data = padder.update(b"a" * 8) + padder.finalize()
        <AssertPlaceHolder>


    def test_sign_with_appended_certs(self):
        builder = ocsp.OCSPResponseBuilder()
        cert, issuer = _cert_and_issuer()
        root_cert, private_key = _generate_root()
        current_time = (
            datetime.datetime.now(datetime.timezone.utc)
            .replace(tzinfo=None)
            .replace(microsecond=0)
        )
        this_update = current_time - datetime.timedelta(days=1)
        next_update = this_update + datetime.timedelta(days=7)
        builder = (
            builder.responder_id(ocsp.OCSPResponderEncoding.NAME, root_cert)
            .add_response(
                cert,
                issuer,
                hashes.SHA1(),
                ocsp.OCSPCertStatus.GOOD,
                this_update,
                next_update,
                None,
                None,
            )
            .certificates([root_cert])
        )
        resp = builder.sign(private_key, hashes.SHA256())
        assert resp.certificates == [root_cert]

    def test_sign_with_appended_certs(self):
        builder = ocsp.OCSPResponseBuilder()
        cert, issuer = _cert_and_issuer()
        root_cert, private_key = _generate_root()
        current_time = (
            datetime.datetime.now(datetime.timezone.utc)
            .replace(tzinfo=None)
            .replace(microsecond=0)
        )
        this_update = current_time - datetime.timedelta(days=1)
        next_update = this_update + datetime.timedelta(days=7)
        builder = (
            builder.responder_id(ocsp.OCSPResponderEncoding.NAME, root_cert)
            .add_response(
                cert,
                issuer,
                hashes.SHA1(),
                ocsp.OCSPCertStatus.GOOD,
                this_update,
                next_update,
                None,
                None,
            )
            .certificates([root_cert])
        )
        resp = builder.sign(private_key, hashes.SHA256())
        <AssertPlaceHolder>

    def sign(
        self,
        private_key: CertificateIssuerPrivateKeyTypes,
        algorithm: hashes.HashAlgorithm | None,
    ) -> OCSPResponse:
        if self._response is None:
            raise ValueError("You must add a response before signing")
        if self._responder_id is None:
            raise ValueError("You must add a responder_id before signing")

        return ocsp.create_ocsp_response(
            OCSPResponseStatus.SUCCESSFUL, self, private_key, algorithm
        )


    def test_recover_prime_factors(self, subtests):
        for key in [
            RSA_KEY_1024,
            RSA_KEY_1025,
            RSA_KEY_1026,
            RSA_KEY_1027,
            RSA_KEY_1028,
            RSA_KEY_1029,
            RSA_KEY_1030,
            RSA_KEY_1031,
            RSA_KEY_1536,
            RSA_KEY_2048,
        ]:
            with subtests.test():
                p, q = rsa.rsa_recover_prime_factors(
                    key.public_numbers.n,
                    key.public_numbers.e,
                    key.d,
                )
                # Unfortunately there is no convention on which prime should be
                # p and which one q. The function we use always makes p > q,
                # but the NIST vectors are not so consistent. Accordingly, we
                # verify we've recovered the proper (p, q) by sorting them and
                # asserting on that.
                assert sorted([p, q]) == sorted([key.p, key.q])
                assert p > q

    def test_recover_prime_factors(self, subtests):
        for key in [
            RSA_KEY_1024,
            RSA_KEY_1025,
            RSA_KEY_1026,
            RSA_KEY_1027,
            RSA_KEY_1028,
            RSA_KEY_1029,
            RSA_KEY_1030,
            RSA_KEY_1031,
            RSA_KEY_1536,
            RSA_KEY_2048,
        ]:
            with subtests.test():
                p, q = rsa.rsa_recover_prime_factors(
                    key.public_numbers.n,
                    key.public_numbers.e,
                    key.d,
                )
                # Unfortunately there is no convention on which prime should be
                # p and which one q. The function we use always makes p > q,
                # but the NIST vectors are not so consistent. Accordingly, we
                # verify we've recovered the proper (p, q) by sorting them and
                # asserting on that.
                <AssertPlaceHolder>
                assert p > q

def rsa_recover_prime_factors(n: int, e: int, d: int) -> tuple[int, int]:
    """
    Compute factors p and q from the private exponent d. We assume that n has
    no more than two factors. This function is adapted from code in PyCrypto.
    """
    # reject invalid values early
    if d <= 1 or e <= 1:
        raise ValueError("d, e can't be <= 1")
    if 17 != pow(17, e * d, n):
        raise ValueError("n, d, e don't match")
    # See 8.2.2(i) in Handbook of Applied Cryptography.
    ktot = d * e - 1
    # The quantity d*e-1 is a multiple of phi(n), even,
    # and can be represented as t*2^s.
    t = ktot
    while t % 2 == 0:
        t = t // 2
    # Cycle through all multiplicative inverses in Zn.
    # The algorithm is non-deterministic, but there is a 50% chance
    # any candidate a leads to successful factoring.
    # See "Digitalized Signatures and Public Key Functions as Intractable
    # as Factorization", M. Rabin, 1979
    spotted = False
    tries = 0
    while not spotted and tries < _MAX_RECOVERY_ATTEMPTS:
        a = random.randint(2, n - 1)
        tries += 1
        k = t
        # Cycle through all values a^{t*2^i}=a^k
        while k < ktot:
            cand = pow(a, k, n)
            # Check if a^k is a non-trivial root of unity (mod n)
            if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:
                # We have found a number such that (cand-1)(cand+1)=0 (mod n).
                # Either of the terms divides n.
                p = gcd(cand + 1, n)
                spotted = True
                break
            k *= 2
    if not spotted:
        raise ValueError("Unable to compute factors p and q from exponent d.")
    # Found !
    q, r = divmod(n, p)
    assert r == 0
    p, q = sorted((p, q), reverse=True)
    return (p, q)


    def test_hash(self):
        n1 = x509.DNSName("test1")
        n2 = x509.DNSName("test2")
        n3 = x509.DNSName("test2")
        assert hash(n1) != hash(n2)
        assert hash(n2) == hash(n3)

    def test_hash(self):
        n1 = x509.DNSName("test1")
        n2 = x509.DNSName("test2")
        n3 = x509.DNSName("test2")
        <AssertPlaceHolder>
        assert hash(n2) == hash(n3)

class DNSName(GeneralName):
    def __init__(self, value: str) -> None:
        if isinstance(value, str):
            try:
                value.encode("ascii")
            except UnicodeEncodeError:
                raise ValueError(
                    "DNSName values should be passed as an A-label string. "
                    "This means unicode characters should be encoded via "
                    "a library like idna."
                )
        else:
            raise TypeError("value must be string")

        self._value = value

    @property
    def value(self) -> str:
        return self._value

    @classmethod
    def _init_without_validation(cls, value: str) -> DNSName:
        instance = cls.__new__(cls)
        instance._value = value
        return instance

    def __repr__(self) -> str:
        return f"<DNSName(value={self.value!r})>"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, DNSName):
            return NotImplemented

        return self.value == other.value

    def __hash__(self) -> int:
        return hash(self.value)


    def test_generate(self, backend):
        key = X448PrivateKey.generate()
        assert key
        assert key.public_key()

    def test_generate(self, backend):
        key = X448PrivateKey.generate()
        assert key
        <AssertPlaceHolder>

    @classmethod
    def generate(cls) -> X448PrivateKey:
        from cryptography.hazmat.backends.openssl.backend import backend

        if not backend.x448_supported():
            raise UnsupportedAlgorithm(
                "X448 is not supported by this version of OpenSSL.",
                _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM,
            )

        return rust_openssl.x448.generate_key()


    def test_delta_crl_indicator(self, backend):
        crl = _load_cert(
            os.path.join("x509", "custom", "crl_delta_crl_indicator.pem"),
            x509.load_pem_x509_crl,
        )

        dci = crl.extensions.get_extension_for_oid(
            ExtensionOID.DELTA_CRL_INDICATOR
        )
        assert dci.value == x509.DeltaCRLIndicator(12345678901234567890)
        assert dci.critical is True

    def test_delta_crl_indicator(self, backend):
        crl = _load_cert(
            os.path.join("x509", "custom", "crl_delta_crl_indicator.pem"),
            x509.load_pem_x509_crl,
        )

        dci = crl.extensions.get_extension_for_oid(
            ExtensionOID.DELTA_CRL_INDICATOR
        )
        assert dci.value == x509.DeltaCRLIndicator(12345678901234567890)
        <AssertPlaceHolder>

    def get_extension_for_oid(
        self, oid: ObjectIdentifier
    ) -> Extension[ExtensionType]:
        for ext in self:
            if ext.oid == oid:
                return ext

        raise ExtensionNotFound(f"No {oid} extension was found", oid)


    def test_with_port(self):
        gn = x509.UniformResourceIdentifier("singlelabel:443/test")
        assert gn.value == "singlelabel:443/test"

    def test_with_port(self):
        gn = x509.UniformResourceIdentifier("singlelabel:443/test")
        <AssertPlaceHolder>


    @pytest.mark.supported(
        only_if=lambda backend: backend.ed448_supported(),
        skip_message="Requires OpenSSL with Ed448 support",
    )
    def test_build_ca_request_with_ed448(self, backend):
        private_key = ed448.Ed448PrivateKey.generate()

        request = (
            x509.CertificateSigningRequestBuilder()
            .subject_name(
                x509.Name(
                    [
                        x509.NameAttribute(
                            NameOID.STATE_OR_PROVINCE_NAME, "Texas"
                        ),
                    ]
                )
            )
            .add_extension(
                x509.BasicConstraints(ca=True, path_length=2), critical=True
            )
            .sign(private_key, None, backend)
        )

        assert request.signature_hash_algorithm is None
        public_key = request.public_key()
        assert isinstance(public_key, ed448.Ed448PublicKey)
        subject = request.subject
        assert isinstance(subject, x509.Name)
        assert list(subject) == [
            x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Texas"),
        ]
        basic_constraints = request.extensions.get_extension_for_class(
            x509.BasicConstraints
        )
        assert basic_constraints.value.ca is True
        assert basic_constraints.value.path_length == 2

    @pytest.mark.supported(
        only_if=lambda backend: backend.ed448_supported(),
        skip_message="Requires OpenSSL with Ed448 support",
    )
    def test_build_ca_request_with_ed448(self, backend):
        private_key = ed448.Ed448PrivateKey.generate()

        request = (
            x509.CertificateSigningRequestBuilder()
            .subject_name(
                x509.Name(
                    [
                        x509.NameAttribute(
                            NameOID.STATE_OR_PROVINCE_NAME, "Texas"
                        ),
                    ]
                )
            )
            .add_extension(
                x509.BasicConstraints(ca=True, path_length=2), critical=True
            )
            .sign(private_key, None, backend)
        )

        assert request.signature_hash_algorithm is None
        public_key = request.public_key()
        assert isinstance(public_key, ed448.Ed448PublicKey)
        subject = request.subject
        assert isinstance(subject, x509.Name)
        assert list(subject) == [
            x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Texas"),
        ]
        basic_constraints = request.extensions.get_extension_for_class(
            x509.BasicConstraints
        )
        <AssertPlaceHolder>
        assert basic_constraints.value.path_length == 2

    def get_extension_for_class(
        self, extclass: type[ExtensionTypeVar]
    ) -> Extension[ExtensionTypeVar]:
        if extclass is UnrecognizedExtension:
            raise TypeError(
                "UnrecognizedExtension can't be used with "
                "get_extension_for_class because more than one instance of the"
                " class may be present."
            )

        for ext in self:
            if isinstance(ext.value, extclass):
                return ext

        raise ExtensionNotFound(
            f"No {extclass} extension was found", extclass.oid
        )


@pytest.mark.supported(
    only_if=lambda backend: backend.ed25519_supported(),
    skip_message="Requires OpenSSL with Ed25519 support",
)
def test_public_key_equality(backend):
    key_bytes = load_vectors_from_file(
        os.path.join("asymmetric", "Ed25519", "ed25519-pkcs8.der"),
        lambda derfile: derfile.read(),
        mode="rb",
    )
    key1 = serialization.load_der_private_key(key_bytes, None).public_key()
    key2 = serialization.load_der_private_key(key_bytes, None).public_key()
    key3 = Ed25519PrivateKey.generate().public_key()
    assert key1 == key2
    assert key1 != key3
    assert key1 != object()

    with pytest.raises(TypeError):
        key1 < key2  # type: ignore[operator]

@pytest.mark.supported(
    only_if=lambda backend: backend.ed25519_supported(),
    skip_message="Requires OpenSSL with Ed25519 support",
)
def test_public_key_equality(backend):
    key_bytes = load_vectors_from_file(
        os.path.join("asymmetric", "Ed25519", "ed25519-pkcs8.der"),
        lambda derfile: derfile.read(),
        mode="rb",
    )
    key1 = serialization.load_der_private_key(key_bytes, None).public_key()
    key2 = serialization.load_der_private_key(key_bytes, None).public_key()
    key3 = Ed25519PrivateKey.generate().public_key()
    assert key1 == key2
    <AssertPlaceHolder>
    assert key1 != object()

    with pytest.raises(TypeError):
        key1 < key2  # type: ignore[operator]

    @abc.abstractmethod
    def public_key(self) -> Ed25519PublicKey:
        """
        The Ed25519PublicKey derived from the private key.
        """


    def test_idna2003_invalid(self, backend):
        cert = _load_cert(
            os.path.join("x509", "custom", "san_idna2003_dnsname.pem"),
            x509.load_pem_x509_certificate,
        )
        san = cert.extensions.get_extension_for_class(
            x509.SubjectAlternativeName
        ).value

        assert len(san) == 1
        [name] = san
        assert name.value == "xn--k4h.ws"

    def test_idna2003_invalid(self, backend):
        cert = _load_cert(
            os.path.join("x509", "custom", "san_idna2003_dnsname.pem"),
            x509.load_pem_x509_certificate,
        )
        san = cert.extensions.get_extension_for_class(
            x509.SubjectAlternativeName
        ).value

        assert len(san) == 1
        [name] = san
        <AssertPlaceHolder>


    def test_encrypt(self, backend):
        f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
        f2 = Fernet(base64.urlsafe_b64encode(b"\x01" * 32), backend=backend)
        f = MultiFernet([f1, f2])

        assert f1.decrypt(f.encrypt(b"abc")) == b"abc"

    def test_encrypt(self, backend):
        f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
        f2 = Fernet(base64.urlsafe_b64encode(b"\x01" * 32), backend=backend)
        f = MultiFernet([f1, f2])

        <AssertPlaceHolder>

    def decrypt(self, token: bytes | str, ttl: int | None = None) -> bytes:
        timestamp, data = Fernet._get_unverified_token_data(token)
        if ttl is None:
            time_info = None
        else:
            time_info = (ttl, int(time.time()))
        return self._decrypt_data(data, timestamp, time_info)


    def test_ne(self):
        eku = x509.ExtendedKeyUsage([x509.ObjectIdentifier("1.3.6")])
        eku2 = x509.ExtendedKeyUsage([x509.ObjectIdentifier("1.3.6.1")])
        assert eku != eku2
        assert eku != object()

    def test_ne(self):
        eku = x509.ExtendedKeyUsage([x509.ObjectIdentifier("1.3.6")])
        eku2 = x509.ExtendedKeyUsage([x509.ObjectIdentifier("1.3.6.1")])
        <AssertPlaceHolder>
        assert eku != object()

class ExtendedKeyUsage(ExtensionType):
    oid = ExtensionOID.EXTENDED_KEY_USAGE

    def __init__(self, usages: Iterable[ObjectIdentifier]) -> None:
        usages = list(usages)
        if not all(isinstance(x, ObjectIdentifier) for x in usages):
            raise TypeError(
                "Every item in the usages list must be an ObjectIdentifier"
            )

        self._usages = usages

    __len__, __iter__, __getitem__ = _make_sequence_methods("_usages")

    def __repr__(self) -> str:
        return f"<ExtendedKeyUsage({self._usages})>"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, ExtendedKeyUsage):
            return NotImplemented

        return self._usages == other._usages

    def __hash__(self) -> int:
        return hash(tuple(self._usages))

    def public_bytes(self) -> bytes:
        return rust_x509.encode_extension_value(self)


    def test_hash(self):
        cdp = x509.CRLDistributionPoints(
            [
                x509.DistributionPoint(
                    [x509.UniformResourceIdentifier("ftp://domain")],
                    None,
                    frozenset(
                        [
                            x509.ReasonFlags.key_compromise,
                            x509.ReasonFlags.ca_compromise,
                        ]
                    ),
                    [x509.UniformResourceIdentifier("uri://thing")],
                ),
            ]
        )
        cdp2 = x509.CRLDistributionPoints(
            [
                x509.DistributionPoint(
                    [x509.UniformResourceIdentifier("ftp://domain")],
                    None,
                    frozenset(
                        [
                            x509.ReasonFlags.key_compromise,
                            x509.ReasonFlags.ca_compromise,
                        ]
                    ),
                    [x509.UniformResourceIdentifier("uri://thing")],
                ),
            ]
        )
        cdp3 = x509.CRLDistributionPoints(
            [
                x509.DistributionPoint(
                    [x509.UniformResourceIdentifier("ftp://domain")],
                    None,
                    frozenset([x509.ReasonFlags.key_compromise]),
                    [x509.UniformResourceIdentifier("uri://thing")],
                ),
            ]
        )
        assert hash(cdp) == hash(cdp2)
        assert hash(cdp) != hash(cdp3)

    def test_hash(self):
        cdp = x509.CRLDistributionPoints(
            [
                x509.DistributionPoint(
                    [x509.UniformResourceIdentifier("ftp://domain")],
                    None,
                    frozenset(
                        [
                            x509.ReasonFlags.key_compromise,
                            x509.ReasonFlags.ca_compromise,
                        ]
                    ),
                    [x509.UniformResourceIdentifier("uri://thing")],
                ),
            ]
        )
        cdp2 = x509.CRLDistributionPoints(
            [
                x509.DistributionPoint(
                    [x509.UniformResourceIdentifier("ftp://domain")],
                    None,
                    frozenset(
                        [
                            x509.ReasonFlags.key_compromise,
                            x509.ReasonFlags.ca_compromise,
                        ]
                    ),
                    [x509.UniformResourceIdentifier("uri://thing")],
                ),
            ]
        )
        cdp3 = x509.CRLDistributionPoints(
            [
                x509.DistributionPoint(
                    [x509.UniformResourceIdentifier("ftp://domain")],
                    None,
                    frozenset([x509.ReasonFlags.key_compromise]),
                    [x509.UniformResourceIdentifier("uri://thing")],
                ),
            ]
        )
        assert hash(cdp) == hash(cdp2)
        <AssertPlaceHolder>

class CRLDistributionPoints(ExtensionType):
    oid = ExtensionOID.CRL_DISTRIBUTION_POINTS

    def __init__(
        self, distribution_points: Iterable[DistributionPoint]
    ) -> None:
        distribution_points = list(distribution_points)
        if not all(
            isinstance(x, DistributionPoint) for x in distribution_points
        ):
            raise TypeError(
                "distribution_points must be a list of DistributionPoint "
                "objects"
            )

        self._distribution_points = distribution_points

    __len__, __iter__, __getitem__ = _make_sequence_methods(
        "_distribution_points"
    )

    def __repr__(self) -> str:
        return f"<CRLDistributionPoints({self._distribution_points})>"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, CRLDistributionPoints):
            return NotImplemented

        return self._distribution_points == other._distribution_points

    def __hash__(self) -> int:
        return hash(tuple(self._distribution_points))

    def public_bytes(self) -> bytes:
        return rust_x509.encode_extension_value(self)


    def test_iter_input(self):
        usages = [
            x509.ObjectIdentifier("1.3.6.1.5.5.7.3.1"),
            x509.ObjectIdentifier("1.3.6.1.5.5.7.3.2"),
        ]
        aia = x509.ExtendedKeyUsage(iter(usages))
        assert list(aia) == usages

    def test_iter_input(self):
        usages = [
            x509.ObjectIdentifier("1.3.6.1.5.5.7.3.1"),
            x509.ObjectIdentifier("1.3.6.1.5.5.7.3.2"),
        ]
        aia = x509.ExtendedKeyUsage(iter(usages))
        <AssertPlaceHolder>