Skip to content

Commit 067123b

Browse files
nesitorolethanh
authored andcommitted
Fix: Apply fixes on tests
1 parent b3cd3fa commit 067123b

File tree

15 files changed

+52
-44
lines changed

15 files changed

+52
-44
lines changed

src/aleph/vm/conf.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ class Settings(BaseSettings):
168168
default=True,
169169
description="Enable IPv6 forwarding on the host. Required for IPv6 connectivity in VMs.",
170170
)
171-
NFTABLES_CHAIN_PREFIX = "aleph"
171+
NFTABLES_CHAIN_PREFIX: str = "aleph"
172172
USE_NDP_PROXY: bool = Field(
173173
default=True,
174174
description="Use the Neighbor Discovery Protocol Proxy to respond to Router Solicitation for instances on IPv6",
@@ -179,16 +179,16 @@ class Settings(BaseSettings):
179179
description="Method used to resolve the dns server if DNS_NAMESERVERS is not present.",
180180
)
181181
DNS_NAMESERVERS: list[str] | None = None
182-
DNS_NAMESERVERS_IPV4: list[str] | None
183-
DNS_NAMESERVERS_IPV6: list[str] | None
182+
DNS_NAMESERVERS_IPV4: list[str] | None = None
183+
DNS_NAMESERVERS_IPV6: list[str] | None = None
184184

185185
FIRECRACKER_PATH: Path = Path("/opt/firecracker/firecracker")
186186
JAILER_PATH: Path = Path("/opt/firecracker/jailer")
187187
SEV_CTL_PATH: Path = Path("/opt/sevctl")
188188
LINUX_PATH: Path = Path("/opt/firecracker/vmlinux.bin")
189189
INIT_TIMEOUT: float = 20.0
190190

191-
CONNECTOR_URL = Url("http://localhost:4021")
191+
CONNECTOR_URL: HttpUrl = HttpUrl("http://localhost:4021")
192192

193193
CACHE_ROOT: Path = Path("/var/cache/aleph/vm")
194194
MESSAGE_CACHE: Path | None = Field(
@@ -311,8 +311,10 @@ class Settings(BaseSettings):
311311
description="Identifier used for the 'fake instance' message defined in "
312312
"examples/instance_message_from_aleph.json",
313313
)
314-
FAKE_INSTANCE_MESSAGE = Path(abspath(join(__file__, "../../../../examples/instance_message_from_aleph.json")))
315-
FAKE_INSTANCE_QEMU_MESSAGE = Path(abspath(join(__file__, "../../../../examples/qemu_message_from_aleph.json")))
314+
FAKE_INSTANCE_MESSAGE: Path = Path(abspath(join(__file__, "../../../../examples/instance_message_from_aleph.json")))
315+
FAKE_INSTANCE_QEMU_MESSAGE: Path = Path(
316+
abspath(join(__file__, "../../../../examples/qemu_message_from_aleph.json"))
317+
)
316318

317319
CHECK_FASTAPI_VM_ID: str = "63faf8b5db1cf8d965e6a464a0cb8062af8e7df131729e48738342d956f29ace"
318320
LEGACY_CHECK_FASTAPI_VM_ID: str = "67705389842a0a1b95eaa408b009741027964edc805997475e95c505d642edd8"
@@ -348,7 +350,7 @@ def check(self):
348350
assert isfile(self.JAILER_PATH), f"File not found {self.JAILER_PATH}"
349351
assert isfile(self.LINUX_PATH), f"File not found {self.LINUX_PATH}"
350352
assert self.NETWORK_INTERFACE, "Network interface is not specified"
351-
assert self.CONNECTOR_URL.startswith("http://") or self.CONNECTOR_URL.startswith("https://")
353+
assert str(self.CONNECTOR_URL).startswith("http://") or str(self.CONNECTOR_URL).startswith("https://")
352354
if self.ALLOW_VM_NETWORKING:
353355
assert exists(
354356
f"/sys/class/net/{self.NETWORK_INTERFACE}"

src/aleph/vm/controllers/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
def configuration_from_file(path: Path):
2727
with open(path) as f:
2828
data = json.load(f)
29-
return Configuration.parse_obj(data)
29+
return Configuration.model_validate(data)
3030

3131

3232
def parse_args(args):

src/aleph/vm/hypervisors/firecracker/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from pathlib import Path
22

3-
from pydantic import BaseModel, ConfigDict, Field, PositiveInt
3+
from pydantic import BaseModel, ConfigDict, PositiveInt
44

55
VSOCK_PATH = "/tmp/v.sock"
66

src/aleph/vm/hypervisors/firecracker/microvm.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ async def save_configuration_file(self, config: FirecrackerConfig) -> Path:
192192
if not self.use_jailer
193193
else open(f"{self.jailer_path}/tmp/config.json", "wb")
194194
) as config_file:
195-
config_file.write(config.json(by_alias=True, exclude_none=True, indent=4).encode())
195+
config_file.write(config.model_dump_json(by_alias=True, exclude_none=True, indent=4).encode())
196196
config_file.flush()
197197
config_file_path = Path(config_file.name)
198198
config_file_path.chmod(0o644)

src/aleph/vm/models.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ def prepare_gpus(self, available_gpus: list[GpuDevice]) -> None:
226226
gpus: list[HostGPU] = []
227227
if self.message.requirements and self.message.requirements.gpu:
228228
for gpu in self.message.requirements.gpu:
229-
gpu = GpuProperties.parse_obj(gpu)
229+
gpu = GpuProperties.model_validate(gpu)
230230
for available_gpu in available_gpus:
231231
if available_gpu.device_id == gpu.device_id:
232232
gpus.append(
@@ -453,8 +453,8 @@ async def save(self):
453453
vcpus=self.vm.hardware_resources.vcpus,
454454
memory=self.vm.hardware_resources.memory,
455455
network_tap=self.vm.tap_interface.device_name if self.vm.tap_interface else "",
456-
message=self.message.json(),
457-
original_message=self.original.json(),
456+
message=self.message.model_dump_json(),
457+
original_message=self.original.model_dump_json(),
458458
persistent=self.persistent,
459459
)
460460
)
@@ -477,8 +477,8 @@ async def save(self):
477477
io_write_bytes=None,
478478
vcpus=self.vm.hardware_resources.vcpus,
479479
memory=self.vm.hardware_resources.memory,
480-
message=self.message.json(),
481-
original_message=self.original.json(),
480+
message=self.message.model_dump_json(),
481+
original_message=self.original.model_dump_json(),
482482
persistent=self.persistent,
483483
gpus=json.dumps(self.gpus, default=pydantic_encoder),
484484
)

src/aleph/vm/orchestrator/reactor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ async def trigger(self, message: AlephMessage):
6161
for subscription in listener.content.on.message:
6262
if subscription_matches(subscription, message):
6363
vm_hash = listener.item_hash
64-
event = message.json()
64+
event = message.model_dump_json()
6565
# Register the listener in the list of coroutines to run asynchronously:
6666
coroutines.append(run_code_on_event(vm_hash, event, self.pubsub, pool=self.pool))
6767
break

src/aleph/vm/orchestrator/run.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
import json
23
import logging
34
from typing import Any
45

src/aleph/vm/orchestrator/views/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ async def update_allocations(request: web.Request):
391391
allocation_lock = asyncio.Lock()
392392
try:
393393
data = await request.json()
394-
allocation = Allocation.parse_obj(data)
394+
allocation = Allocation.model_validate(data)
395395
except ValidationError as error:
396396
return web.json_response(text=error.json(), status=web.HTTPBadRequest.status_code)
397397

@@ -486,7 +486,7 @@ async def notify_allocation(request: web.Request):
486486
await update_aggregate_settings()
487487
try:
488488
data = await request.json()
489-
vm_notification = VMNotification.parse_obj(data)
489+
vm_notification = VMNotification.model_validate(data)
490490
except JSONDecodeError:
491491
return web.HTTPBadRequest(reason="Body is not valid JSON")
492492
except ValidationError as error:
@@ -631,7 +631,7 @@ async def operate_reserve_resources(request: web.Request, authenticated_sender:
631631
pool: VmPool = request.app["vm_pool"]
632632
try:
633633
data = await request.json()
634-
message = InstanceContent.parse_obj(data)
634+
message = InstanceContent.model_validate(data)
635635
except JSONDecodeError:
636636
return web.HTTPBadRequest(reason="Body is not valid JSON")
637637
except ValidationError as error:

src/aleph/vm/orchestrator/views/authentication.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from nacl.exceptions import BadSignatureError
2525
from pydantic import BaseModel, ValidationError, field_validator, model_validator
2626
from solathon.utils import verify_signature
27+
from typing_extensions import Self
2728

2829
from aleph.vm.conf import settings
2930

@@ -103,7 +104,7 @@ def payload_must_be_hex(cls, v: bytes) -> bytes:
103104
return bytes.fromhex(v.decode())
104105

105106
@model_validator(mode="after")
106-
def check_expiry(values) -> SignedPubKeyHeader:
107+
def check_expiry(values) -> Self:
107108
"""Check that the token has not expired"""
108109
payload = values.payload
109110
content = SignedPubKeyPayload.model_validate_json(payload)
@@ -112,7 +113,7 @@ def check_expiry(values) -> SignedPubKeyHeader:
112113
return values
113114

114115
@model_validator(mode="after")
115-
def check_signature(values) -> SignedPubKeyHeader:
116+
def check_signature(values) -> Self:
116117
"""Check that the signature is valid"""
117118
signature = values.signature
118119
payload = values.payload

src/aleph/vm/resources.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import subprocess
22
from enum import Enum
3+
from typing import Optional
34

45
from aleph_message.models import HashableModel
56
from pydantic import BaseModel, ConfigDict, Field
@@ -27,7 +28,7 @@ class GpuDevice(HashableModel):
2728
"""GPU properties."""
2829

2930
vendor: str = Field(description="GPU vendor name")
30-
model: str | None = Field(description="GPU model name on Aleph Network")
31+
model: Optional[str] = Field(description="GPU model name on Aleph Network", default=None)
3132
device_name: str = Field(description="GPU vendor card name")
3233
device_class: GpuDeviceClass = Field(
3334
description="GPU device class. Look at https://admin.pci-ids.ucw.cz/read/PD/03"

src/aleph/vm/storage.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ async def get_latest_amend(item_hash: str) -> str:
136136
if settings.FAKE_DATA_PROGRAM:
137137
return item_hash
138138
else:
139-
url = f"{settings.CONNECTOR_URL}/compute/latest_amend/{item_hash}"
139+
url = f"{settings.CONNECTOR_URL}compute/latest_amend/{item_hash}"
140140
async with aiohttp.ClientSession() as session:
141141
resp = await session.get(url)
142142
resp.raise_for_status()
@@ -154,7 +154,7 @@ async def get_message(ref: str) -> ProgramMessage | InstanceMessage:
154154
logger.debug("Using the fake data message")
155155
else:
156156
cache_path = (Path(settings.MESSAGE_CACHE) / ref).with_suffix(".json")
157-
url = f"{settings.CONNECTOR_URL}/download/message/{ref}"
157+
url = f"{settings.CONNECTOR_URL}download/message/{ref}"
158158
await download_file(url, cache_path)
159159

160160
with open(cache_path) as cache_file:
@@ -190,7 +190,7 @@ async def get_code_path(ref: str) -> Path:
190190
raise ValueError(msg)
191191

192192
cache_path = Path(settings.CODE_CACHE) / ref
193-
url = f"{settings.CONNECTOR_URL}/download/code/{ref}"
193+
url = f"{settings.CONNECTOR_URL}download/code/{ref}"
194194
await download_file(url, cache_path)
195195
return cache_path
196196

@@ -202,7 +202,7 @@ async def get_data_path(ref: str) -> Path:
202202
return Path(f"{data_dir}.zip")
203203

204204
cache_path = Path(settings.DATA_CACHE) / ref
205-
url = f"{settings.CONNECTOR_URL}/download/data/{ref}"
205+
url = f"{settings.CONNECTOR_URL}download/data/{ref}"
206206
await download_file(url, cache_path)
207207
return cache_path
208208

@@ -223,7 +223,7 @@ async def get_runtime_path(ref: str) -> Path:
223223
return Path(settings.FAKE_DATA_RUNTIME)
224224

225225
cache_path = Path(settings.RUNTIME_CACHE) / ref
226-
url = f"{settings.CONNECTOR_URL}/download/runtime/{ref}"
226+
url = f"{settings.CONNECTOR_URL}download/runtime/{ref}"
227227

228228
if not cache_path.is_file():
229229
# File does not exist, download it
@@ -241,7 +241,7 @@ async def get_rootfs_base_path(ref: ItemHash) -> Path:
241241
return Path(settings.FAKE_INSTANCE_BASE)
242242

243243
cache_path = Path(settings.RUNTIME_CACHE) / ref
244-
url = f"{settings.CONNECTOR_URL}/download/runtime/{ref}"
244+
url = f"{settings.CONNECTOR_URL}download/runtime/{ref}"
245245
await download_file(url, cache_path)
246246
await chown_to_jailman(cache_path)
247247
return cache_path

src/aleph/vm/utils/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@
2424

2525
def get_message_executable_content(message_dict: dict) -> ExecutableContent:
2626
try:
27-
return ProgramContent.parse_obj(message_dict)
27+
return ProgramContent.model_validate(message_dict)
2828
except ValueError:
29-
return InstanceContent.parse_obj(message_dict)
29+
return InstanceContent.model_validate(message_dict)
3030

3131

3232
def cors_allow_all(function):

tests/supervisor/test_checkpayment.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ async def compute_required_flow(executions):
6363
return 500 * len(executions)
6464

6565
mocker.patch("aleph.vm.orchestrator.tasks.compute_required_flow", compute_required_flow)
66-
message = InstanceContent.parse_obj(fake_instance_content)
66+
message = InstanceContent.model_validate(fake_instance_content)
6767

6868
hash = "decadecadecadecadecadecadecadecadecadecadecadecadecadecadecadeca"
6969

@@ -117,7 +117,7 @@ async def compute_required_flow(executions):
117117
return 500 * len(executions)
118118

119119
mocker.patch("aleph.vm.orchestrator.tasks.compute_required_flow", compute_required_flow)
120-
message = InstanceContent.parse_obj(fake_instance_content)
120+
message = InstanceContent.model_validate(fake_instance_content)
121121

122122
hash = "decadecadecadecadecadecadecadecadecadecadecadecadecadecadecadeca"
123123

@@ -157,7 +157,7 @@ async def test_not_enough_flow(mocker, fake_instance_content):
157157
mocker.patch("aleph.vm.orchestrator.tasks.get_stream", return_value=2, autospec=True)
158158
mocker.patch("aleph.vm.orchestrator.tasks.get_message_status", return_value=MessageStatus.PROCESSED)
159159
mocker.patch("aleph.vm.orchestrator.tasks.compute_required_flow", return_value=5)
160-
message = InstanceContent.parse_obj(fake_instance_content)
160+
message = InstanceContent.model_validate(fake_instance_content)
161161

162162
mocker.patch.object(VmExecution, "is_running", new=True)
163163
mocker.patch.object(VmExecution, "stop", new=mocker.AsyncMock(return_value=False))
@@ -201,7 +201,7 @@ async def get_stream(sender, receiver, chain):
201201
mocker.patch("aleph.vm.orchestrator.tasks.get_community_wallet_address", return_value=mock_community_wallet_address)
202202
mocker.patch("aleph.vm.orchestrator.tasks.get_message_status", return_value=MessageStatus.PROCESSED)
203203
mocker.patch("aleph.vm.orchestrator.tasks.compute_required_flow", return_value=5)
204-
message = InstanceContent.parse_obj(fake_instance_content)
204+
message = InstanceContent.model_validate(fake_instance_content)
205205

206206
mocker.patch.object(VmExecution, "is_running", new=True)
207207
mocker.patch.object(VmExecution, "stop", new=mocker.AsyncMock(return_value=False))

tests/supervisor/test_gpu_x_vga_support.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from aleph.vm.controllers.configuration import QemuGPU
66
from aleph.vm.hypervisors.qemu.qemuvm import QemuVM
7-
from aleph.vm.resources import GpuDevice, GpuDeviceClass, HostGPU
7+
from aleph.vm.resources import GpuDevice, GpuDeviceClass
88

99

1010
class TestGpuXVgaSupport:

tests/supervisor/test_views.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,17 @@ async def test_allocation_fails_on_invalid_item_hash(aiohttp_client):
2626
"/control/allocations", json={"persistent_vms": ["not-an-ItemHash"]}, headers={"X-Auth-Signature": "test"}
2727
)
2828
assert response.status == 400
29-
assert await response.json() == [
29+
response = await response.json()
30+
for error in response:
31+
error.pop("url", None)
32+
33+
assert response == [
3034
{
31-
"loc": [
32-
"persistent_vms",
33-
0,
34-
],
35-
"msg": "Could not determine hash type: 'not-an-ItemHash'",
36-
"type": "value_error.unknownhash",
35+
"loc": ["persistent_vms", 0],
36+
"msg": "Value error, Could not determine hash type: 'not-an-ItemHash'",
37+
"type": "value_error",
38+
"ctx": {"error": "Could not determine hash type: 'not-an-ItemHash'"},
39+
"input": "not-an-ItemHash",
3740
},
3841
]
3942

@@ -365,7 +368,7 @@ async def test_reserve_resources(aiohttp_client, mocker, mock_app_with_pool):
365368
"size_mib": 1000,
366369
},
367370
}
368-
InstanceContent.parse_obj(instance_content)
371+
InstanceContent.model_validate(instance_content)
369372

370373
response: web.Response = await client.post("/control/reserve_resources", json=instance_content)
371374
assert response.status == 200, await response.text()
@@ -479,7 +482,7 @@ async def test_reserve_resources_double_fail(aiohttp_client, mocker, mock_app_wi
479482
"size_mib": 1000,
480483
},
481484
}
482-
InstanceContent.parse_obj(instance_content)
485+
InstanceContent.model_validate(instance_content)
483486

484487
response: web.Response = await client.post("/control/reserve_resources", json=instance_content)
485488
assert response.status == 400, await response.text()

0 commit comments

Comments
 (0)