22
33import asyncio
44import json
5+ from types import SimpleNamespace
56
6- import httpx
7+ from aiohttp import web
8+ from aiohttp .test_utils import TestServer
79import pytest
810
911from 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
0 commit comments