Skip to content

Commit 660762f

Browse files
committed
fix: lint tests were failing
- Updated all instances of **extra_fields to ensure proper handling of Optional dictionaries using `(extra_fields or {})` pattern. - Added proper return statements in `AlephHttpClient.get_message_status` to return parsed JSON data as a `MessageStatus` object. - Updated `Settings` class in `conf.py` to correct DNS resolvers type and simplify the `model_config` definition. - Refactored `parse_volume` to ensure correct handling of Mapping types and MachineVolume types, avoiding TypeErrors. - Improved field validation and model validation in `SignedPubKeyHeader` by using correct Pydantic v2 validation decorators and ensuring compatibility with the new model behavior. - Applied formatting and consistency fixes for `model_dump` usage and indentation improvements in test files.
1 parent a409433 commit 660762f

File tree

7 files changed

+35
-37
lines changed

7 files changed

+35
-37
lines changed

src/aleph/sdk/client/authenticated_http.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -710,7 +710,7 @@ async def _upload_file_native(
710710
item_hash=file_hash,
711711
mime_type=mime_type,
712712
time=time.time(),
713-
**extra_fields,
713+
**(extra_fields or {}),
714714
)
715715
message, _ = await self._storage_push_file_with_message(
716716
file_content=file_content,

src/aleph/sdk/client/http.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,3 +467,6 @@ async def get_message_status(self, item_hash: str) -> MessageStatus:
467467
if resp.status == HTTPNotFound.status_code:
468468
raise MessageNotFoundError(f"No such hash {item_hash}")
469469
resp.raise_for_status()
470+
471+
data = await resp.json()
472+
return MessageStatus(**data)

src/aleph/sdk/conf.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,10 @@
55
from shutil import which
66
from typing import ClassVar, Dict, Optional, Union
77

8-
from pydantic_settings import BaseSettings
9-
108
from aleph_message.models import Chain
119
from aleph_message.models.execution.environment import HypervisorType
1210
from pydantic import BaseModel, ConfigDict, Field
11+
from pydantic_settings import BaseSettings
1312

1413
from aleph.sdk.types import ChainInfo
1514

@@ -142,12 +141,10 @@ class Settings(BaseSettings):
142141
DNS_PROGRAM_DOMAIN: ClassVar[str] = "program.public.aleph.sh"
143142
DNS_INSTANCE_DOMAIN: ClassVar[str] = "instance.public.aleph.sh"
144143
DNS_STATIC_DOMAIN: ClassVar[str] = "static.public.aleph.sh"
145-
DNS_RESOLVERS: ClassVar[str] = ["9.9.9.9", "1.1.1.1"]
144+
DNS_RESOLVERS: ClassVar[list[str]] = ["9.9.9.9", "1.1.1.1"]
146145

147146
model_config = ConfigDict(
148-
env_prefix="ALEPH_",
149-
case_sensitive=False,
150-
env_file=".env"
147+
env_prefix="ALEPH_", case_sensitive=False, env_file=".env"
151148
)
152149

153150

@@ -159,7 +156,7 @@ class MainConfiguration(BaseModel):
159156
path: Path
160157
chain: Chain
161158

162-
model_config = ConfigDict(use_enum_values = True)
159+
model_config = ConfigDict(use_enum_values=True)
163160

164161

165162
# Settings singleton

src/aleph/sdk/utils.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,13 @@
2828
from uuid import UUID
2929
from zipfile import BadZipFile, ZipFile
3030

31-
from pydantic import BaseModel
32-
31+
import pydantic_core
3332
from aleph_message.models import ItemHash, MessageType
3433
from aleph_message.models.execution.program import Encoding
3534
from aleph_message.models.execution.volume import MachineVolume
3635
from cryptography.hazmat.backends import default_backend
3736
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
3837
from jwcrypto.jwa import JWA
39-
import pydantic_core
4038

4139
from aleph.sdk.conf import settings
4240
from aleph.sdk.types import GenericMessage, SEVInfo, SEVMeasurement
@@ -181,17 +179,18 @@ def extended_json_encoder(obj: Any) -> Any:
181179
def parse_volume(volume_dict: Union[Mapping, MachineVolume]) -> MachineVolume:
182180
# Python 3.9 does not support `isinstance(volume_dict, MachineVolume)`,
183181
# so we need to iterate over all types.
184-
if any(
185-
isinstance(volume_dict, volume_type) for volume_type in get_args(MachineVolume)
186-
):
187-
return volume_dict
188182
for volume_type in get_args(MachineVolume):
189-
try:
190-
return volume_type.model_validate(volume_dict)
191-
except ValueError:
192-
continue
193-
else:
194-
raise ValueError(f"Could not parse volume: {volume_dict}")
183+
if isinstance(volume_dict, volume_type):
184+
return volume_dict
185+
186+
if isinstance(volume_dict, Mapping):
187+
for volume_type in get_args(MachineVolume):
188+
try:
189+
return volume_type(**volume_dict)
190+
except (TypeError, ValueError):
191+
continue
192+
193+
raise ValueError("Invalid volume data, could not be parsed into a MachineVolume")
195194

196195

197196
def compute_sha256(s: str) -> str:

tests/unit/aleph_vm_authentication.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from eth_account.messages import encode_defunct
1414
from jwcrypto import jwk
1515
from jwcrypto.jwa import JWA
16-
from pydantic import BaseModel, ValidationError, model_validator, field_validator
16+
from pydantic import BaseModel, ValidationError, field_validator, model_validator
1717

1818
from aleph.sdk.utils import bytes_from_hex
1919

@@ -66,17 +66,15 @@ class SignedPubKeyHeader(BaseModel):
6666
@field_validator("signature")
6767
def signature_must_be_hex(cls, value: bytes) -> bytes:
6868
"""Convert the signature from hexadecimal to bytes"""
69-
7069
return bytes_from_hex(value.decode())
7170

7271
@field_validator("payload")
7372
def payload_must_be_hex(cls, value: bytes) -> bytes:
7473
"""Convert the payload from hexadecimal to bytes"""
75-
7674
return bytes_from_hex(value.decode())
7775

7876
@model_validator(mode="after")
79-
def check_expiry(cls, values) -> Dict[str, bytes]:
77+
def check_expiry(cls, values: "SignedPubKeyHeader") -> "SignedPubKeyHeader":
8078
"""Check that the token has not expired"""
8179
payload: bytes = values.payload
8280
content = SignedPubKeyPayload.model_validate_json(payload)
@@ -88,7 +86,7 @@ def check_expiry(cls, values) -> Dict[str, bytes]:
8886
return values
8987

9088
@model_validator(mode="after")
91-
def check_signature(cls, values: Dict[str, bytes]) -> Dict[str, bytes]:
89+
def check_signature(cls, values: "SignedPubKeyHeader") -> "SignedPubKeyHeader":
9290
"""Check that the signature is valid"""
9391
signature: bytes = values.signature
9492
payload: bytes = values.payload

tests/unit/conftest.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,9 @@ def json_post() -> dict:
135135
def raw_messages_response(aleph_messages) -> Callable[[int], Dict[str, Any]]:
136136
return lambda page: {
137137
"messages": (
138-
[message.model_dump() for message in aleph_messages] if int(page) == 1 else []
138+
[message.model_dump() for message in aleph_messages]
139+
if int(page) == 1
140+
else []
139141
),
140142
"pagination_item": "messages",
141143
"pagination_page": int(page),

tests/unit/test_utils.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
ProgramMessage,
1313
StoreMessage,
1414
)
15-
from aleph_message.models.execution.environment import MachineResources
1615
from aleph_message.models.execution.volume import (
1716
EphemeralVolume,
1817
ImmutableVolume,
@@ -115,17 +114,17 @@ def test_enum_as_str():
115114
(
116115
MessageType.aggregate,
117116
{
118-
'address': '0x1',
119-
'content': {
120-
'Hello': {
121-
'vcpus': 1,
122-
'memory': 1024,
123-
'seconds': 1,
124-
'published_ports': None,
117+
"address": "0x1",
118+
"content": {
119+
"Hello": {
120+
"vcpus": 1,
121+
"memory": 1024,
122+
"seconds": 1,
123+
"published_ports": None,
125124
},
126125
},
127-
'key': 'test',
128-
'time': 1.0,
126+
"key": "test",
127+
"time": 1.0,
129128
},
130129
),
131130
],

0 commit comments

Comments
 (0)