Skip to content

Commit 69b9cf0

Browse files
committed
Mock test_download HTTP requests
1 parent 9ff6b5f commit 69b9cf0

File tree

2 files changed

+72
-17
lines changed

2 files changed

+72
-17
lines changed

tests/unit/conftest.py

Lines changed: 46 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import json
2+
from io import BytesIO
23
from pathlib import Path
34
from tempfile import NamedTemporaryFile
4-
from typing import Any, Callable, Dict, List
5+
from typing import Any, Callable, Dict, List, Optional, Union
56
from unittest.mock import AsyncMock, MagicMock
67

78
import pytest as pytest
@@ -195,19 +196,59 @@ def mock_session_with_post_success(
195196
return client
196197

197198

198-
def make_custom_mock_response(resp_json, status=200) -> MockResponse:
199+
import asyncio
200+
from functools import wraps
201+
202+
203+
def async_wrap(cls):
204+
class AsyncWrapper:
205+
def __init__(self, *args, **kwargs):
206+
self._instance = cls(*args, **kwargs)
207+
208+
def __getattr__(self, item):
209+
attr = getattr(self._instance, item)
210+
if callable(attr):
211+
212+
@wraps(attr)
213+
async def method(*args, **kwargs):
214+
loop = asyncio.get_running_loop()
215+
return await loop.run_in_executor(None, attr, *args, **kwargs)
216+
217+
return method
218+
return attr
219+
220+
return AsyncWrapper
221+
222+
223+
AsyncBytesIO = async_wrap(BytesIO)
224+
225+
226+
def make_custom_mock_response(
227+
resp: Union[Dict[str, Any], bytes], status=200
228+
) -> MockResponse:
199229
class CustomMockResponse(MockResponse):
230+
content: Optional[AsyncBytesIO]
231+
200232
async def json(self):
201-
return resp_json
233+
return resp
202234

203235
@property
204236
def status(self):
205237
return status
206238

207-
return CustomMockResponse(sync=True)
239+
mock = CustomMockResponse(sync=True)
240+
241+
try:
242+
mock.content = AsyncBytesIO(resp)
243+
except Exception as e:
244+
print(e)
245+
246+
return mock
208247

209248

210-
def make_mock_get_session(get_return_value: Dict[str, Any]) -> AlephHttpClient:
249+
def make_mock_get_session(
250+
get_return_value: Union[Dict[str, Any], bytes]
251+
) -> AlephHttpClient:
211252
class MockHttpSession(AsyncMock):
212253
def get(self, *_args, **_kwargs):
213254
return make_custom_mock_response(get_return_value)

tests/unit/test_download.py

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,20 @@
11
import tempfile
22
from pathlib import Path
3+
from unittest.mock import AsyncMock, patch
34

45
import pytest
56

67
from aleph.sdk import AlephHttpClient
7-
from aleph.sdk.conf import settings as sdk_settings
8+
9+
from .conftest import make_mock_get_session
10+
11+
12+
def make_mock_download_client(item_hash: str) -> AlephHttpClient:
13+
if item_hash == "QmeomffUNfmQy76CQGy9NdmqEnnHU9soCexBnGU3ezPHVH":
14+
return make_mock_get_session(b"test\n")
15+
if item_hash == "Qmdy5LaAL4eghxE7JD6Ah5o4PJGarjAV9st8az2k52i1vq":
16+
return make_mock_get_session(bytes(5817703))
17+
raise NotImplementedError
818

919

1020
@pytest.mark.parametrize(
@@ -16,21 +26,24 @@
1626
)
1727
@pytest.mark.asyncio
1828
async def test_download(file_hash: str, expected_size: int):
19-
async with AlephHttpClient(api_server=sdk_settings.API_HOST) as client:
20-
file_content = await client.download_file(file_hash) # File is 5B
21-
file_size = len(file_content)
22-
assert file_size == expected_size
29+
mock_download_client = make_mock_download_client(file_hash)
30+
async with mock_download_client:
31+
file_content = await mock_download_client.download_file(file_hash)
32+
file_size = len(file_content)
33+
assert file_size == expected_size
2334

2435

2536
@pytest.mark.asyncio
2637
async def test_download_to_file():
38+
file_hash = "QmeomffUNfmQy76CQGy9NdmqEnnHU9soCexBnGU3ezPHVH"
39+
mock_download_client = make_mock_download_client(file_hash)
2740
with tempfile.TemporaryDirectory() as temp_dir:
2841
temp_dir_path = Path(temp_dir)
2942
download_path = temp_dir_path / "test.txt"
3043

31-
async with AlephHttpClient(api_server=sdk_settings.API_HOST) as client:
32-
returned_path = await client.download_file_to_path(
33-
"QmeomffUNfmQy76CQGy9NdmqEnnHU9soCexBnGU3ezPHVH", str(download_path)
44+
async with mock_download_client:
45+
returned_path = await mock_download_client.download_file_to_path(
46+
file_hash, str(download_path)
3447
)
3548

3649
assert returned_path == download_path
@@ -48,7 +61,8 @@ async def test_download_to_file():
4861
)
4962
@pytest.mark.asyncio
5063
async def test_download_ipfs(file_hash: str, expected_size: int):
51-
async with AlephHttpClient(api_server=sdk_settings.API_HOST) as client:
52-
file_content = await client.download_file_ipfs(file_hash) # 5817703 B FILE
53-
file_size = len(file_content)
54-
assert file_size == expected_size
64+
mock_download_client = make_mock_download_client(file_hash)
65+
async with mock_download_client:
66+
file_content = await mock_download_client.download_file_ipfs(file_hash)
67+
file_size = len(file_content)
68+
assert file_size == expected_size

0 commit comments

Comments
 (0)