Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 0 additions & 10 deletions api/tests/unit_tests/.ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -251,16 +251,6 @@ extend-select = ["ANN401", "ARG"]
"libs/test_schedule_utils_enhanced.py" = ["S110"]
"libs/test_sendgrid_client.py" = ["ARG001", "TID251"]
"models/test_dataset_models.py" = ["ARG005"]
"oss/__mock/aliyun_oss.py" = ["ARG002"]
"oss/__mock/baidu_obs.py" = ["ARG002"]
"oss/__mock/base.py" = ["ARG002"]
"oss/__mock/tencent_cos.py" = ["ARG002"]
"oss/__mock/volcengine_tos.py" = ["ARG002"]
"oss/aliyun_oss/aliyun_oss/test_aliyun_oss.py" = ["ARG002"]
"oss/baidu_obs/test_baidu_obs.py" = ["ARG002"]
"oss/opendal/test_opendal.py" = ["ARG002"]
"oss/tencent_cos/test_tencent_cos.py" = ["ARG002"]
"oss/volcengine_tos/test_volcengine_tos.py" = ["ARG002"]
"services/agent/test_agent_observability_service.py" = ["ARG002", "ARG005"]
"services/agent/test_agent_services.py" = ["ARG001", "ARG002", "ARG003", "ARG005"]
"services/agent/test_prompt_mentions.py" = ["ARG005"]
Expand Down
43 changes: 14 additions & 29 deletions api/tests/unit_tests/oss/__mock/aliyun_oss.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import os
import posixpath
from collections.abc import Generator
from dataclasses import dataclass

import pytest
from oss2 import Bucket
Expand All @@ -16,30 +18,15 @@
)


@dataclass
class MockResponse:
def __init__(self, status, headers, request_id):
self.status = status
self.headers = headers
self.request_id = request_id
status: int
headers: dict[str, str]
request_id: str


class MockAliyunOssClass:
def __init__(
self,
auth,
endpoint,
bucket_name,
is_cname=False,
session=None,
connect_timeout=None,
app_name="",
enable_crc=True,
proxies=None,
region=None,
cloudbox_id=None,
is_path_style=False,
is_verify_object_strict=True,
):
def __init__(self, *_args: object, **_kwargs: object) -> None:
self.bucket_name = get_example_bucket()
self.key = posixpath.join(get_example_folder(), get_example_filename())
self.content = get_example_data()
Expand All @@ -53,39 +40,37 @@ def __init__(
"request_id",
)

def put_object(self, key, data, headers=None, progress_callback=None):
def put_object(self, key: str, data: bytes) -> PutObjectResult:
assert key == self.key
assert data == self.content
return PutObjectResult(self.resp)

def get_object(self, key, byte_range=None, headers=None, progress_callback=None, process=None, params=None):
def get_object(self, key: str) -> GetObjectResult:
assert key == self.key

response = object_response(self.content)
response.headers.update(self.resp.headers)
return GetObjectResult(OssResponse(response))

def get_object_to_file(
self, key, filename, byte_range=None, headers=None, progress_callback=None, process=None, params=None
):
def get_object_to_file(self, key: str, filename: str) -> None:
assert key == self.key
assert filename == self.filepath

def object_exists(self, key, headers=None):
def object_exists(self, key: str) -> bool:
assert key == self.key
return True

def delete_object(self, key, params=None, headers=None):
def delete_object(self, key: str) -> MockResponse:
assert key == self.key
self.resp.headers["x-oss-delete-marker"] = True
self.resp.headers["x-oss-delete-marker"] = "true"
return self.resp


MOCK = os.getenv("MOCK_SWITCH", "false").lower() == "true"


@pytest.fixture
def setup_aliyun_oss_mock(monkeypatch: pytest.MonkeyPatch):
def setup_aliyun_oss_mock(monkeypatch: pytest.MonkeyPatch) -> Generator[None]:
if MOCK:
monkeypatch.setattr(Bucket, "__init__", MockAliyunOssClass.__init__)
monkeypatch.setattr(Bucket, "put_object", MockAliyunOssClass.put_object)
Expand Down
15 changes: 8 additions & 7 deletions api/tests/unit_tests/oss/__mock/baidu_obs.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import base64
import hashlib
import os
from collections.abc import Generator
from io import BytesIO
from types import SimpleNamespace

Expand All @@ -16,36 +17,36 @@


class MockBaiduObsClass:
def __init__(self, config=None):
def __init__(self, *_args: object, **_kwargs: object) -> None:
self.bucket_name = get_example_bucket()
self.key = get_example_filename()
self.content = get_example_data()
self.filepath = get_example_filepath()

def put_object(self, bucket_name, key, data, content_length=None, content_md5=None, **kwargs):
def put_object(self, bucket_name: str, key: str, data: bytes, content_length: int, content_md5: bytes) -> None:
assert bucket_name == self.bucket_name
assert key == self.key
assert data == self.content
assert content_length == len(self.content)
expected_md5 = base64.standard_b64encode(hashlib.md5(self.content).digest())
assert content_md5 == expected_md5

def get_object(self, bucket_name, key, **kwargs):
def get_object(self, bucket_name: str, key: str) -> SimpleNamespace:
assert bucket_name == self.bucket_name
assert key == self.key
return SimpleNamespace(data=BytesIO(self.content))

def get_object_to_file(self, bucket_name, key, file_name, **kwargs):
def get_object_to_file(self, bucket_name: str, key: str, file_name: str) -> None:
assert bucket_name == self.bucket_name
assert key == self.key
assert file_name == self.filepath

def get_object_meta_data(self, bucket_name, key, **kwargs):
def get_object_meta_data(self, bucket_name: str, key: str) -> SimpleNamespace:
assert bucket_name == self.bucket_name
assert key == self.key
return SimpleNamespace(status=200)

def delete_object(self, bucket_name, key, **kwargs):
def delete_object(self, bucket_name: str, key: str) -> None:
assert bucket_name == self.bucket_name
assert key == self.key

Expand All @@ -54,7 +55,7 @@ def delete_object(self, bucket_name, key, **kwargs):


@pytest.fixture
def setup_baidu_obs_mock(monkeypatch: pytest.MonkeyPatch):
def setup_baidu_obs_mock(monkeypatch: pytest.MonkeyPatch) -> Generator[None]:
if MOCK:
monkeypatch.setattr(BosClient, "__init__", MockBaiduObsClass.__init__)
monkeypatch.setattr(BosClient, "put_object", MockBaiduObsClass.put_object)
Expand Down
14 changes: 7 additions & 7 deletions api/tests/unit_tests/oss/__mock/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,33 +46,33 @@ def get_example_filepath() -> str:

class BaseStorageTest:
@pytest.fixture(autouse=True)
def setup_method(self, *args, **kwargs):
def setup_method(self, *_args: object, **_kwargs: object) -> None:
"""Should be implemented in child classes to setup specific storage."""
self.storage: BaseStorage

def test_save(self):
def test_save(self) -> None:
"""Test saving data."""
self.storage.save(get_example_filename(), get_example_data())

def test_load_once(self):
def test_load_once(self) -> None:
"""Test loading data once."""
assert self.storage.load_once(get_example_filename()) == get_example_data()

def test_load_stream(self):
def test_load_stream(self) -> None:
"""Test loading data as a stream."""
generator = self.storage.load_stream(get_example_filename())
assert isinstance(generator, Generator)
assert next(generator) == get_example_data()
assert list(generator) == []

def test_download(self):
def test_download(self) -> None:
"""Test downloading data."""
self.storage.download(get_example_filename(), get_example_filepath())

def test_exists(self):
def test_exists(self) -> None:
"""Test checking if a file exists."""
assert self.storage.exists(get_example_filename())

def test_delete(self):
def test_delete(self) -> None:
"""Test deleting a file."""
self.storage.delete(get_example_filename())
13 changes: 7 additions & 6 deletions api/tests/unit_tests/oss/__mock/local.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import shutil
from collections.abc import Generator
from pathlib import Path
from unittest.mock import MagicMock, mock_open, patch

Expand All @@ -14,32 +15,32 @@


class MockLocalFSClass:
def write_bytes(self, data):
def write_bytes(self, data: bytes) -> None:
assert data == get_example_data()

def read_bytes(self):
def read_bytes(self) -> bytes:
return get_example_data()

@staticmethod
def copyfile(src, dst):
def copyfile(src: str, dst: str) -> None:
assert src == os.path.join(get_example_folder(), get_example_filename())
assert dst == get_example_filepath()

@staticmethod
def exists(path):
def exists(path: str) -> bool:
assert path == os.path.join(get_example_folder(), get_example_filename())
return True

@staticmethod
def remove(path):
def remove(path: str) -> None:
assert path == os.path.join(get_example_folder(), get_example_filename())


MOCK = os.getenv("MOCK_SWITCH", "false").lower() == "true"


@pytest.fixture
def setup_local_fs_mock(monkeypatch: pytest.MonkeyPatch):
def setup_local_fs_mock(monkeypatch: pytest.MonkeyPatch) -> Generator[None]:
if MOCK:
monkeypatch.setattr(Path, "write_bytes", MockLocalFSClass.write_bytes)
monkeypatch.setattr(Path, "read_bytes", MockLocalFSClass.read_bytes)
Expand Down
18 changes: 11 additions & 7 deletions api/tests/unit_tests/oss/__mock/tencent_cos.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
from collections.abc import Generator

import pytest
from qcloud_cos import CosS3Client
Expand All @@ -12,38 +13,41 @@
object_response,
)

# CosS3Client returns the response headers as a dict.
type _CosHeaders = dict[str, str | int | bool]


class MockTencentCosClass:
def __init__(self, conf, retry=1, session=None):
def __init__(self, *_args: object, **_kwargs: object) -> None:
self.bucket_name = get_example_bucket()
self.key = get_example_filename()
self.content = get_example_data()
self.filepath = get_example_filepath()
self.resp = {
self.resp: _CosHeaders = {
"ETag": "ee8de918d05640145b18f70f4c3aa602",
"Server": "tencent-cos",
"x-cos-hash-crc64ecma": 16749565679157681890,
"x-cos-request-id": "NWU5MDNkYzlfNjRiODJhMDlfMzFmYzhfMTFm****",
}

def put_object(self, Bucket, Body, Key, EnableMD5=False, **kwargs): # noqa: N803
def put_object(self, Bucket: str, Body: bytes, Key: str) -> _CosHeaders: # noqa: N803
assert Bucket == self.bucket_name
assert Key == self.key
assert Body == self.content
return self.resp

def get_object(self, Bucket, Key, KeySimplifyCheck=True, **kwargs): # noqa: N803
def get_object(self, Bucket: str, Key: str) -> dict[str, StreamBody]: # noqa: N803
assert Bucket == self.bucket_name
assert Key == self.key

return {"Body": StreamBody(object_response(self.content))}

def object_exists(self, Bucket, Key): # noqa: N803
def object_exists(self, Bucket: str, Key: str) -> bool: # noqa: N803
assert Bucket == self.bucket_name
assert Key == self.key
return True

def delete_object(self, Bucket, Key, **kwargs): # noqa: N803
def delete_object(self, Bucket: str, Key: str) -> _CosHeaders: # noqa: N803
assert Bucket == self.bucket_name
assert Key == self.key
self.resp.update({"x-cos-delete-marker": True})
Expand All @@ -54,7 +58,7 @@ def delete_object(self, Bucket, Key, **kwargs): # noqa: N803


@pytest.fixture
def setup_tencent_cos_mock(monkeypatch: pytest.MonkeyPatch):
def setup_tencent_cos_mock(monkeypatch: pytest.MonkeyPatch) -> Generator[None]:
if MOCK:
monkeypatch.setattr(CosS3Client, "__init__", MockTencentCosClass.__init__)
monkeypatch.setattr(CosS3Client, "put_object", MockTencentCosClass.put_object)
Expand Down
15 changes: 8 additions & 7 deletions api/tests/unit_tests/oss/__mock/volcengine_tos.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
from collections import UserDict
from collections.abc import Generator

import pytest
from tos import TosClientV2
Expand All @@ -15,13 +16,13 @@
)


class AttrDict(UserDict):
def __getattr__(self, item):
class AttrDict(UserDict[str, object]):
def __getattr__(self, item: str) -> object:
return self.get(item)


class MockVolcengineTosClass:
def __init__(self, ak="", sk="", endpoint="", region=""):
def __init__(self, *_args: object, **_kwargs: object) -> None:
self.bucket_name = get_example_bucket()
self.key = get_example_filename()
self.content = get_example_data()
Expand All @@ -42,7 +43,7 @@ def __init__(self, ak="", sk="", endpoint="", region=""):
}
)

def put_object(self, bucket: str, key: str, content=None) -> PutObjectOutput:
def put_object(self, bucket: str, key: str, content: bytes) -> PutObjectOutput:
assert bucket == self.bucket_name
assert key == self.key
assert content == self.content
Expand All @@ -54,7 +55,7 @@ def get_object(self, bucket: str, key: str) -> GetObjectOutput:

return GetObjectOutput(TosResponse(object_response(self.content)))

def get_object_to_file(self, bucket: str, key: str, file_path: str):
def get_object_to_file(self, bucket: str, key: str, file_path: str) -> None:
assert bucket == self.bucket_name
assert key == self.key
assert file_path == self.filepath
Expand All @@ -64,7 +65,7 @@ def head_object(self, bucket: str, key: str) -> HeadObjectOutput:
assert key == self.key
return HeadObjectOutput(self.resp)

def delete_object(self, bucket: str, key: str):
def delete_object(self, bucket: str, key: str) -> DeleteObjectOutput:
assert bucket == self.bucket_name
assert key == self.key
return DeleteObjectOutput(self.resp)
Expand All @@ -74,7 +75,7 @@ def delete_object(self, bucket: str, key: str):


@pytest.fixture
def setup_volcengine_tos_mock(monkeypatch: pytest.MonkeyPatch):
def setup_volcengine_tos_mock(monkeypatch: pytest.MonkeyPatch) -> Generator[None]:
if MOCK:
monkeypatch.setattr(TosClientV2, "__init__", MockVolcengineTosClass.__init__)
monkeypatch.setattr(TosClientV2, "put_object", MockVolcengineTosClass.put_object)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from typing import override
from unittest.mock import patch

import pytest
Expand All @@ -15,7 +16,8 @@

class TestAliyunOss(BaseStorageTest):
@pytest.fixture(autouse=True)
def setup_method(self, setup_aliyun_oss_mock):
@override
def setup_method(self, setup_aliyun_oss_mock: None) -> None:
"""Executed before each test method."""
with patch.object(Auth, "__init__", return_value=None):
self.storage = AliyunOssStorage()
Expand Down
Loading
Loading