diff --git a/src/aleph/services/ipfs/service.py b/src/aleph/services/ipfs/service.py index e085dda0..da49fb70 100644 --- a/src/aleph/services/ipfs/service.py +++ b/src/aleph/services/ipfs/service.py @@ -68,6 +68,9 @@ async def get_ipfs_size( dag_node = await asyncio.wait_for( self.ipfs_client.dag.get(hash), timeout=timeout ) + result = 0 + if isinstance(dag_node, str): + dag_node = json.loads(dag_node) if isinstance(dag_node, dict): if "Data" in dag_node and isinstance(dag_node["Data"], dict): # This is the common structure for UnixFS nodes after aioipfs parsing @@ -81,7 +84,11 @@ async def get_ipfs_size( "Tsize" in dag_node ): # Sometimes it might be at the top level directly result = dag_node["Tsize"] - elif "Links" in dag_node and isinstance(dag_node["Links"], list): + if ( + result == 0 + and "Links" in dag_node + and isinstance(dag_node["Links"], list) + ): total_size = 0 for link in dag_node["Links"]: # In case it's a link list, get the Tsize property if exists diff --git a/tests/services/test_ipfs_service.py b/tests/services/test_ipfs_service.py index 888b4dcd..fb626bd9 100644 --- a/tests/services/test_ipfs_service.py +++ b/tests/services/test_ipfs_service.py @@ -1,4 +1,5 @@ import asyncio +import json from unittest.mock import AsyncMock, patch import aioipfs @@ -133,6 +134,31 @@ async def test_get_ipfs_size_non_dict(): ipfs_client.block.stat.assert_called_once_with("test_hash") +@pytest.mark.asyncio +async def test_get_ipfs_size_json(): + """Test when dag.get returns a non-dictionary (bytes)""" + # Setup + mock_dag_get_data = { + "Data": {"/": {"bytes": "CAE"}}, + "Links": [ + {"Hash": {"/": "hash1"}, "Name": "test1", "Tsize": 12596071}, + {"Hash": {"/": "hash2"}, "Name": "test2", "Tsize": 20168090}, + ], + } + ipfs_client = AsyncMock() + ipfs_client.dag.get = AsyncMock(return_value=json.dumps(mock_dag_get_data)) + + service = IpfsService(ipfs_client=ipfs_client) + + # Execute + result = await service.get_ipfs_size("test_hash") + + # Assert + assert result == 32764161 + ipfs_client.dag.get.assert_called_once_with("test_hash") + ipfs_client.block.stat.assert_not_called() + + @pytest.mark.asyncio async def test_get_ipfs_size_api_error(): """Test handling of APIError"""