Skip to content

Commit ea1b473

Browse files
author
kennyromanov
committed
fix: The HttpX HTTP client has been removed from the library; The HTTP requests and the timeouts have been fixed
1 parent 872d910 commit ea1b473

4 files changed

Lines changed: 85 additions & 40 deletions

File tree

‎setup.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
setup(
77
name="whatsapp-api-client-python",
8-
version="0.0.54",
8+
version="0.0.55",
99
description=(
1010
"This library helps you easily create"
1111
" a Python application with WhatsApp API."
@@ -41,6 +41,6 @@
4141
" (CC BY-ND 4.0)"
4242
),
4343
install_requires=["requests==2.34.2", "aiofiles>=24.1.0", "aiogram>=3.28.2", "aiohttp>=3.13.5"],
44-
extras_require={"voip": ["aiortc>=1.15,<2", "httpx>=0.28,<1", "websockets>=16,<17"]},
44+
extras_require={"voip": ["aiortc>=1.15,<2", "websockets>=16,<17"]},
4545
python_requires=">=3.10"
4646
)

‎tests/test_voip.py‎

Lines changed: 58 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22

33
import asyncio
44
import json
5+
from types import SimpleNamespace
56

6-
import httpx
7+
from aiohttp import web
8+
from aiohttp.test_utils import TestServer
79
import pytest
810

911
from whatsapp_api_client_python.API import GreenAPI, GreenAPIError
@@ -147,9 +149,9 @@ async def request(self, method, url, **kwargs):
147149
timeline.append(("REST", endpoint))
148150

149151
if endpoint == "callsGetIceServers":
150-
return httpx.Response(200, json=[])
152+
return SimpleNamespace(status_code=200, text="[]")
151153

152-
return httpx.Response(204)
154+
return SimpleNamespace(status_code=204, text="")
153155

154156
async def unexpected_request(*args, **kwargs):
155157
raise AssertionError("VoIP must not use the common requestAsync policy")
@@ -391,7 +393,31 @@ def __init__(self, status, body=""):
391393

392394
async def request(self, method, url, **kwargs):
393395
self.requests.append((method, url, kwargs))
394-
return httpx.Response(self.status, text=self.body)
396+
return SimpleNamespace(status_code=self.status, text=self.body)
397+
398+
399+
@pytest.mark.parametrize(
400+
("name_field", "expected"),
401+
[({"name": "Alice"}, "Alice"), ({"name": ""}, ""), ({"name": None}, None), ({}, None)],
402+
)
403+
@pytest.mark.asyncio
404+
async def test_call_name_preserves_empty_and_missing_values(harness, name_field, expected):
405+
payload = {"state": "inc-call", "info": {"id": "call-1", "wid": "200@lid", **name_field}}
406+
api = GreenAPI("123", "secret")
407+
api.voip._transport = StaticTransport(200, json.dumps(payload))
408+
409+
assert (await api.voip.getStateAsync()).info.name == expected
410+
411+
calls, socket, _, _, _ = harness
412+
incoming = []
413+
calls.on("incoming_call", incoming.append)
414+
await socket.emit("message", {"type": "state", "state": payload})
415+
416+
assert calls.state.info.name == expected
417+
assert len(incoming) == 1
418+
assert incoming[0].wid == "200@lid"
419+
assert incoming[0].name == expected
420+
await calls.closeAsync()
395421

396422

397423
@pytest.mark.parametrize("raise_errors", [False, True])
@@ -404,7 +430,8 @@ async def test_voip_rest_accepts_200_and_204_independently_of_sdk_policy(raise_e
404430
assert (await api.voip.getStateAsync()).state == "idle"
405431

406432
assert transport.requests[0] == (
407-
"GET", "https://example.test/waInstance123/callsState/secret", {},
433+
"GET", "https://example.test/waInstance123/callsState/secret",
434+
{"headers": {"User-Agent": "GREEN-API_SDK_PY/1.0"}},
408435
)
409436

410437
transport.status, transport.body = 204, ""
@@ -413,13 +440,14 @@ async def test_voip_rest_accepts_200_and_204_independently_of_sdk_policy(raise_e
413440

414441
assert transport.requests[-1] == (
415442
"POST", "https://example.test/waInstance123/callsDial/secret",
416-
{"headers": {"Content-Type": "application/json"}, "json": {"chatId": "79991234567@c.us"}},
443+
{"headers": {"User-Agent": "GREEN-API_SDK_PY/1.0", "Content-Type": "application/json"},
444+
"json": {"chatId": "79991234567@c.us"}},
417445
)
418446

419447
for command in (api.voip.acceptAsync, api.voip.rejectAsync, api.voip.hangUpAsync):
420448
await command()
421449
assert transport.requests[-1][0] == "POST"
422-
assert transport.requests[-1][2] == {}
450+
assert transport.requests[-1][2] == {"headers": {"User-Agent": "GREEN-API_SDK_PY/1.0"}}
423451

424452

425453
@pytest.mark.parametrize("raise_errors", [False, True])
@@ -462,32 +490,37 @@ def test_common_http_handler_still_rejects_204(caplog):
462490

463491

464492
@pytest.mark.asyncio
465-
async def test_voip_uses_httpx_transport_for_204_without_post_body(monkeypatch):
466-
api = GreenAPI("123", "secret", raise_errors=True, host="https://example.test")
493+
async def test_voip_uses_aiohttp_for_204_without_post_body():
467494
requests = []
468495

469-
def handle(request):
470-
requests.append(request)
471-
return httpx.Response(204)
496+
async def handle(request):
497+
requests.append((request.path, request.headers, await request.read()))
472498

473-
real_client = httpx.AsyncClient
499+
if request.path.endswith("/callsReject/secret"):
500+
return web.Response(status=302, headers={"Location": "/redirected"})
474501

475-
monkeypatch.setattr(
476-
httpx, "AsyncClient",
477-
lambda: real_client(transport=httpx.MockTransport(handle)),
478-
)
502+
return web.Response(status=204)
479503

480-
await api.voip.acceptAsync()
481-
await api.voip.dialAsync("79991234567")
504+
app = web.Application()
505+
app.router.add_post("/{tail:.*}", handle)
482506

483-
assert requests[0].url.path == "/waInstance123/callsAccept/secret"
484-
assert requests[0].content == b""
507+
async with TestServer(app) as server:
508+
api = GreenAPI("123", "secret", raise_errors=True, host=str(server.make_url("/")))
485509

486-
assert "content-type" not in requests[0].headers
510+
await api.voip.acceptAsync()
511+
await api.voip.dialAsync("79991234567")
487512

488-
assert requests[1].url.path == "/waInstance123/callsDial/secret"
489-
assert requests[1].headers["content-type"] == "application/json"
490-
assert json.loads(requests[1].content) == {"chatId": "79991234567@c.us"}
513+
with pytest.raises(RuntimeError, match="callsReject failed: 302"):
514+
await api.voip.rejectAsync()
515+
516+
assert requests[0][0] == "/waInstance123/callsAccept/secret"
517+
assert requests[0][2] == b""
518+
assert requests[0][1]["User-Agent"] == "GREEN-API_SDK_PY/1.0"
519+
assert "Content-Type" not in requests[0][1]
520+
assert requests[1][0] == "/waInstance123/callsDial/secret"
521+
assert requests[1][1]["Content-Type"] == "application/json"
522+
assert json.loads(requests[1][2]) == {"chatId": "79991234567@c.us"}
523+
assert len(requests) == 3
491524

492525

493526
@pytest.mark.asyncio

‎whatsapp_api_client_python/tools/voip/calls.py‎

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
from typing import Literal, Mapping
99
from urllib.parse import urlsplit, urlunsplit
1010

11+
import aiohttp
12+
1113
from .audio import AudioFactory, CallAudio
1214
from .signaling import ReconnectingSocket
1315

@@ -27,7 +29,7 @@
2729
class CallInfo:
2830
id: str
2931
wid: str
30-
name: str
32+
name: str | None
3133

3234

3335
@dataclass(frozen=True)
@@ -41,7 +43,7 @@ def call_state_from_json(value: Mapping) -> CallState:
4143
info = value.get("info")
4244

4345
if isinstance(info, dict):
44-
info = CallInfo(id=info["id"], wid=info["wid"], name=info["name"])
46+
info = CallInfo(id=info["id"], wid=info["wid"], name=info.get("name"))
4547

4648
else:
4749
info = None
@@ -72,26 +74,36 @@ def websocketUrl(self) -> str:
7274
return urlunsplit((scheme, host.netloc, path, "", ""))
7375

7476
async def _request(self, method: str, endpoint: str, payload=_MISSING):
75-
kwargs = {}
77+
kwargs = {"headers": {"User-Agent": "GREEN-API_SDK_PY/1.0"}}
7678

7779
if payload is not _MISSING:
78-
kwargs = {"headers": {"Content-Type": "application/json"}, "json": payload}
80+
kwargs["headers"]["Content-Type"] = "application/json"
81+
kwargs["json"] = payload
7982

8083
if self._transport is None:
81-
import httpx
82-
83-
async with httpx.AsyncClient() as transport:
84-
response = await transport.request(method, self._url(endpoint), **kwargs)
84+
timeout = aiohttp.ClientTimeout(total=None, connect=5, sock_read=5)
85+
86+
async with aiohttp.ClientSession(
87+
timeout=timeout, raise_for_status=False, trust_env=True,
88+
skip_auto_headers={"Content-Type"},
89+
) as transport:
90+
async with transport.request(
91+
method, self._url(endpoint), allow_redirects=False, **kwargs
92+
) as response:
93+
status_code = response.status
94+
body = await response.text()
8595
else:
8696
response = await self._transport.request(method, self._url(endpoint), **kwargs)
97+
status_code = response.status_code
98+
body = response.text
8799

88-
if not 200 <= response.status_code < 300:
89-
raise RuntimeError(f"{endpoint} failed: {response.status_code} {response.text}")
100+
if not 200 <= status_code < 300:
101+
raise RuntimeError(f"{endpoint} failed: {status_code} {body}")
90102

91-
if response.status_code == 204 or not response.text:
103+
if status_code == 204 or not body:
92104
return None
93105

94-
return json.loads(response.text)
106+
return json.loads(body)
95107

96108
async def getStateAsync(self) -> CallState:
97109
return call_state_from_json(await self._request("GET", "callsState"))

‎whatsapp_api_client_python/tools/voip/signaling.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
INITIAL_BACKOFF_MS = 500
1212

13-
MAX_BACKOFF_MS = 10 * 000
13+
MAX_BACKOFF_MS = 10 * 1000
1414

1515
PERMANENT_CLOSE_MIN = 4000
1616

0 commit comments

Comments
 (0)