test_http_client.py
1 # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai> 2 # 3 # SPDX-License-Identifier: Apache-2.0 4 5 import httpx 6 import pytest 7 8 from haystack.utils.http_client import init_http_client 9 10 11 def test_init_http_client(): 12 # test without any params 13 http_client = init_http_client() 14 assert http_client is None 15 16 # test client is initialized with http_client_kwargs 17 http_client = init_http_client(http_client_kwargs={"base_url": "https://example.com"}) 18 assert http_client is not None 19 assert isinstance(http_client, httpx.Client) 20 assert http_client.base_url == "https://example.com" 21 22 23 def test_init_http_client_async(): 24 # test without any params 25 http_async_client = init_http_client(async_client=True) 26 assert http_async_client is None 27 28 # test async client is initialized with http_client_kwargs 29 http_async_client = init_http_client(http_client_kwargs={"base_url": "https://example.com"}, async_client=True) 30 assert http_async_client is not None 31 assert isinstance(http_async_client, httpx.AsyncClient) 32 assert http_async_client.base_url == "https://example.com" 33 34 35 def test_http_client_kwargs_type_validation(): 36 # test http_client_kwargs is not a dictionary 37 with pytest.raises(TypeError, match="The parameter 'http_client_kwargs' must be a dictionary."): 38 init_http_client(http_client_kwargs="invalid") 39 40 41 def test_http_client_kwargs_with_invalid_params(): 42 # test http_client_kwargs with invalid keys 43 with pytest.raises(TypeError, match="unexpected keyword argument"): 44 init_http_client(http_client_kwargs={"invalid_key": "invalid"}) 45 46 47 def test_init_http_client_with_dict_limits(): 48 """Test that dict limits are converted to httpx.Limits objects without AttributeError.""" 49 http_client_kwargs = {"limits": {"max_connections": 100, "max_keepalive_connections": 20}} 50 51 # This should not raise AttributeError: 'dict' object has no attribute 'max_connections' 52 client = init_http_client(http_client_kwargs=http_client_kwargs, async_client=False) 53 assert client is not None 54 assert isinstance(client, httpx.Client) 55 56 client.close()