File size: 7,823 Bytes
a9e27c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
"""Outbound request, parsing, and resource ownership with no network access."""

import asyncio

import httpx
import pytest

from free_claude_code.core.web_tools import WebSearchResult
from free_claude_code.runtime.web_tools import client as web_client


def _httpx_clients(monkeypatch, handler):
    original_client = httpx.AsyncClient
    clients = []

    def construct(**kwargs):
        client = original_client(transport=httpx.MockTransport(handler), **kwargs)
        clients.append(client)
        return client

    monkeypatch.setattr(web_client.httpx, "AsyncClient", construct)
    return clients


@pytest.mark.asyncio
async def test_search_request_parsing_limit_and_client_closure(monkeypatch):
    def handle(request):
        assert str(request.url).startswith("https://lite.duckduckgo.com/lite/")
        assert request.url.params["q"] == "query & details"
        assert "free-claude-code/" in request.headers["User-Agent"]
        links = [
            f'<a href="/l/?uddg=https%3A%2F%2Fexample.com%2F{index}">Title {index}</a>'
            for index in range(12)
        ]
        links.insert(1, links[0])
        return httpx.Response(200, text="".join(links))

    clients = _httpx_clients(monkeypatch, handle)
    result = await web_client.HTTPWebToolsClient().search("query & details")
    assert result == [
        WebSearchResult(title=f"Title {index}", url=f"https://example.com/{index}")
        for index in range(10)
    ]
    assert len(clients) == 1 and clients[0].is_closed


@pytest.mark.asyncio
@pytest.mark.parametrize("cancel_during_body", [False, True])
async def test_search_cancellation_closes_client_and_open_response(
    monkeypatch, cancel_during_body
):
    entered = asyncio.Event()

    class Body(httpx.AsyncByteStream):
        closed = False

        async def __aiter__(self):
            entered.set()
            await asyncio.Event().wait()
            yield b""

        async def aclose(self):
            self.closed = True

    body = Body()

    async def handle(request):
        if not cancel_during_body:
            entered.set()
            await asyncio.Event().wait()
        return httpx.Response(200, stream=body)

    clients = _httpx_clients(monkeypatch, handle)
    task = asyncio.create_task(web_client.HTTPWebToolsClient().search("held"))
    try:
        await asyncio.wait_for(entered.wait(), 1)
        task.cancel()
        with pytest.raises(asyncio.CancelledError):
            await task
        assert len(clients) == 1 and clients[0].is_closed
        assert body.closed is cancel_during_body
    finally:
        if not task.done():
            task.cancel()
        await asyncio.gather(task, return_exceptions=True)


@pytest.mark.asyncio
async def test_fetch_cancellation_closes_response_session_and_connector(monkeypatch):
    from contextlib import asynccontextmanager
    from types import SimpleNamespace

    from free_claude_code.application.web_tools.ports import WebFetchEgressPolicy

    entered = asyncio.Event()
    response_closed, session_closed = [], []
    connectors = []
    original_connector = web_client.TCPConnector

    def connector(**kwargs):
        value = original_connector(**kwargs)
        connectors.append(value)
        return value

    async def chunks(_size):
        entered.set()
        await asyncio.Event().wait()
        yield b""

    @asynccontextmanager
    async def response(url, *, allow_redirects):
        assert url == "https://8.8.8.8/"
        assert allow_redirects is False
        try:
            yield SimpleNamespace(
                status=200,
                url=url,
                headers={},
                charset=None,
                raise_for_status=lambda: None,
                content=SimpleNamespace(iter_chunked=chunks),
            )
        finally:
            response_closed.append(True)

    @asynccontextmanager
    async def session(**kwargs):
        assert kwargs["connector"] is connectors[-1]
        try:
            yield SimpleNamespace(get=response)
        finally:
            session_closed.append(True)

    monkeypatch.setattr(web_client, "TCPConnector", connector)
    monkeypatch.setattr(web_client, "ClientSession", session)
    task = asyncio.create_task(
        web_client.HTTPWebToolsClient().fetch(
            "https://8.8.8.8/",
            egress=WebFetchEgressPolicy(False, frozenset({"https"})),
        )
    )
    try:
        await asyncio.wait_for(entered.wait(), 1)
        task.cancel()
        with pytest.raises(asyncio.CancelledError):
            await task
        assert response_closed == [True]
        assert session_closed == [True]
        assert len(connectors) == 1 and connectors[0].closed
    finally:
        if not task.done():
            task.cancel()
        await asyncio.gather(task, return_exceptions=True)


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("headers", "charset", "body", "expected_title", "expected_data"),
    [
        (
            {"content-type": "text/html"},
            None,
            b"<html><head><title>Test Title</title></head><body><p>Hello world</p></body></html>",
            "Test Title",
            "Hello world",
        ),
        (
            {},
            None,
            b"Plain utf-8 body",
            "https://8.8.8.8/",
            "Plain utf-8 body",
        ),
        (
            {"content-type": "text/plain; charset=iso-8859-1"},
            "iso-8859-1",
            b"caf\xe9",
            "https://8.8.8.8/",
            "café",
        ),
        (
            {"content-type": "text/plain; charset=bogus"},
            "bogus",
            b"fallback text",
            "https://8.8.8.8/",
            "fallback text",
        ),
        (
            {"content-type": "application/pdf"},
            None,
            b"%PDF-1.4\n%mangled\xff\xfe",
            "https://8.8.8.8/",
            "%PDF-1.4\n%mangled\ufffd\ufffd",
        ),
    ],
)
async def test_fetch_charset_and_content_type_handling(
    monkeypatch, headers, charset, body, expected_title, expected_data
):
    from contextlib import asynccontextmanager
    from types import SimpleNamespace

    from free_claude_code.application.web_tools.ports import WebFetchEgressPolicy

    async def chunks(_size):
        yield body

    def raise_for_unread_encoding():
        if charset:
            return charset
        raise RuntimeError("Cannot compute fallback encoding of a not yet read body")

    @asynccontextmanager
    async def response(url, *, allow_redirects):
        assert url == "https://8.8.8.8/"
        assert allow_redirects is False
        yield SimpleNamespace(
            status=200,
            url=url,
            headers=headers,
            charset=charset,
            get_encoding=raise_for_unread_encoding,
            raise_for_status=lambda: None,
            content=SimpleNamespace(iter_chunked=chunks),
        )

    @asynccontextmanager
    async def session(**kwargs):
        yield SimpleNamespace(get=response)

    monkeypatch.setattr(web_client, "ClientSession", session)
    result = await web_client.HTTPWebToolsClient().fetch(
        "https://8.8.8.8/",
        egress=WebFetchEgressPolicy(False, frozenset({"https"})),
    )
    assert result.url == "https://8.8.8.8/"
    assert result.title == expected_title
    assert result.media_type == "text/plain"
    assert result.data == expected_data


@pytest.mark.parametrize(
    ("charset", "expected"),
    [
        (None, "utf-8"),
        ("", "utf-8"),
        ("utf-8", "utf-8"),
        ("UTF-8", "utf-8"),
        ("iso-8859-1", "iso8859-1"),
        ("latin-1", "iso8859-1"),
        ("bogus", "utf-8"),
        ("invalid\x00null", "utf-8"),
    ],
)
def test_text_encoding(charset, expected):
    assert web_client._text_encoding(charset) == expected