async def test_disabled_log_no_attribute_error() -> None:
    """Ensure that initializing the log with disabled=True does not
    raise an AttributeError.
    Regression test for https://github.com/Textualize/textual/issues/5028
    """

    class DisabledLogApp(App):
        def compose(self) -> ComposeResult:
            yield Log(disabled=True)

    async with DisabledLogApp().run_test() as pilot:
        # If no exception is raised, the test will pass
        log = pilot.app.query_one(Log)
        assert log.disabled == True

async def test_disabled_log_no_attribute_error() -> None:
    """Ensure that initializing the log with disabled=True does not
    raise an AttributeError.
    Regression test for https://github.com/Textualize/textual/issues/5028
    """

    class DisabledLogApp(App):
        def compose(self) -> ComposeResult:
            yield Log(disabled=True)

    async with DisabledLogApp().run_test() as pilot:
        # If no exception is raised, the test will pass
        log = pilot.app.query_one(Log)
        <AssertPlaceHolder>


python -m venv .venv
source .venv/bin/activate
hash -r
poetry env use python
poetry install --with dev
pip install ipdb

async def test_replace_option_prompt_with_valid_index() -> None:
    """It should be possible to replace the prompt of an option index that does exist."""
    async with OptionListApp().run_test() as pilot:
        option_list = pilot.app.query_one(OptionList).replace_option_prompt_at_index(1, "new-prompt")
        assert option_list.get_option_at_index(1).prompt == "new-prompt"

async def test_replace_option_prompt_with_valid_index() -> None:
    """It should be possible to replace the prompt of an option index that does exist."""
    async with OptionListApp().run_test() as pilot:
        option_list = pilot.app.query_one(OptionList).replace_option_prompt_at_index(1, "new-prompt")
        <AssertPlaceHolder>

    def get_option_at_index(self, index: int) -> Option:
        """Get the option at the given index.

        Args:
            index: The index of the option to get.

        Returns:
            The option at that index.

        Raises:
            OptionDoesNotExist: If there is no option with the given index.
        """
        try:
            return self._options[index]
        except IndexError:
            raise OptionDoesNotExist(
                f"There is no option with an index of {index}"
            ) from None


async def test_universal_selector_doesnt_select_self():
    class ExampleApp(App):
        def compose(self) -> ComposeResult:
            yield Container(
                Widget(
                    Widget(),
                    Widget(
                        Widget(),
                    ),
                ),
                Widget(),
                id="root-container",
            )

    app = ExampleApp()
    async with app.run_test():
        container = app.query_one("#root-container", Container)
        query = container.query("*")
        results = list(query.results())
        assert len(results) == 5
        assert not any(node.id == "root-container" for node in results)

async def test_universal_selector_doesnt_select_self():
    class ExampleApp(App):
        def compose(self) -> ComposeResult:
            yield Container(
                Widget(
                    Widget(),
                    Widget(
                        Widget(),
                    ),
                ),
                Widget(),
                id="root-container",
            )

    app = ExampleApp()
    async with app.run_test():
        container = app.query_one("#root-container", Container)
        query = container.query("*")
        results = list(query.results())
        assert len(results) == 5
        <AssertPlaceHolder>

        @overload
        def results(self) -> Iterator[QueryType]: ...


async def test_overflow_change_updates_virtual_size_appropriately():
    class MyApp(App):
        def compose(self):
            yield VerticalScroll()

    app = MyApp()

    async with app.run_test() as pilot:
        vertical = app.query_one(VerticalScroll)

        height = vertical.virtual_size.height

        vertical.styles.overflow_x = "scroll"
        await pilot.pause()  # Let changes propagate.
        assert vertical.virtual_size.height < height

        vertical.styles.overflow_x = "hidden"
        await pilot.pause()
        assert vertical.virtual_size.height == height

        width = vertical.virtual_size.width

        vertical.styles.overflow_y = "scroll"
        await pilot.pause()
        assert vertical.virtual_size.width < width

        vertical.styles.overflow_y = "hidden"
        await pilot.pause()
        assert vertical.virtual_size.width == width

async def test_overflow_change_updates_virtual_size_appropriately():
    class MyApp(App):
        def compose(self):
            yield VerticalScroll()

    app = MyApp()

    async with app.run_test() as pilot:
        vertical = app.query_one(VerticalScroll)

        height = vertical.virtual_size.height

        vertical.styles.overflow_x = "scroll"
        await pilot.pause()  # Let changes propagate.
        assert vertical.virtual_size.height < height

        vertical.styles.overflow_x = "hidden"
        await pilot.pause()
        <AssertPlaceHolder>

        width = vertical.virtual_size.width

        vertical.styles.overflow_y = "scroll"
        await pilot.pause()
        assert vertical.virtual_size.width < width

        vertical.styles.overflow_y = "hidden"
        await pilot.pause()
        assert vertical.virtual_size.width == width

        @overload
        def query_one(self, selector: str) -> Widget: ...


async def test_softbreak_split_links_rendered_correctly() -> None:
    """Test for https://github.com/Textualize/textual/issues/2805"""

    document = """\
My site [has
this
URL](https://example.com)\
"""
    async with MarkdownApp(document).run_test() as pilot:
        markdown = pilot.app.query_one(Markdown)
        paragraph = markdown.children[0]
        assert isinstance(paragraph, MD.MarkdownParagraph)
        assert paragraph._content.plain == "My site has this URL"
        print(paragraph._content.spans)

        expected_spans = [
            Span(8, 20, Style.from_meta({"@click": "link('https://example.com')"})),
        ]
        print(expected_spans)

    assert paragraph._content.spans == expected_spans

async def test_softbreak_split_links_rendered_correctly() -> None:
    """Test for https://github.com/Textualize/textual/issues/2805"""

    document = """\
My site [has
this
URL](https://example.com)\
"""
    async with MarkdownApp(document).run_test() as pilot:
        markdown = pilot.app.query_one(Markdown)
        paragraph = markdown.children[0]
        assert isinstance(paragraph, MD.MarkdownParagraph)
        <AssertPlaceHolder>
        print(paragraph._content.spans)

        expected_spans = [
            Span(8, 20, Style.from_meta({"@click": "link('https://example.com')"})),
        ]
        print(expected_spans)

    assert paragraph._content.spans == expected_spans


async def test_delete_word_left_to_start_of_line():
    """If no word boundary found when we 'delete word left', then
    the deletion happens to the start of the line."""
    app = TextAreaApp()
    async with app.run_test() as pilot:
        text_area = app.query_one(TextArea)
        text_area.load_text("0123\n   456789")
        text_area.selection = Selection.cursor((1, 3))

        await pilot.press("ctrl+w")

        assert text_area.text == "0123\n456789"
        assert text_area.selection == Selection.cursor((1, 0))

async def test_delete_word_left_to_start_of_line():
    """If no word boundary found when we 'delete word left', then
    the deletion happens to the start of the line."""
    app = TextAreaApp()
    async with app.run_test() as pilot:
        text_area = app.query_one(TextArea)
        text_area.load_text("0123\n   456789")
        text_area.selection = Selection.cursor((1, 3))

        await pilot.press("ctrl+w")

        <AssertPlaceHolder>
        assert text_area.selection == Selection.cursor((1, 0))

    @classmethod
    def cursor(cls, location: Location) -> "Selection":
        """Create a Selection with the same start and end point - a "cursor".

        Args:
            location: The location to create the zero-width Selection.
        """
        return cls(location, location)


async def test_tree_node_toggle_all() -> None:
    """Toggling all on a node should toggle all child nodes too."""
    async with TreeApp().run_test() as pilot:
        assert pilot.app.query_one(Tree).root.is_expanded is False
        check_node = pilot.app.query_one(Tree).root.children[0]
        while check_node.children:
            assert any(child.is_expanded for child in check_node.children) is False
            check_node = check_node.children[0]
        pilot.app.query_one(Tree).root.toggle_all()
        assert pilot.app.query_one(Tree).root.is_expanded is True
        check_node = pilot.app.query_one(Tree).root.children[0]
        while check_node.children:
            assert check_node.children[0].is_expanded is True
            assert any(child.is_expanded for child in check_node.children[1:]) is False
            check_node = check_node.children[0]
        pilot.app.query_one(Tree).root.toggle_all()
        assert pilot.app.query_one(Tree).root.is_expanded is False
        check_node = pilot.app.query_one(Tree).root.children[0]
        while check_node.children:
            assert any(child.is_expanded for child in check_node.children) is False
            check_node = check_node.children[0]

async def test_tree_node_toggle_all() -> None:
    """Toggling all on a node should toggle all child nodes too."""
    async with TreeApp().run_test() as pilot:
        <AssertPlaceHolder>
        check_node = pilot.app.query_one(Tree).root.children[0]
        while check_node.children:
            assert any(child.is_expanded for child in check_node.children) is False
            check_node = check_node.children[0]
        pilot.app.query_one(Tree).root.toggle_all()
        assert pilot.app.query_one(Tree).root.is_expanded is True
        check_node = pilot.app.query_one(Tree).root.children[0]
        while check_node.children:
            assert check_node.children[0].is_expanded is True
            assert any(child.is_expanded for child in check_node.children[1:]) is False
            check_node = check_node.children[0]
        pilot.app.query_one(Tree).root.toggle_all()
        <AssertPlaceHolder>
        check_node = pilot.app.query_one(Tree).root.children[0]
        while check_node.children:
            assert any(child.is_expanded for child in check_node.children) is False
            check_node = check_node.children[0]


def test_clear() -> None:
    """It should be possible to clear all notifications."""
    tester = Notifications()
    for _ in range(100):
        tester.add(Notification("test", timeout=120))
    assert len(tester) == 100
    tester.clear()
    assert len(tester) == 0

def test_clear() -> None:
    """It should be possible to clear all notifications."""
    tester = Notifications()
    for _ in range(100):
        tester.add(Notification("test", timeout=120))
    <AssertPlaceHolder>
    tester.clear()
    assert len(tester) == 0

class Notifications:
    """Class for managing a collection of notifications."""

    def __init__(self) -> None:
        """Initialise the notification collection."""
        self._notifications: dict[str, Notification] = {}

    def _reap(self) -> Self:
        """Remove any expired notifications from the notification collection."""
        for notification in list(self._notifications.values()):
            if notification.has_expired:
                del self._notifications[notification.identity]
        return self

    def add(self, notification: Notification) -> Self:
        """Add the given notification to the collection of managed notifications.

        Args:
            notification: The notification to add.

        Returns:
            Self.
        """
        self._reap()._notifications[notification.identity] = notification
        return self

    def clear(self) -> Self:
        """Clear all the notifications."""
        self._notifications.clear()
        return self

    def __len__(self) -> int:
        """The number of notifications."""
        return len(self._reap()._notifications)

    def __iter__(self) -> Iterator[Notification]:
        return iter(self._reap()._notifications.values())

    def __contains__(self, notification: Notification) -> bool:
        return notification.identity in self._notifications

    def __delitem__(self, notification: Notification) -> None:
        try:
            del self._reap()._notifications[notification.identity]
        except KeyError:
            # An attempt to remove a notification we don't know about is a
            # no-op. What matters here is that the notification is forgotten
            # about, and it looks like a caller has tried to be
            # belt-and-braces. We're fine with this.
            pass


async def test_disabled_tab_is_not_activated_by_clicking_underline():
    """Regression test for https://github.com/Textualize/textual/issues/4701"""

    class DisabledTabApp(App):
        def compose(self) -> ComposeResult:
            yield Tabs(
                Tab("Enabled", id="enabled"),
                Tab("Disabled", id="disabled", disabled=True),
            )

    app = DisabledTabApp()
    async with app.run_test() as pilot:
        # Click the underline beneath the disabled tab
        await pilot.click(Tabs, offset=(14, 2))
        tabs = pilot.app.query_one(Tabs)
        assert tabs.active_tab is not None
        assert tabs.active_tab.id == "enabled"

async def test_disabled_tab_is_not_activated_by_clicking_underline():
    """Regression test for https://github.com/Textualize/textual/issues/4701"""

    class DisabledTabApp(App):
        def compose(self) -> ComposeResult:
            yield Tabs(
                Tab("Enabled", id="enabled"),
                Tab("Disabled", id="disabled", disabled=True),
            )

    app = DisabledTabApp()
    async with app.run_test() as pilot:
        # Click the underline beneath the disabled tab
        await pilot.click(Tabs, offset=(14, 2))
        tabs = pilot.app.query_one(Tabs)
        <AssertPlaceHolder>
        assert tabs.active_tab.id == "enabled"


async def test_focus_next_and_previous_with_type_selector():
    """Move focus with a selector that matches the currently focused node."""
    app = FocusTestApp()
    async with app.run_test():
        screen = app.screen

        screen.set_focus(screen.query_one("#Paul"))
        assert screen.focused.id == "Paul"

        assert screen.focus_next(Focusable).id == "baz"
        assert screen.focus_next(Focusable).id == "child"

        assert screen.focus_previous(Focusable).id == "baz"
        assert screen.focus_previous(Focusable).id == "Paul"
        assert screen.focus_previous(Focusable).id == "container1"
        assert screen.focus_previous(Focusable).id == "foo"

async def test_focus_next_and_previous_with_type_selector():
    """Move focus with a selector that matches the currently focused node."""
    app = FocusTestApp()
    async with app.run_test():
        screen = app.screen

        screen.set_focus(screen.query_one("#Paul"))
        assert screen.focused.id == "Paul"

        assert screen.focus_next(Focusable).id == "baz"
        assert screen.focus_next(Focusable).id == "child"

        assert screen.focus_previous(Focusable).id == "baz"
        assert screen.focus_previous(Focusable).id == "Paul"
        <AssertPlaceHolder>
        assert screen.focus_previous(Focusable).id == "foo"

    def focus_previous(self, selector: str | type[QueryType] = "*") -> Widget | None:
        """Focus the previous widget, optionally filtered by a CSS selector.

        If no widget is currently focused, this will focus the first focusable widget.
        If no focusable widget matches the given CSS selector, focus is set to `None`.

        Args:
            selector: CSS selector to filter
                what nodes can be focused.

        Returns:
            Newly focused widget, or None for no focus. If the return
                is not `None`, then it is guaranteed that the widget returned matches
                the CSS selectors given in the argument.
        """
        return self._move_focus(-1, selector)


async def test_set_current_to_unknown_id() -> None:
    """Test attempting to switch to an unknown widget ID."""
    async with SwitcherApp().run_test() as pilot:
        assert pilot.app.query_one(ContentSwitcher).current is None
        assert all(
            not child.display for child in pilot.app.query_one(ContentSwitcher).children
        )
        with pytest.raises(NoMatches):
            pilot.app.query_one(ContentSwitcher).current = "does-not-exist"

async def test_set_current_to_unknown_id() -> None:
    """Test attempting to switch to an unknown widget ID."""
    async with SwitcherApp().run_test() as pilot:
        <AssertPlaceHolder>
        assert all(
            not child.display for child in pilot.app.query_one(ContentSwitcher).children
        )
        with pytest.raises(NoMatches):
            pilot.app.query_one(ContentSwitcher).current = "does-not-exist"


def test_get_tree_node_by_id() -> None:
    """It should be possible to get a TreeNode by its ID."""
    tree = Tree[None]("Anakin")
    child = tree.root.add("Leia")
    grandchild = child.add("Ben")
    assert tree.get_node_by_id(tree.root.id).id == tree.root.id
    assert tree.get_node_by_id(child.id).id == child.id
    assert tree.get_node_by_id(grandchild.id).id == grandchild.id
    with pytest.raises(UnknownNodeID):
        tree.get_node_by_id(cast(NodeID, grandchild.id + 1000))

def test_get_tree_node_by_id() -> None:
    """It should be possible to get a TreeNode by its ID."""
    tree = Tree[None]("Anakin")
    child = tree.root.add("Leia")
    grandchild = child.add("Ben")
    <AssertPlaceHolder>
    assert tree.get_node_by_id(child.id).id == child.id
    assert tree.get_node_by_id(grandchild.id).id == grandchild.id
    with pytest.raises(UnknownNodeID):
        tree.get_node_by_id(cast(NodeID, grandchild.id + 1000))

    def get_node_by_id(self, node_id: NodeID) -> TreeNode[TreeDataType]:
        """Get a tree node by its ID.

        Args:
            node_id: The ID of the node to get.

        Returns:
            The node associated with that ID.

        Raises:
            UnknownNodeID: Raised if the `TreeNode` ID is unknown.
        """
        try:
            return self._tree_nodes[node_id]
        except KeyError:
            raise UnknownNodeID(f"Unknown NodeID ({node_id}) in tree") from None


async def test_click_by_widget():
    """Test that click accept a Widget instance."""
    pressed = False

    class TestApp(CenteredButtonApp):
        def on_button_pressed(self):
            nonlocal pressed
            pressed = True

    app = TestApp()
    async with app.run_test() as pilot:
        button = app.query_one(Button)
        assert not pressed
        await pilot.click(button)
        assert pressed

async def test_click_by_widget():
    """Test that click accept a Widget instance."""
    pressed = False

    class TestApp(CenteredButtonApp):
        def on_button_pressed(self):
            nonlocal pressed
            pressed = True

    app = TestApp()
    async with app.run_test() as pilot:
        button = app.query_one(Button)
        assert not pressed
        await pilot.click(button)
        <AssertPlaceHolder>


async def test_tree_simple_clear() -> None:
    """Clearing a tree should keep the old root label and data."""
    async with TreeClearApp().run_test() as pilot:
        tree = pilot.app.query_one(VerseTree)
        assert len(tree.root.children) > 1
        pilot.app.query_one(VerseTree).clear()
        assert len(tree.root.children) == 0
        assert str(tree.root.label) == "White Sun"
        assert isinstance(tree.root.data, VerseStar)

async def test_tree_simple_clear() -> None:
    """Clearing a tree should keep the old root label and data."""
    async with TreeClearApp().run_test() as pilot:
        tree = pilot.app.query_one(VerseTree)
        <AssertPlaceHolder>
        pilot.app.query_one(VerseTree).clear()
        assert len(tree.root.children) == 0
        assert str(tree.root.label) == "White Sun"
        assert isinstance(tree.root.data, VerseStar)


python -m venv .venv
source .venv/bin/activate
uv pip install -e .
uv pip install --group dev
uv pip install ipdb

    def test_items(self, d: HTTPHeaderDict) -> None:
        items = d.items()
        assert len(items) == 2
        assert list(items) == [
            ("Cookie", "foo"),
            ("Cookie", "bar"),
        ]
        assert ("Cookie", "foo") in items
        assert ("Cookie", "bar") in items
        assert ("X-Some-Header", "foo") not in items
        assert ("Cookie", "not_present") not in items
        assert ("Cookie", 1) not in items  # type: ignore[comparison-overlap]
        assert "Cookie" not in items  # type: ignore[comparison-overlap]

    def test_items(self, d: HTTPHeaderDict) -> None:
        items = d.items()
        assert len(items) == 2
        assert list(items) == [
            ("Cookie", "foo"),
            ("Cookie", "bar"),
        ]
        assert ("Cookie", "foo") in items
        assert ("Cookie", "bar") in items
        assert ("X-Some-Header", "foo") not in items
        assert ("Cookie", "not_present") not in items
        <AssertPlaceHolder>
        assert "Cookie" not in items  # type: ignore[comparison-overlap]

    def items(self) -> HTTPHeaderDictItemView:  # type: ignore[override]
        return HTTPHeaderDictItemView(self)


    def test_retry_total_none(self) -> None:
        """if Total is none, connect error should take precedence"""
        error = ConnectTimeoutError()
        retry = Retry(connect=2, total=None)
        retry = retry.increment(error=error)
        retry = retry.increment(error=error)
        with pytest.raises(MaxRetryError) as e:
            retry.increment(error=error)
        assert e.value.reason == error

        timeout_error = ReadTimeoutError(DUMMY_POOL, "/", "read timed out")
        retry = Retry(connect=2, total=None)
        retry = retry.increment(method="GET", error=timeout_error)
        retry = retry.increment(method="GET", error=timeout_error)
        retry = retry.increment(method="GET", error=timeout_error)
        assert not retry.is_exhausted()

    def test_retry_total_none(self) -> None:
        """if Total is none, connect error should take precedence"""
        error = ConnectTimeoutError()
        retry = Retry(connect=2, total=None)
        retry = retry.increment(error=error)
        retry = retry.increment(error=error)
        with pytest.raises(MaxRetryError) as e:
            retry.increment(error=error)
        assert e.value.reason == error

        timeout_error = ReadTimeoutError(DUMMY_POOL, "/", "read timed out")
        retry = Retry(connect=2, total=None)
        retry = retry.increment(method="GET", error=timeout_error)
        retry = retry.increment(method="GET", error=timeout_error)
        retry = retry.increment(method="GET", error=timeout_error)
        <AssertPlaceHolder>

    def is_exhausted(self) -> bool:
        """Are we out of retries?"""
        retry_counts = [
            x
            for x in (
                self.total,
                self.connect,
                self.read,
                self.redirect,
                self.status,
                self.other,
            )
            if x
        ]
        if not retry_counts:
            return False

        return min(retry_counts) < 0


    def test_getlist(self, d: HTTPHeaderDict) -> None:
        assert d.getlist("cookie") == ["foo", "bar"]
        assert d.getlist("Cookie") == ["foo", "bar"]
        assert d.getlist("b") == []
        d.add("b", "asdf")
        assert d.getlist("b") == ["asdf"]

    def test_getlist(self, d: HTTPHeaderDict) -> None:
        assert d.getlist("cookie") == ["foo", "bar"]
        assert d.getlist("Cookie") == ["foo", "bar"]
        <AssertPlaceHolder>
        d.add("b", "asdf")
        assert d.getlist("b") == ["asdf"]

    @typing.overload
    def getlist(self, key: str) -> list[str]: ...


    def test_render_parts(self) -> None:
        field = RequestField("somename", "data")
        parts = field._render_parts({"name": "value", "filename": "value"})
        assert 'name="value"' in parts
        assert 'filename="value"' in parts
        parts = field._render_parts([("name", "value"), ("filename", "value")])
        assert parts == 'name="value"; filename="value"'

    def test_render_parts(self) -> None:
        field = RequestField("somename", "data")
        parts = field._render_parts({"name": "value", "filename": "value"})
        assert 'name="value"' in parts
        assert 'filename="value"' in parts
        parts = field._render_parts([("name", "value"), ("filename", "value")])
        <AssertPlaceHolder>

    def _render_parts(
        self,
        header_parts: (
            dict[str, _TYPE_FIELD_VALUE | None]
            | typing.Sequence[tuple[str, _TYPE_FIELD_VALUE | None]]
        ),
    ) -> str:
        """
        Helper function to format and quote a single header.

        Useful for single headers that are composed of multiple items. E.g.,
        'Content-Disposition' fields.

        :param header_parts:
            A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format
            as `k1="v1"; k2="v2"; ...`.
        """
        iterable: typing.Iterable[tuple[str, _TYPE_FIELD_VALUE | None]]

        parts = []
        if isinstance(header_parts, dict):
            iterable = header_parts.items()
        else:
            iterable = header_parts

        for name, value in iterable:
            if value is not None:
                parts.append(self._render_part(name, value))

        return "; ".join(parts)


    def test_override_pool_kwargs_url(self) -> None:
        """Assert overriding pool kwargs works with connection_from_url."""
        p = PoolManager()
        pool_kwargs = {"retries": 100, "block": True}

        default_pool = p.connection_from_url("http://example.com/")
        override_pool = p.connection_from_url(
            "http://example.com/", pool_kwargs=pool_kwargs
        )

        assert retry.Retry.DEFAULT == default_pool.retries
        assert not default_pool.block

        assert 100 == override_pool.retries
        assert override_pool.block

    def test_override_pool_kwargs_url(self) -> None:
        """Assert overriding pool kwargs works with connection_from_url."""
        p = PoolManager()
        pool_kwargs = {"retries": 100, "block": True}

        default_pool = p.connection_from_url("http://example.com/")
        override_pool = p.connection_from_url(
            "http://example.com/", pool_kwargs=pool_kwargs
        )

        <AssertPlaceHolder>
        assert not default_pool.block

        assert 100 == override_pool.retries
        assert override_pool.block

    def connection_from_url(
        self, url: str, pool_kwargs: dict[str, typing.Any] | None = None
    ) -> HTTPConnectionPool:
        """
        Similar to :func:`urllib3.connectionpool.connection_from_url`.

        If ``pool_kwargs`` is not provided and a new pool needs to be
        constructed, ``self.connection_pool_kw`` is used to initialize
        the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``
        is provided, it is used instead. Note that if a new pool does not
        need to be created for the request, the provided ``pool_kwargs`` are
        not used.
        """
        u = parse_url(url)
        return self.connection_from_host(
            u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs
        )


    def test_pool_manager_no_url_absolute_form(self) -> None:
        """Valides we won't send a request with absolute form without a proxy"""
        p = PoolManager()
        assert p._proxy_requires_url_absolute_form(Url("http://example.com")) is False
        assert p._proxy_requires_url_absolute_form(Url("https://example.com")) is False

    def test_pool_manager_no_url_absolute_form(self) -> None:
        """Valides we won't send a request with absolute form without a proxy"""
        p = PoolManager()
        <AssertPlaceHolder>
        assert p._proxy_requires_url_absolute_form(Url("https://example.com")) is False

    def _proxy_requires_url_absolute_form(self, parsed_url: Url) -> bool:
        """
        Indicates if the proxy requires the complete destination URL in the
        request.  Normally this is only needed when not using an HTTP CONNECT
        tunnel.
        """
        if self.proxy is None:
            return False

        return not connection_requires_http_tunnel(
            self.proxy, self.proxy_config, parsed_url.scheme
        )


    def test_stream_keepalive(self) -> None:
        x = 2

        with HTTPConnectionPool(self.host, self.port) as pool:
            for _ in range(x):
                response = pool.request(
                    "GET",
                    "/chunked",
                    headers={"Connection": "keep-alive"},
                    preload_content=False,
                    retries=False,
                )
                for chunk in response.stream():
                    assert chunk == b"123"

            assert pool.num_connections == 1
            assert pool.num_requests == x

    def test_stream_keepalive(self) -> None:
        x = 2

        with HTTPConnectionPool(self.host, self.port) as pool:
            for _ in range(x):
                response = pool.request(
                    "GET",
                    "/chunked",
                    headers={"Connection": "keep-alive"},
                    preload_content=False,
                    retries=False,
                )
                for chunk in response.stream():
                    assert chunk == b"123"

            assert pool.num_connections == 1
            <AssertPlaceHolder>

    def stream(
        self, amt: int | None = 2**16, decode_content: bool | None = None
    ) -> typing.Iterator[bytes]:
        raise NotImplementedError()


    def test_dnsname_to_stdlib_simple(self) -> None:
        """
        We can convert a dnsname to a native string when the domain is simple.
        """
        name = "उदाहरण.परीक"
        expected_result = "xn--p1b6ci4b4b3a.xn--11b5bs8d"

        assert _dnsname_to_stdlib(name) == expected_result

    def test_dnsname_to_stdlib_simple(self) -> None:
        """
        We can convert a dnsname to a native string when the domain is simple.
        """
        name = "उदाहरण.परीक"
        expected_result = "xn--p1b6ci4b4b3a.xn--11b5bs8d"

        <AssertPlaceHolder>

def _dnsname_to_stdlib(name: str) -> str | None:
    """
    Converts a dNSName SubjectAlternativeName field to the form used by the
    standard library on the given Python version.

    Cryptography produces a dNSName as a unicode string that was idna-decoded
    from ASCII bytes. We need to idna-encode that string to get it back, and
    then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib
    uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).

    If the name cannot be idna-encoded then we return None signalling that
    the name given should be skipped.
    """

    def idna_encode(name: str) -> bytes | None:
        """
        Borrowed wholesale from the Python Cryptography Project. It turns out
        that we can't just safely call `idna.encode`: it can explode for
        wildcard names. This avoids that problem.
        """
        import idna

        try:
            for prefix in ["*.", "."]:
                if name.startswith(prefix):
                    name = name[len(prefix) :]
                    return prefix.encode("ascii") + idna.encode(name)
            return idna.encode(name)
        except idna.core.IDNAError:
            return None

    # Don't send IPv6 addresses through the IDNA encoder.
    if ":" in name:
        return name

    encoded_name = idna_encode(name)
    if encoded_name is None:
        return None
    return encoded_name.decode("utf-8")


    def test_merge_pool_kwargs_invalid_key(self) -> None:
        """Assert removing invalid keys with _merge_pool_kwargs doesn't break"""
        p = PoolManager(retries=100)
        merged = p._merge_pool_kwargs({"invalid_key": None})
        assert p.connection_pool_kw == merged

    def test_merge_pool_kwargs_invalid_key(self) -> None:
        """Assert removing invalid keys with _merge_pool_kwargs doesn't break"""
        p = PoolManager(retries=100)
        merged = p._merge_pool_kwargs({"invalid_key": None})
        <AssertPlaceHolder>

    def _merge_pool_kwargs(
        self, override: dict[str, typing.Any] | None
    ) -> dict[str, typing.Any]:
        """
        Merge a dictionary of override values for self.connection_pool_kw.

        This does not modify self.connection_pool_kw and returns a new dict.
        Any keys in the override dictionary with a value of ``None`` are
        removed from the merged dictionary.
        """
        base_pool_kwargs = self.connection_pool_kw.copy()
        if override:
            for key, value in override.items():
                if value is None:
                    try:
                        del base_pool_kwargs[key]
                    except KeyError:
                        pass
                else:
                    base_pool_kwargs[key] = value
        return base_pool_kwargs


    def test_ca_certs_default_cert_required(self) -> None:
        with connection_from_url("https://google.com:80", ca_certs=DEFAULT_CA) as pool:
            conn = pool._get_conn()
            assert conn.cert_reqs == ssl.CERT_REQUIRED  # type: ignore[attr-defined]

    def test_ca_certs_default_cert_required(self) -> None:
        with connection_from_url("https://google.com:80", ca_certs=DEFAULT_CA) as pool:
            conn = pool._get_conn()
            <AssertPlaceHolder>

    def _get_conn(self, timeout: float | None = None) -> BaseHTTPConnection:
        """
        Get a connection. Will return a pooled connection if one is available.

        If no connections are available and :prop:`.block` is ``False``, then a
        fresh connection is returned.

        :param timeout:
            Seconds to wait before giving up and raising
            :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and
            :prop:`.block` is ``True``.
        """
        conn = None

        if self.pool is None:
            raise ClosedPoolError(self, "Pool is closed.")

        try:
            conn = self.pool.get(block=self.block, timeout=timeout)

        except AttributeError:  # self.pool is None
            raise ClosedPoolError(self, "Pool is closed.") from None  # Defensive:

        except queue.Empty:
            if self.block:
                raise EmptyPoolError(
                    self,
                    "Pool is empty and a new connection can't be opened due to blocking mode.",
                ) from None
            pass  # Oh well, we'll create a new connection then

        # If this is a persistent connection, check if it got disconnected
        if conn and is_connection_dropped(conn):
            log.debug("Resetting dropped connection: %s", self.host)
            conn.close()

        return conn or self._new_conn()


    def test_textplain(self) -> None:
        fields = [("k", ("somefile.txt", b"v"))]

        encoded, content_type = encode_multipart_formdata(fields, boundary=BOUNDARY)
        expected = (
            b"--" + BOUNDARY_BYTES + b"\r\n"
            b'Content-Disposition: form-data; name="k"; filename="somefile.txt"\r\n'
            b"Content-Type: text/plain\r\n"
            b"\r\n"
            b"v\r\n"
            b"--" + BOUNDARY_BYTES + b"--\r\n"
        )

        assert encoded == expected

        assert content_type == "multipart/form-data; boundary=" + str(BOUNDARY)

    def test_textplain(self) -> None:
        fields = [("k", ("somefile.txt", b"v"))]

        encoded, content_type = encode_multipart_formdata(fields, boundary=BOUNDARY)
        expected = (
            b"--" + BOUNDARY_BYTES + b"\r\n"
            b'Content-Disposition: form-data; name="k"; filename="somefile.txt"\r\n'
            b"Content-Type: text/plain\r\n"
            b"\r\n"
            b"v\r\n"
            b"--" + BOUNDARY_BYTES + b"--\r\n"
        )

        assert encoded == expected

        <AssertPlaceHolder>

def encode_multipart_formdata(
    fields: _TYPE_FIELDS, boundary: str | None = None
) -> tuple[bytes, str]:
    """
    Encode a dictionary of ``fields`` using the multipart/form-data MIME format.

    :param fields:
        Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).
        Values are processed by :func:`urllib3.fields.RequestField.from_tuples`.

    :param boundary:
        If not specified, then a random boundary will be generated using
        :func:`urllib3.filepost.choose_boundary`.
    """
    body = BytesIO()
    if boundary is None:
        boundary = choose_boundary()

    for field in iter_field_objects(fields):
        body.write(f"--{boundary}\r\n".encode("latin-1"))

        writer(body).write(field.render_headers())
        data = field.data

        if isinstance(data, int):
            data = str(data)  # Backwards compatibility

        if isinstance(data, str):
            writer(body).write(data)
        else:
            body.write(data)

        body.write(b"\r\n")

    body.write(f"--{boundary}--\r\n".encode("latin-1"))

    content_type = f"multipart/form-data; boundary={boundary}"

    return body.getvalue(), content_type


    def test_https_connection_from_url_case_insensitive(self) -> None:
        """Assert scheme case is ignored when pooling HTTPS connections."""
        p = PoolManager()
        pool = p.connection_from_url("https://example.com/")
        other_pool = p.connection_from_url("HTTPS://EXAMPLE.COM/")

        assert 1 == len(p.pools)
        assert pool is other_pool
        assert all(isinstance(key, PoolKey) for key in p.pools.keys())

    def test_https_connection_from_url_case_insensitive(self) -> None:
        """Assert scheme case is ignored when pooling HTTPS connections."""
        p = PoolManager()
        pool = p.connection_from_url("https://example.com/")
        other_pool = p.connection_from_url("HTTPS://EXAMPLE.COM/")

        assert 1 == len(p.pools)
        assert pool is other_pool
        <AssertPlaceHolder>

    def keys(self) -> set[_KT]:  # type: ignore[override]
        with self.lock:
            return set(self._container.keys())


    def test_geturl_retries(self) -> None:
        fp = BytesIO(b"")
        resp = HTTPResponse(fp, request_url="http://example.com")
        request_histories = (
            RequestHistory(
                method="GET",
                url="http://example.com",
                error=None,
                status=301,
                redirect_location="https://example.com/",
            ),
            RequestHistory(
                method="GET",
                url="https://example.com/",
                error=None,
                status=301,
                redirect_location="https://www.example.com",
            ),
        )
        retry = Retry(history=request_histories)
        resp = HTTPResponse(fp, retries=retry)
        assert resp.geturl() == "https://www.example.com"

    def test_geturl_retries(self) -> None:
        fp = BytesIO(b"")
        resp = HTTPResponse(fp, request_url="http://example.com")
        request_histories = (
            RequestHistory(
                method="GET",
                url="http://example.com",
                error=None,
                status=301,
                redirect_location="https://example.com/",
            ),
            RequestHistory(
                method="GET",
                url="https://example.com/",
                error=None,
                status=301,
                redirect_location="https://www.example.com",
            ),
        )
        retry = Retry(history=request_histories)
        resp = HTTPResponse(fp, retries=retry)
        <AssertPlaceHolder>

    def geturl(self) -> str | None:
        return self.url


    def test_add_comma_separated_multiheader(self, d: HTTPHeaderDict) -> None:
        d.add("bar", "foo")
        # The bytes value gets converted to str. The API is typed for str only,
        # but the implementation continues supports bytes.
        d.add(b"BAR", "bar")  # type: ignore[arg-type]
        d.add("Bar", "asdf")
        assert d.getlist("bar") == ["foo", "bar", "asdf"]
        assert d["bar"] == "foo, bar, asdf"

    def test_add_comma_separated_multiheader(self, d: HTTPHeaderDict) -> None:
        d.add("bar", "foo")
        # The bytes value gets converted to str. The API is typed for str only,
        # but the implementation continues supports bytes.
        d.add(b"BAR", "bar")  # type: ignore[arg-type]
        d.add("Bar", "asdf")
        <AssertPlaceHolder>
        assert d["bar"] == "foo, bar, asdf"


def test_connection_state_properties(pool: HTTPConnectionPool) -> None:
    conn = pool._get_conn()

    assert conn.is_closed is True
    assert conn.is_connected is False
    assert conn.has_connected_to_proxy is False
    assert conn.is_verified is False
    assert conn.proxy_is_verified is None

    conn.connect()

    assert conn.is_closed is False
    assert conn.is_connected is True
    assert conn.has_connected_to_proxy is False
    assert conn.is_verified is False
    assert conn.proxy_is_verified is None

    conn.request("GET", "/")
    resp = conn.getresponse()
    assert resp.status == 200

    conn.close()

    assert conn.is_closed is True
    assert conn.is_connected is False
    assert conn.has_connected_to_proxy is False
    assert conn.is_verified is False
    assert conn.proxy_is_verified is None

def test_connection_state_properties(pool: HTTPConnectionPool) -> None:
    conn = pool._get_conn()

    <AssertPlaceHolder>
    assert conn.is_connected is False
    assert conn.has_connected_to_proxy is False
    assert conn.is_verified is False
    assert conn.proxy_is_verified is None

    conn.connect()

    assert conn.is_closed is False
    assert conn.is_connected is True
    assert conn.has_connected_to_proxy is False
    assert conn.is_verified is False
    assert conn.proxy_is_verified is None

    conn.request("GET", "/")
    resp = conn.getresponse()
    assert resp.status == 200

    conn.close()

    <AssertPlaceHolder>
    assert conn.is_connected is False
    assert conn.has_connected_to_proxy is False
    assert conn.is_verified is False
    assert conn.proxy_is_verified is None

def getresponse(self) -> BaseHTTPResponse: ...


    def test_303_redirect_makes_request_lose_body(self) -> None:
        with HTTPConnectionPool(self.host, self.port) as pool:
            response = pool.request(
                "POST",
                "/redirect",
                fields={"target": "/headers_and_params", "status": "303 See Other"},
            )
        data = response.json()
        assert data["params"] == {}
        assert "Content-Type" not in HTTPHeaderDict(data["headers"])

    def test_303_redirect_makes_request_lose_body(self) -> None:
        with HTTPConnectionPool(self.host, self.port) as pool:
            response = pool.request(
                "POST",
                "/redirect",
                fields={"target": "/headers_and_params", "status": "303 See Other"},
            )
        data = response.json()
        <AssertPlaceHolder>
        assert "Content-Type" not in HTTPHeaderDict(data["headers"])

    def json(self) -> typing.Any:
        """
        Deserializes the body of the HTTP response as a Python object.

        The body of the HTTP response must be encoded using UTF-8, as per
        `RFC 8529 Section 8.1 <https://www.rfc-editor.org/rfc/rfc8259#section-8.1>`_.

        To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to
        your custom decoder instead.

        If the body of the HTTP response is not decodable to UTF-8, a
        `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a
        valid JSON document, a `json.JSONDecodeError` will be raised.

        Read more :ref:`here <json_content>`.

        :returns: The body of the HTTP response as a Python object.
        """
        data = self.data.decode("utf-8")
        return _json.loads(data)


    def test_read1_with_illegal_mix_decode_toggle(self) -> None:
        data = zlib.compress(b"foo")

        fp = BytesIO(data)

        resp = HTTPResponse(
            fp, headers={"content-encoding": "deflate"}, preload_content=False
        )

        assert resp.read1(1) == b"f"

        with pytest.raises(
            RuntimeError,
            match=(
                r"Calling read1\(decode_content=False\) is not supported after "
                r"read1\(decode_content=True\) was called"
            ),
        ):
            resp.read1(1, decode_content=False)

        with pytest.raises(
            RuntimeError,
            match=(
                r"Calling read1\(decode_content=False\) is not supported after "
                r"read1\(decode_content=True\) was called"
            ),
        ):
            resp.read1(decode_content=False)

    def test_read1_with_illegal_mix_decode_toggle(self) -> None:
        data = zlib.compress(b"foo")

        fp = BytesIO(data)

        resp = HTTPResponse(
            fp, headers={"content-encoding": "deflate"}, preload_content=False
        )

        <AssertPlaceHolder>

        with pytest.raises(
            RuntimeError,
            match=(
                r"Calling read1\(decode_content=False\) is not supported after "
                r"read1\(decode_content=True\) was called"
            ),
        ):
            resp.read1(1, decode_content=False)

        with pytest.raises(
            RuntimeError,
            match=(
                r"Calling read1\(decode_content=False\) is not supported after "
                r"read1\(decode_content=True\) was called"
            ),
        ):
            resp.read1(decode_content=False)

    def read1(
        self,
        amt: int | None = None,
        decode_content: bool | None = None,
    ) -> bytes:
        """
        Similar to ``http.client.HTTPResponse.read1`` and documented
        in :meth:`io.BufferedReader.read1`, but with an additional parameter:
        ``decode_content``.

        :param amt:
            How much of the content to read.

        :param decode_content:
            If True, will attempt to decode the body based on the
            'content-encoding' header.
        """
        if decode_content is None:
            decode_content = self.decode_content
        if amt and amt < 0:
            # Negative numbers and `None` should be treated the same.
            amt = None
        # try and respond without going to the network
        if self._has_decoded_content:
            if not decode_content:
                raise RuntimeError(
                    "Calling read1(decode_content=False) is not supported after "
                    "read1(decode_content=True) was called."
                )
            if len(self._decoded_buffer) > 0:
                if amt is None:
                    return self._decoded_buffer.get_all()
                return self._decoded_buffer.get(amt)
        if amt == 0:
            return b""

        # FIXME, this method's type doesn't say returning None is possible
        data = self._raw_read(amt, read1=True)
        if not decode_content or data is None:
            return data

        self._init_decoder()
        while True:
            flush_decoder = not data
            decoded_data = self._decode(data, decode_content, flush_decoder)
            self._decoded_buffer.put(decoded_data)
            if decoded_data or flush_decoder:
                break
            data = self._raw_read(8192, read1=True)

        if amt is None:
            return self._decoded_buffer.get_all()
        return self._decoded_buffer.get(amt)


    def test_has_ipv6_enabled_but_fails(self) -> None:
        with patch("socket.has_ipv6", True):
            with patch("socket.socket") as mock:
                instance = mock.return_value
                instance.bind = Mock(side_effect=Exception("No IPv6 here!"))
                assert not _has_ipv6("::1")

    def test_has_ipv6_enabled_but_fails(self) -> None:
        with patch("socket.has_ipv6", True):
            with patch("socket.socket") as mock:
                instance = mock.return_value
                instance.bind = Mock(side_effect=Exception("No IPv6 here!"))
                <AssertPlaceHolder>

def _has_ipv6(host: str) -> bool:
    """Returns True if the system can bind an IPv6 address."""
    sock = None
    has_ipv6 = False

    if socket.has_ipv6:
        # has_ipv6 returns true if cPython was compiled with IPv6 support.
        # It does not tell us if the system has IPv6 support enabled. To
        # determine that we must bind to an IPv6 address.
        # https://github.com/urllib3/urllib3/pull/611
        # https://bugs.python.org/issue658327
        try:
            sock = socket.socket(socket.AF_INET6)
            sock.bind((host, 0))
            has_ipv6 = True
        except Exception:
            pass

    if sock:
        sock.close()
    return has_ipv6


    def test_mock_httpresponse_stream(self) -> None:
        # Mock out a HTTP Request that does enough to make it through urllib3's
        # read() and close() calls, and also exhausts and underlying file
        # object.
        class MockHTTPRequest:
            def __init__(self) -> None:
                self.fp: BytesIO | None = None

            def read(self, amt: int) -> bytes:
                assert self.fp is not None
                data = self.fp.read(amt)
                if not data:
                    self.fp = None

                return data

            def read1(self, amt: int) -> bytes:
                return self.read(1)

            def close(self) -> None:
                self.fp = None

        bio = BytesIO(b"foo")
        fp = MockHTTPRequest()
        fp.fp = bio
        resp = HTTPResponse(fp, preload_content=False)  # type: ignore[arg-type]
        stream = resp.stream(2)

        assert next(stream) == b"fo"
        assert next(stream) == b"o"
        with pytest.raises(StopIteration):
            next(stream)

    def test_mock_httpresponse_stream(self) -> None:
        # Mock out a HTTP Request that does enough to make it through urllib3's
        # read() and close() calls, and also exhausts and underlying file
        # object.
        class MockHTTPRequest:
            def __init__(self) -> None:
                self.fp: BytesIO | None = None

            def read(self, amt: int) -> bytes:
                assert self.fp is not None
                data = self.fp.read(amt)
                if not data:
                    self.fp = None

                return data

            def read1(self, amt: int) -> bytes:
                return self.read(1)

            def close(self) -> None:
                self.fp = None

        bio = BytesIO(b"foo")
        fp = MockHTTPRequest()
        fp.fp = bio
        resp = HTTPResponse(fp, preload_content=False)  # type: ignore[arg-type]
        stream = resp.stream(2)

        assert next(stream) == b"fo"
        <AssertPlaceHolder>
        with pytest.raises(StopIteration):
            next(stream)

    def stream(
        self, amt: int | None = 2**16, decode_content: bool | None = None
    ) -> typing.Generator[bytes]:
        """
        A generator wrapper for the read() method. A call will block until
        ``amt`` bytes have been read from the connection or until the
        connection is closed.

        :param amt:
            How much of the content to read. The generator will return up to
            much data per iteration, but may return less. This is particularly
            likely when using compressed data. However, the empty string will
            never be returned.

        :param decode_content:
            If True, will attempt to decode the body based on the
            'content-encoding' header.
        """
        if self.chunked and self.supports_chunked_reads():
            yield from self.read_chunked(amt, decode_content=decode_content)
        else:
            while not is_fp_closed(self._fp) or len(self._decoded_buffer) > 0:
                data = self.read(amt=amt, decode_content=decode_content)

                if data:
                    yield data


    def test_stream_none_unchunked_response_does_not_hang(self) -> None:
        done_event = Event()

        def socket_handler(listener: socket.socket) -> None:
            sock = listener.accept()[0]

            buf = b""
            while not buf.endswith(b"\r\n\r\n"):
                buf += sock.recv(65536)

            sock.send(
                b"HTTP/1.1 200 OK\r\n"
                b"Content-Length: 12\r\n"
                b"Content-type: text/plain\r\n"
                b"\r\n"
                b"hello, world"
            )
            done_event.wait(5)
            sock.close()

        self._start_server(socket_handler)
        with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
            r = pool.request("GET", "/", timeout=LONG_TIMEOUT, preload_content=False)

            # Stream should read to the end.
            assert [b"hello, world"] == list(r.stream(None))

            done_event.set()

    def test_stream_none_unchunked_response_does_not_hang(self) -> None:
        done_event = Event()

        def socket_handler(listener: socket.socket) -> None:
            sock = listener.accept()[0]

            buf = b""
            while not buf.endswith(b"\r\n\r\n"):
                buf += sock.recv(65536)

            sock.send(
                b"HTTP/1.1 200 OK\r\n"
                b"Content-Length: 12\r\n"
                b"Content-type: text/plain\r\n"
                b"\r\n"
                b"hello, world"
            )
            done_event.wait(5)
            sock.close()

        self._start_server(socket_handler)
        with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
            r = pool.request("GET", "/", timeout=LONG_TIMEOUT, preload_content=False)

            # Stream should read to the end.
            <AssertPlaceHolder>

            done_event.set()


    def test_dict_conversion(self, d: HTTPHeaderDict) -> None:
        # Also tested in connectionpool, needs to preserve case
        hdict = {
            "Content-Length": "0",
            "Content-type": "text/plain",
            "Server": "Hypercorn/1.2.3",
        }
        h = dict(HTTPHeaderDict(hdict).items())
        assert hdict == h
        assert hdict == dict(HTTPHeaderDict(hdict))

    def test_dict_conversion(self, d: HTTPHeaderDict) -> None:
        # Also tested in connectionpool, needs to preserve case
        hdict = {
            "Content-Length": "0",
            "Content-type": "text/plain",
            "Server": "Hypercorn/1.2.3",
        }
        h = dict(HTTPHeaderDict(hdict).items())
        <AssertPlaceHolder>
        assert hdict == dict(HTTPHeaderDict(hdict))

    def items(self) -> HTTPHeaderDictItemView:  # type: ignore[override]
        return HTTPHeaderDictItemView(self)


    def test_many_urls(self) -> None:
        urls = [
            "http://localhost:8081/foo",
            "http://www.google.com/mail",
            "http://localhost:8081/bar",
            "https://www.google.com/",
            "https://www.google.com/mail",
            "http://yahoo.com",
            "http://bing.com",
            "http://yahoo.com/",
        ]

        connections = set()

        p = PoolManager(10)

        for url in urls:
            conn = p.connection_from_url(url)
            connections.add(conn)

        assert len(connections) == 5

    def test_many_urls(self) -> None:
        urls = [
            "http://localhost:8081/foo",
            "http://www.google.com/mail",
            "http://localhost:8081/bar",
            "https://www.google.com/",
            "https://www.google.com/mail",
            "http://yahoo.com",
            "http://bing.com",
            "http://yahoo.com/",
        ]

        connections = set()

        p = PoolManager(10)

        for url in urls:
            conn = p.connection_from_url(url)
            connections.add(conn)

        <AssertPlaceHolder>


    def test__is_legal_header_name(self) -> None:
        assert _is_legal_header_name(b"foo"), "foo"
        assert _is_legal_header_name(b"foo-bar"), "foo-bar"
        assert _is_legal_header_name(b"foo-bar-baz"), "foo-bar-baz"

        # A field name MUST NOT contain characters in the ranges 0x00-0x20,
        # 0x41-0x5a, or 0x7f-0xff (all ranges inclusive). [1]
        for i in range(0x00, 0x20):
            assert not _is_legal_header_name(
                f"foo{chr(i)}bar".encode()
            ), f"foo\\x{i}bar"
        for i in range(0x41, 0x5A):
            assert not _is_legal_header_name(
                f"foo{chr(i)}bar".encode()
            ), f"foo\\x{i}bar"
        for i in range(0x7F, 0xFF):
            assert not _is_legal_header_name(
                f"foo{chr(i)}bar".encode()
            ), f"foo\\x{i}bar"

        # This specifically excludes all non-visible ASCII characters, ASCII SP
        # (0x20), and uppercase characters ('A' to 'Z', ASCII 0x41 to 0x5a). [1]
        assert not _is_legal_header_name(b"foo bar"), "foo bar"
        assert not _is_legal_header_name(b"foo\x20bar"), "foo\\x20bar"
        assert not _is_legal_header_name(b"Foo-Bar"), "Foo-Bar"

        # With the exception of pseudo-header fields (Section 8.3), which have a
        # name that starts with a single colon, field names MUST NOT include a
        # colon (ASCII COLON, 0x3a). [1]
        assert not _is_legal_header_name(b":foo"), ":foo"
        assert not _is_legal_header_name(b"foo:bar"), "foo:bar"
        assert not _is_legal_header_name(b"foo:"), "foo:"

    def test__is_legal_header_name(self) -> None:
        assert _is_legal_header_name(b"foo"), "foo"
        assert _is_legal_header_name(b"foo-bar"), "foo-bar"
        assert _is_legal_header_name(b"foo-bar-baz"), "foo-bar-baz"

        # A field name MUST NOT contain characters in the ranges 0x00-0x20,
        # 0x41-0x5a, or 0x7f-0xff (all ranges inclusive). [1]
        for i in range(0x00, 0x20):
            assert not _is_legal_header_name(
                f"foo{chr(i)}bar".encode()
            ), f"foo\\x{i}bar"
        for i in range(0x41, 0x5A):
            assert not _is_legal_header_name(
                f"foo{chr(i)}bar".encode()
            ), f"foo\\x{i}bar"
        for i in range(0x7F, 0xFF):
            assert not _is_legal_header_name(
                f"foo{chr(i)}bar".encode()
            ), f"foo\\x{i}bar"

        # This specifically excludes all non-visible ASCII characters, ASCII SP
        # (0x20), and uppercase characters ('A' to 'Z', ASCII 0x41 to 0x5a). [1]
        assert not _is_legal_header_name(b"foo bar"), "foo bar"
        assert not _is_legal_header_name(b"foo\x20bar"), "foo\\x20bar"
        assert not _is_legal_header_name(b"Foo-Bar"), "Foo-Bar"

        # With the exception of pseudo-header fields (Section 8.3), which have a
        # name that starts with a single colon, field names MUST NOT include a
        # colon (ASCII COLON, 0x3a). [1]
        assert not _is_legal_header_name(b":foo"), ":foo"
        assert not _is_legal_header_name(b"foo:bar"), "foo:bar"
        <AssertPlaceHolder>

def _is_legal_header_name(name: bytes) -> bool:
    """
    "An implementation that validates fields according to the definitions in Sections
    5.1 and 5.5 of [HTTP] only needs an additional check that field names do not
    include uppercase characters." (https://httpwg.org/specs/rfc9113.html#n-field-validity)

    `http.client._is_legal_header_name` does not validate the field name according to the
    HTTP 1.1 spec, so we do that here, in addition to checking for uppercase characters.

    This does not allow for the `:` character in the header name, so should not
    be used to validate pseudo-headers.
    """
    return bool(RE_IS_LEGAL_HEADER_NAME.match(name))


    def test_pool_close_twice(self) -> None:
        pool = connection_from_url("http://google.com:80")

        # Populate with some connections
        conn1 = pool._get_conn()
        conn2 = pool._get_conn()
        pool._put_conn(conn1)
        pool._put_conn(conn2)

        pool.close()
        assert pool.pool is None

        try:
            pool.close()
        except AttributeError:
            pytest.fail("Pool of the ConnectionPool is None and has no attribute get.")

    def test_pool_close_twice(self) -> None:
        pool = connection_from_url("http://google.com:80")

        # Populate with some connections
        conn1 = pool._get_conn()
        conn2 = pool._get_conn()
        pool._put_conn(conn1)
        pool._put_conn(conn2)

        pool.close()
        <AssertPlaceHolder>

        try:
            pool.close()
        except AttributeError:
            pytest.fail("Pool of the ConnectionPool is None and has no attribute get.")


    def test_redirect_cross_host_remove_headers(self) -> None:
        with PoolManager() as http:
            r = http.request(
                "GET",
                f"{self.base_url}/redirect",
                fields={"target": f"{self.base_url_alt}/headers"},
                headers={
                    "Authorization": "foo",
                    "Proxy-Authorization": "bar",
                    "Cookie": "foo=bar",
                },
            )

            assert r.status == 200

            data = r.json()

            assert "Authorization" not in data
            assert "Proxy-Authorization" not in data
            assert "Cookie" not in data

            r = http.request(
                "GET",
                f"{self.base_url}/redirect",
                fields={"target": f"{self.base_url_alt}/headers"},
                headers={
                    "authorization": "foo",
                    "proxy-authorization": "baz",
                    "cookie": "foo=bar",
                },
            )

            assert r.status == 200

            data = r.json()

            assert "authorization" not in data
            assert "Authorization" not in data
            assert "proxy-authorization" not in data
            assert "Proxy-Authorization" not in data
            assert "cookie" not in data
            assert "Cookie" not in data

    def test_redirect_cross_host_remove_headers(self) -> None:
        with PoolManager() as http:
            r = http.request(
                "GET",
                f"{self.base_url}/redirect",
                fields={"target": f"{self.base_url_alt}/headers"},
                headers={
                    "Authorization": "foo",
                    "Proxy-Authorization": "bar",
                    "Cookie": "foo=bar",
                },
            )

            assert r.status == 200

            data = r.json()

            <AssertPlaceHolder>
            assert "Proxy-Authorization" not in data
            assert "Cookie" not in data

            r = http.request(
                "GET",
                f"{self.base_url}/redirect",
                fields={"target": f"{self.base_url_alt}/headers"},
                headers={
                    "authorization": "foo",
                    "proxy-authorization": "baz",
                    "cookie": "foo=bar",
                },
            )

            assert r.status == 200

            data = r.json()

            assert "authorization" not in data
            <AssertPlaceHolder>
            assert "proxy-authorization" not in data
            assert "Proxy-Authorization" not in data
            assert "cookie" not in data
            assert "Cookie" not in data


    @pytest.mark.timeout(PER_TEST_TIMEOUT)
    def test_tls_in_tls_tunnel(self) -> None:
        """
        Basic communication over the TLS in TLS tunnel.
        """
        self.start_destination_server()
        self.start_proxy_server()

        sock = socket.create_connection(
            (self.proxy_server.host, self.proxy_server.port)
        )
        with self.client_context.wrap_socket(
            sock, server_hostname="localhost"
        ) as proxy_sock:
            with SSLTransport(
                proxy_sock, self.client_context, server_hostname="localhost"
            ) as destination_sock:
                assert destination_sock.version() is not None
                destination_sock.send(sample_request())
                response = consume_socket(destination_sock)
                validate_response(response)

    @pytest.mark.timeout(PER_TEST_TIMEOUT)
    def test_tls_in_tls_tunnel(self) -> None:
        """
        Basic communication over the TLS in TLS tunnel.
        """
        self.start_destination_server()
        self.start_proxy_server()

        sock = socket.create_connection(
            (self.proxy_server.host, self.proxy_server.port)
        )
        with self.client_context.wrap_socket(
            sock, server_hostname="localhost"
        ) as proxy_sock:
            with SSLTransport(
                proxy_sock, self.client_context, server_hostname="localhost"
            ) as destination_sock:
                <AssertPlaceHolder>
                destination_sock.send(sample_request())
                response = consume_socket(destination_sock)
                validate_response(response)

    def version(self) -> str | None:
        return self.sslobj.version()


    def test_chunked_head_response_does_not_hang(self) -> None:
        self.start_response_handler(
            b"HTTP/1.1 200 OK\r\n"
            b"Transfer-Encoding: chunked\r\n"
            b"Content-type: text/plain\r\n"
            b"\r\n"
        )
        with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
            r = pool.request("HEAD", "/", timeout=LONG_TIMEOUT, preload_content=False)

            # stream will use the read_chunked method here.
            assert [] == list(r.stream())

    def test_chunked_head_response_does_not_hang(self) -> None:
        self.start_response_handler(
            b"HTTP/1.1 200 OK\r\n"
            b"Transfer-Encoding: chunked\r\n"
            b"Content-type: text/plain\r\n"
            b"\r\n"
        )
        with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
            r = pool.request("HEAD", "/", timeout=LONG_TIMEOUT, preload_content=False)

            # stream will use the read_chunked method here.
            <AssertPlaceHolder>


    def test_merge_pool_kwargs(self) -> None:
        """Assert _merge_pool_kwargs works in the happy case"""
        retries = retry.Retry(total=100)
        p = PoolManager(retries=retries)
        merged = p._merge_pool_kwargs({"new_key": "value"})
        assert {"retries": retries, "new_key": "value"} == merged

    def test_merge_pool_kwargs(self) -> None:
        """Assert _merge_pool_kwargs works in the happy case"""
        retries = retry.Retry(total=100)
        p = PoolManager(retries=retries)
        merged = p._merge_pool_kwargs({"new_key": "value"})
        <AssertPlaceHolder>


    def test_httplib_headers_case_insensitive(self) -> None:
        self.start_response_handler(
            b"HTTP/1.1 200 OK\r\n"
            b"Content-Length: 0\r\n"
            b"Content-type: text/plain\r\n"
            b"\r\n"
        )
        with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
            HEADERS = {"Content-Length": "0", "Content-type": "text/plain"}
            r = pool.request("GET", "/")
            assert HEADERS == dict(r.headers.items())  # to preserve case sensitivity

    def test_httplib_headers_case_insensitive(self) -> None:
        self.start_response_handler(
            b"HTTP/1.1 200 OK\r\n"
            b"Content-Length: 0\r\n"
            b"Content-type: text/plain\r\n"
            b"\r\n"
        )
        with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
            HEADERS = {"Content-Length": "0", "Content-type": "text/plain"}
            r = pool.request("GET", "/")
            <AssertPlaceHolder>


    def test_no_user_agent_header(self) -> None:
        """ConnectionPool can suppress sending a user agent header"""
        custom_ua = "I'm not a web scraper, what are you talking about?"
        with HTTPConnectionPool(self.host, self.port) as pool:
            # Suppress user agent in the request headers.
            no_ua_headers = {"User-Agent": SKIP_HEADER}
            r = pool.request("GET", "/headers", headers=no_ua_headers)
            request_headers = r.json()
            assert "User-Agent" not in request_headers
            assert no_ua_headers["User-Agent"] == SKIP_HEADER

            # Suppress user agent in the pool headers.
            pool.headers = no_ua_headers
            r = pool.request("GET", "/headers")
            request_headers = r.json()
            assert "User-Agent" not in request_headers
            assert no_ua_headers["User-Agent"] == SKIP_HEADER

            # Request headers override pool headers.
            pool_headers = {"User-Agent": custom_ua}
            pool.headers = pool_headers
            r = pool.request("GET", "/headers", headers=no_ua_headers)
            request_headers = r.json()
            assert "User-Agent" not in request_headers
            assert no_ua_headers["User-Agent"] == SKIP_HEADER
            assert pool_headers.get("User-Agent") == custom_ua

    def test_no_user_agent_header(self) -> None:
        """ConnectionPool can suppress sending a user agent header"""
        custom_ua = "I'm not a web scraper, what are you talking about?"
        with HTTPConnectionPool(self.host, self.port) as pool:
            # Suppress user agent in the request headers.
            no_ua_headers = {"User-Agent": SKIP_HEADER}
            r = pool.request("GET", "/headers", headers=no_ua_headers)
            request_headers = r.json()
            assert "User-Agent" not in request_headers
            <AssertPlaceHolder>

            # Suppress user agent in the pool headers.
            pool.headers = no_ua_headers
            r = pool.request("GET", "/headers")
            request_headers = r.json()
            assert "User-Agent" not in request_headers
            <AssertPlaceHolder>

            # Request headers override pool headers.
            pool_headers = {"User-Agent": custom_ua}
            pool.headers = pool_headers
            r = pool.request("GET", "/headers", headers=no_ua_headers)
            request_headers = r.json()
            assert "User-Agent" not in request_headers
            <AssertPlaceHolder>
            assert pool_headers.get("User-Agent") == custom_ua


    def test_request_chunked_is_deprecated(
        self,
    ) -> None:
        with HTTPConnectionPool(self.host, self.port) as pool:
            conn = pool._get_conn()

            with pytest.warns(DeprecationWarning) as w:
                conn.request_chunked("GET", "/headers")  # type: ignore[attr-defined]
            assert len(w) == 1 and str(w[0].message) == (
                "HTTPConnection.request_chunked() is deprecated and will be removed in urllib3 v2.1.0. "
                "Instead use HTTPConnection.request(..., chunked=True)."
            )

            resp = conn.getresponse()
            assert resp.status == 200
            assert resp.json()["Transfer-Encoding"] == "chunked"
            conn.close()

    def test_request_chunked_is_deprecated(
        self,
    ) -> None:
        with HTTPConnectionPool(self.host, self.port) as pool:
            conn = pool._get_conn()

            with pytest.warns(DeprecationWarning) as w:
                conn.request_chunked("GET", "/headers")  # type: ignore[attr-defined]
            assert len(w) == 1 and str(w[0].message) == (
                "HTTPConnection.request_chunked() is deprecated and will be removed in urllib3 v2.1.0. "
                "Instead use HTTPConnection.request(..., chunked=True)."
            )

            resp = conn.getresponse()
            <AssertPlaceHolder>
            assert resp.json()["Transfer-Encoding"] == "chunked"
            conn.close()


    def test_http_connection_from_url_case_insensitive(self) -> None:
        """Assert scheme case is ignored when pooling HTTP connections."""
        p = PoolManager()
        pool = p.connection_from_url("http://example.com/")
        other_pool = p.connection_from_url("HTTP://EXAMPLE.COM/")

        assert 1 == len(p.pools)
        assert pool is other_pool
        assert all(isinstance(key, PoolKey) for key in p.pools.keys())

    def test_http_connection_from_url_case_insensitive(self) -> None:
        """Assert scheme case is ignored when pooling HTTP connections."""
        p = PoolManager()
        pool = p.connection_from_url("http://example.com/")
        other_pool = p.connection_from_url("HTTP://EXAMPLE.COM/")

        <AssertPlaceHolder>
        assert pool is other_pool
        assert all(isinstance(key, PoolKey) for key in p.pools.keys())

    def connection_from_url(
        self, url: str, pool_kwargs: dict[str, typing.Any] | None = None
    ) -> HTTPConnectionPool:
        """
        Similar to :func:`urllib3.connectionpool.connection_from_url`.

        If ``pool_kwargs`` is not provided and a new pool needs to be
        constructed, ``self.connection_pool_kw`` is used to initialize
        the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``
        is provided, it is used instead. Note that if a new pool does not
        need to be created for the request, the provided ``pool_kwargs`` are
        not used.
        """
        u = parse_url(url)
        return self.connection_from_host(
            u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs
        )


    def test_empty_head_response_does_not_hang(self) -> None:
        self.start_response_handler(
            b"HTTP/1.1 200 OK\r\n"
            b"Content-Length: 256\r\n"
            b"Content-type: text/plain\r\n"
            b"\r\n"
        )
        with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
            r = pool.request("HEAD", "/", timeout=LONG_TIMEOUT, preload_content=False)

            # stream will use the read method here.
            assert [] == list(r.stream())

    def test_empty_head_response_does_not_hang(self) -> None:
        self.start_response_handler(
            b"HTTP/1.1 200 OK\r\n"
            b"Content-Length: 256\r\n"
            b"Content-type: text/plain\r\n"
            b"\r\n"
        )
        with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
            r = pool.request("HEAD", "/", timeout=LONG_TIMEOUT, preload_content=False)

            # stream will use the read method here.
            <AssertPlaceHolder>


    def test_default_user_agent_header(self) -> None:
        """ConnectionPool has a default user agent"""
        default_ua = _get_default_user_agent()
        custom_ua = "I'm not a web scraper, what are you talking about?"
        custom_ua2 = "Yet Another User Agent"
        with HTTPConnectionPool(self.host, self.port) as pool:
            # Use default user agent if no user agent was specified.
            r = pool.request("GET", "/headers")
            request_headers = r.json()
            assert request_headers.get("User-Agent") == _get_default_user_agent()

            # Prefer the request user agent over the default.
            headers = {"UsEr-AGENt": custom_ua}
            r = pool.request("GET", "/headers", headers=headers)
            request_headers = r.json()
            assert request_headers.get("User-Agent") == custom_ua

            # Do not modify pool headers when using the default user agent.
            pool_headers = {"foo": "bar"}
            pool.headers = pool_headers
            r = pool.request("GET", "/headers")
            request_headers = r.json()
            assert request_headers.get("User-Agent") == default_ua
            assert "User-Agent" not in pool_headers

            pool.headers.update({"User-Agent": custom_ua2})
            r = pool.request("GET", "/headers")
            request_headers = r.json()
            assert request_headers.get("User-Agent") == custom_ua2

    def test_default_user_agent_header(self) -> None:
        """ConnectionPool has a default user agent"""
        default_ua = _get_default_user_agent()
        custom_ua = "I'm not a web scraper, what are you talking about?"
        custom_ua2 = "Yet Another User Agent"
        with HTTPConnectionPool(self.host, self.port) as pool:
            # Use default user agent if no user agent was specified.
            r = pool.request("GET", "/headers")
            request_headers = r.json()
            <AssertPlaceHolder>

            # Prefer the request user agent over the default.
            headers = {"UsEr-AGENt": custom_ua}
            r = pool.request("GET", "/headers", headers=headers)
            request_headers = r.json()
            assert request_headers.get("User-Agent") == custom_ua

            # Do not modify pool headers when using the default user agent.
            pool_headers = {"foo": "bar"}
            pool.headers = pool_headers
            r = pool.request("GET", "/headers")
            request_headers = r.json()
            assert request_headers.get("User-Agent") == default_ua
            assert "User-Agent" not in pool_headers

            pool.headers.update({"User-Agent": custom_ua2})
            r = pool.request("GET", "/headers")
            request_headers = r.json()
            assert request_headers.get("User-Agent") == custom_ua2

def _get_default_user_agent() -> str:
    return f"python-urllib3/{__version__}"


    def test_encode_invalid_chars_none(self) -> None:
        assert _encode_invalid_chars(None, set()) is None

    def test_encode_invalid_chars_none(self) -> None:
        <AssertPlaceHolder>

def _encode_invalid_chars(
    component: str | None, allowed_chars: typing.Container[str]
) -> str | None:
    """Percent-encodes a URI component without reapplying
    onto an already percent-encoded component.
    """
    if component is None:
        return component

    component = to_str(component)

    # Normalize existing percent-encoded bytes.
    # Try to see if the component we're encoding is already percent-encoded
    # so we can skip all '%' characters but still encode all others.
    component, percent_encodings = _PERCENT_RE.subn(
        lambda match: match.group(0).upper(), component
    )

    uri_bytes = component.encode("utf-8", "surrogatepass")
    is_percent_encoded = percent_encodings == uri_bytes.count(b"%")
    encoded_component = bytearray()

    for i in range(0, len(uri_bytes)):
        # Will return a single character bytestring
        byte = uri_bytes[i : i + 1]
        byte_ord = ord(byte)
        if (is_percent_encoded and byte == b"%") or (
            byte_ord < 128 and byte.decode() in allowed_chars
        ):
            encoded_component += byte
            continue
        encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper()))

    return encoded_component.decode()


    def test_create(self) -> None:
        simple_field = RequestField("somename", "data")
        assert simple_field.render_headers() == "\r\n"
        filename_field = RequestField("somename", "data", filename="somefile.txt")
        assert filename_field.render_headers() == "\r\n"
        headers_field = RequestField(
            "somename", "data", headers={"Content-Length": "4"}
        )
        assert headers_field.render_headers() == "Content-Length: 4\r\n\r\n"

    def test_create(self) -> None:
        simple_field = RequestField("somename", "data")
        <AssertPlaceHolder>
        filename_field = RequestField("somename", "data", filename="somefile.txt")
        assert filename_field.render_headers() == "\r\n"
        headers_field = RequestField(
            "somename", "data", headers={"Content-Length": "4"}
        )
        assert headers_field.render_headers() == "Content-Length: 4\r\n\r\n"

    def render_headers(self) -> str:
        """
        Renders the headers for this request field.
        """
        lines = []

        sort_keys = ["Content-Disposition", "Content-Type", "Content-Location"]
        for sort_key in sort_keys:
            if self.headers.get(sort_key, False):
                lines.append(f"{sort_key}: {self.headers[sort_key]}")

        for header_name, header_value in self.headers.items():
            if header_name not in sort_keys:
                if header_value:
                    lines.append(f"{header_name}: {header_value}")

        lines.append("\r\n")
        return "\r\n".join(lines)


    def test_backoff_reset_after_redirect(self) -> None:
        retry = Retry(total=100, redirect=5, backoff_factor=0.2)
        retry = retry.increment(method="GET")
        retry = retry.increment(method="GET")
        assert retry.get_backoff_time() == 0.4
        redirect_response = HTTPResponse(status=302, headers={"location": "test"})
        retry = retry.increment(method="GET", response=redirect_response)
        assert retry.get_backoff_time() == 0
        retry = retry.increment(method="GET")
        retry = retry.increment(method="GET")
        assert retry.get_backoff_time() == 0.4

    def test_backoff_reset_after_redirect(self) -> None:
        retry = Retry(total=100, redirect=5, backoff_factor=0.2)
        retry = retry.increment(method="GET")
        retry = retry.increment(method="GET")
        <AssertPlaceHolder>.4
        redirect_response = HTTPResponse(status=302, headers={"location": "test"})
        retry = retry.increment(method="GET", response=redirect_response)
        <AssertPlaceHolder>
        retry = retry.increment(method="GET")
        retry = retry.increment(method="GET")
        <AssertPlaceHolder>.4

    def get_backoff_time(self) -> float:
        """Formula for computing the current backoff

        :rtype: float
        """
        # We want to consider only the last consecutive errors sequence (Ignore redirects).
        consecutive_errors_len = len(
            list(
                takewhile(lambda x: x.redirect_location is None, reversed(self.history))
            )
        )
        if consecutive_errors_len <= 1:
            return 0

        backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))
        if self.backoff_jitter != 0.0:
            backoff_value += random.random() * self.backoff_jitter
        return float(max(0, min(self.backoff_max, backoff_value)))


    def test_header_parsing_errors(self) -> None:
        hpe = HeaderParsingError([MessageDefect("defects")], "unparsed_data")

        assert "defects" in str(hpe)
        assert "unparsed_data" in str(hpe)

    def test_header_parsing_errors(self) -> None:
        hpe = HeaderParsingError([MessageDefect("defects")], "unparsed_data")

        assert "defects" in str(hpe)
        <AssertPlaceHolder>

class HeaderParsingError(HTTPError):
    """Raised by assert_header_parsing, but we convert it to a log.warning statement."""

    def __init__(
        self, defects: list[MessageDefect], unparsed_data: bytes | str | None
    ) -> None:
        message = f"{defects or 'Unknown'}, unparsed data: {unparsed_data!r}"
        super().__init__(message)


    def test_url_from_pool(self) -> None:
        with connection_from_url("http://google.com:80") as pool:
            path = "path?query=foo"
            assert f"http://google.com:80/{path}" == _url_from_pool(pool, path)

    def test_url_from_pool(self) -> None:
        with connection_from_url("http://google.com:80") as pool:
            path = "path?query=foo"
            <AssertPlaceHolder>

def _url_from_pool(
    pool: HTTPConnectionPool | HTTPSConnectionPool, path: str | None = None
) -> str:
    """Returns the URL from a given connection pool. This is mainly used for testing and logging."""
    return Url(scheme=pool.scheme, host=pool.host, port=pool.port, path=path).url


    def test_backoff_jitter(self) -> None:
        """Backoff with jitter is computed correctly"""
        max_backoff = 1
        jitter = 0.4
        retry = Retry(
            total=100,
            backoff_factor=0.2,
            backoff_max=max_backoff,
            backoff_jitter=jitter,
        )
        assert retry.get_backoff_time() == 0  # First request

        retry = retry.increment(method="GET")
        assert retry.get_backoff_time() == 0  # First retry

        retry = retry.increment(method="GET")
        assert retry.backoff_factor == 0.2
        assert retry.total == 98
        assert 0.4 <= retry.get_backoff_time() <= 0.8  # Start backoff

        retry = retry.increment(method="GET")
        assert 0.8 <= retry.get_backoff_time() <= max_backoff

        retry = retry.increment(method="GET")
        assert retry.get_backoff_time() == max_backoff

        retry = retry.increment(method="GET")
        assert retry.get_backoff_time() == max_backoff

    def test_backoff_jitter(self) -> None:
        """Backoff with jitter is computed correctly"""
        max_backoff = 1
        jitter = 0.4
        retry = Retry(
            total=100,
            backoff_factor=0.2,
            backoff_max=max_backoff,
            backoff_jitter=jitter,
        )
        assert retry.get_backoff_time() == 0  # First request

        retry = retry.increment(method="GET")
        assert retry.get_backoff_time() == 0  # First retry

        retry = retry.increment(method="GET")
        assert retry.backoff_factor == 0.2
        assert retry.total == 98
        assert 0.4 <= retry.get_backoff_time() <= 0.8  # Start backoff

        retry = retry.increment(method="GET")
        <AssertPlaceHolder>

        retry = retry.increment(method="GET")
        assert retry.get_backoff_time() == max_backoff

        retry = retry.increment(method="GET")
        assert retry.get_backoff_time() == max_backoff


    def test_merge_pool_kwargs_remove_key(self) -> None:
        """Assert keys can be removed with _merge_pool_kwargs"""
        p = PoolManager(retries=100)
        merged = p._merge_pool_kwargs({"retries": None})
        assert "retries" not in merged

    def test_merge_pool_kwargs_remove_key(self) -> None:
        """Assert keys can be removed with _merge_pool_kwargs"""
        p = PoolManager(retries=100)
        merged = p._merge_pool_kwargs({"retries": None})
        <AssertPlaceHolder>

    def _merge_pool_kwargs(
        self, override: dict[str, typing.Any] | None
    ) -> dict[str, typing.Any]:
        """
        Merge a dictionary of override values for self.connection_pool_kw.

        This does not modify self.connection_pool_kw and returns a new dict.
        Any keys in the override dictionary with a value of ``None`` are
        removed from the merged dictionary.
        """
        base_pool_kwargs = self.connection_pool_kw.copy()
        if override:
            for key, value in override.items():
                if value is None:
                    try:
                        del base_pool_kwargs[key]
                    except KeyError:
                        pass
                else:
                    base_pool_kwargs[key] = value
        return base_pool_kwargs


    def test_top_level_request_with_json_with_httpheaderdict(self) -> None:
        body = {"attribute": "value"}
        header = HTTPHeaderDict(cookie="foo, bar")
        with PoolManager(headers=header) as http:
            r = http.request(method="POST", url=f"{self.base_url}/echo_json", json=body)
            assert r.status == 200
            assert r.json() == body
            assert "application/json" in r.headers["Content-Type"].replace(
                " ", ""
            ).split(",")

    def test_top_level_request_with_json_with_httpheaderdict(self) -> None:
        body = {"attribute": "value"}
        header = HTTPHeaderDict(cookie="foo, bar")
        with PoolManager(headers=header) as http:
            r = http.request(method="POST", url=f"{self.base_url}/echo_json", json=body)
            assert r.status == 200
            <AssertPlaceHolder>
            assert "application/json" in r.headers["Content-Type"].replace(
                " ", ""
            ).split(",")


    @resolvesLocalhostFQDN()
    def test_same_url(self) -> None:
        # Convince ourselves that normally we don't get the same object
        conn1 = connection_from_url("http://localhost:8081/foo")
        conn2 = connection_from_url("http://localhost:8081/bar")

        assert conn1 != conn2

        # Now try again using the PoolManager
        p = PoolManager(1)

        conn1 = p.connection_from_url("http://localhost:8081/foo")
        conn2 = p.connection_from_url("http://localhost:8081/bar")

        assert conn1 == conn2

        # Ensure that FQDNs are handled separately from relative domains
        p = PoolManager(2)

        conn1 = p.connection_from_url("http://localhost.:8081/foo")
        conn2 = p.connection_from_url("http://localhost:8081/bar")

        assert conn1 != conn2

    @resolvesLocalhostFQDN()
    def test_same_url(self) -> None:
        # Convince ourselves that normally we don't get the same object
        conn1 = connection_from_url("http://localhost:8081/foo")
        conn2 = connection_from_url("http://localhost:8081/bar")

        <AssertPlaceHolder>

        # Now try again using the PoolManager
        p = PoolManager(1)

        conn1 = p.connection_from_url("http://localhost:8081/foo")
        conn2 = p.connection_from_url("http://localhost:8081/bar")

        assert conn1 == conn2

        # Ensure that FQDNs are handled separately from relative domains
        p = PoolManager(2)

        conn1 = p.connection_from_url("http://localhost.:8081/foo")
        conn2 = p.connection_from_url("http://localhost:8081/bar")

        <AssertPlaceHolder>


    def test_defaults_are_applied(self) -> None:
        """Test that modifying the default socket options works."""
        # This test needs to be here in order to be run. socket.create_connection actually tries
        # to connect to the host provided so we need a dummyserver to be running.
        with HTTPConnectionPool(self.host, self.port) as pool:
            # Get the HTTPConnection instance
            conn = pool._new_conn()
            try:
                # Update the default socket options
                assert conn.socket_options is not None
                conn.socket_options += [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]
                s = conn._new_conn()  # type: ignore[attr-defined]
                nagle_disabled = (
                    s.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) > 0
                )
                using_keepalive = (
                    s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) > 0
                )
                assert nagle_disabled
                assert using_keepalive
            finally:
                conn.close()
                s.close()

    def test_defaults_are_applied(self) -> None:
        """Test that modifying the default socket options works."""
        # This test needs to be here in order to be run. socket.create_connection actually tries
        # to connect to the host provided so we need a dummyserver to be running.
        with HTTPConnectionPool(self.host, self.port) as pool:
            # Get the HTTPConnection instance
            conn = pool._new_conn()
            try:
                # Update the default socket options
                <AssertPlaceHolder>
                conn.socket_options += [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]
                s = conn._new_conn()  # type: ignore[attr-defined]
                nagle_disabled = (
                    s.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) > 0
                )
                using_keepalive = (
                    s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) > 0
                )
                assert nagle_disabled
                assert using_keepalive
            finally:
                conn.close()
                s.close()

    def _new_conn(self) -> BaseHTTPConnection:
        """
        Return a fresh :class:`HTTPConnection`.
        """
        self.num_connections += 1
        log.debug(
            "Starting new HTTP connection (%d): %s:%s",
            self.num_connections,
            self.host,
            self.port or "80",
        )

        conn = self.ConnectionCls(
            host=self.host,
            port=self.port,
            timeout=self.timeout.connect_timeout,
            **self.conn_kw,
        )
        return conn


    def test_proxy_pooling_ext(self) -> None:
        with proxy_from_url(self.proxy_url) as http:
            hc1 = http.connection_from_url(self.http_url)
            hc2 = http.connection_from_host(self.http_host, self.http_port)
            hc3 = http.connection_from_url(self.http_url_alt)
            hc4 = http.connection_from_host(self.http_host_alt, self.http_port)
            assert hc1 == hc2
            assert hc2 == hc3
            assert hc3 == hc4

            sc1 = http.connection_from_url(self.https_url)
            sc2 = http.connection_from_host(
                self.https_host, self.https_port, scheme="https"
            )
            sc3 = http.connection_from_url(self.https_url_alt)
            sc4 = http.connection_from_host(
                self.https_host_alt, self.https_port, scheme="https"
            )
            assert sc1 == sc2
            assert sc2 != sc3
            assert sc3 == sc4

    def test_proxy_pooling_ext(self) -> None:
        with proxy_from_url(self.proxy_url) as http:
            hc1 = http.connection_from_url(self.http_url)
            hc2 = http.connection_from_host(self.http_host, self.http_port)
            hc3 = http.connection_from_url(self.http_url_alt)
            hc4 = http.connection_from_host(self.http_host_alt, self.http_port)
            assert hc1 == hc2
            assert hc2 == hc3
            assert hc3 == hc4

            sc1 = http.connection_from_url(self.https_url)
            sc2 = http.connection_from_host(
                self.https_host, self.https_port, scheme="https"
            )
            sc3 = http.connection_from_url(self.https_url_alt)
            sc4 = http.connection_from_host(
                self.https_host_alt, self.https_port, scheme="https"
            )
            <AssertPlaceHolder>
            assert sc2 != sc3
            assert sc3 == sc4

    def connection_from_host(
        self,
        host: str | None,
        port: int | None = None,
        scheme: str | None = "http",
        pool_kwargs: dict[str, typing.Any] | None = None,
    ) -> HTTPConnectionPool:
        if scheme == "https":
            return super().connection_from_host(
                host, port, scheme, pool_kwargs=pool_kwargs
            )

        return super().connection_from_host(
            self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs  # type: ignore[union-attr]
        )


    def test_contextmanager(self) -> None:
        with connection_from_url("http://google.com:80") as pool:
            # Populate with some connections
            conn1 = pool._get_conn()
            conn2 = pool._get_conn()
            conn3 = pool._get_conn()
            pool._put_conn(conn1)
            pool._put_conn(conn2)

            old_pool_queue = pool.pool

        assert pool.pool is None
        with pytest.raises(ClosedPoolError):
            pool._get_conn()

        pool._put_conn(conn3)
        with pytest.raises(ClosedPoolError):
            pool._get_conn()
        with pytest.raises(Empty):
            assert old_pool_queue is not None
            old_pool_queue.get(block=False)

    def test_contextmanager(self) -> None:
        with connection_from_url("http://google.com:80") as pool:
            # Populate with some connections
            conn1 = pool._get_conn()
            conn2 = pool._get_conn()
            conn3 = pool._get_conn()
            pool._put_conn(conn1)
            pool._put_conn(conn2)

            old_pool_queue = pool.pool

        <AssertPlaceHolder>
        with pytest.raises(ClosedPoolError):
            pool._get_conn()

        pool._put_conn(conn3)
        with pytest.raises(ClosedPoolError):
            pool._get_conn()
        with pytest.raises(Empty):
            assert old_pool_queue is not None
            old_pool_queue.get(block=False)

    def _get_conn(self, timeout: float | None = None) -> BaseHTTPConnection:
        """
        Get a connection. Will return a pooled connection if one is available.

        If no connections are available and :prop:`.block` is ``False``, then a
        fresh connection is returned.

        :param timeout:
            Seconds to wait before giving up and raising
            :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and
            :prop:`.block` is ``True``.
        """
        conn = None

        if self.pool is None:
            raise ClosedPoolError(self, "Pool is closed.")

        try:
            conn = self.pool.get(block=self.block, timeout=timeout)

        except AttributeError:  # self.pool is None
            raise ClosedPoolError(self, "Pool is closed.") from None  # Defensive:

        except queue.Empty:
            if self.block:
                raise EmptyPoolError(
                    self,
                    "Pool is empty and a new connection can't be opened due to blocking mode.",
                ) from None
            pass  # Oh well, we'll create a new connection then

        # If this is a persistent connection, check if it got disconnected
        if conn and is_connection_dropped(conn):
            log.debug("Resetting dropped connection: %s", self.host)
            conn.close()

        return conn or self._new_conn()


    def test_has_ipv6_disabled_on_compile(self) -> None:
        with patch("socket.has_ipv6", False):
            assert not _has_ipv6("::1")

    def test_has_ipv6_disabled_on_compile(self) -> None:
        with patch("socket.has_ipv6", False):
            <AssertPlaceHolder>