Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor(api): annotate vector store provider unit tests (#44692)

Eddy ZHANG39d9a3336195
diff --git a/api/providers/vdb/vdb-alibabacloud-mysql/tests/unit_tests/src/dify_vdb_alibabacloud_mysql/test_alibabacloud_mysql_vector.py b/api/providers/vdb/vdb-alibabacloud-mysql/tests/unit_tests/src/dify_vdb_alibabacloud_mysql/test_alibabacloud_mysql_vector.py
index f0184c549f9..75b301ccebc 100644
--- a/api/providers/vdb/vdb-alibabacloud-mysql/tests/unit_tests/src/dify_vdb_alibabacloud_mysql/test_alibabacloud_mysql_vector.py
+++ b/api/providers/vdb/vdb-alibabacloud-mysql/tests/unit_tests/src/dify_vdb_alibabacloud_mysql/test_alibabacloud_mysql_vector.py
@@ -15,21 +15,21 @@ from core.rag.models.document import Document
from models.dataset import Dataset
-def test_validate_distance_function_accepts_supported_values():
+def test_validate_distance_function_accepts_supported_values() -> None:
factory = AlibabaCloudMySQLVectorFactory()
assert factory._validate_distance_function("cosine") == "cosine"
assert factory._validate_distance_function("euclidean") == "euclidean"
-def test_validate_distance_function_rejects_unsupported_values():
+def test_validate_distance_function_rejects_unsupported_values() -> None:
factory = AlibabaCloudMySQLVectorFactory()
with pytest.raises(ValueError, match="Invalid distance function"):
factory._validate_distance_function("dot_product")
-def test_factory_init_vector_uses_existing_index_struct_class_prefix(monkeypatch: pytest.MonkeyPatch):
+def test_factory_init_vector_uses_existing_index_struct_class_prefix(monkeypatch: pytest.MonkeyPatch) -> None:
factory = AlibabaCloudMySQLVectorFactory()
dataset = Dataset(
id="dataset-1", index_struct=json.dumps({"vector_store": {"class_prefix": "existing_collection"}})
@@ -52,7 +52,9 @@ def test_factory_init_vector_uses_existing_index_struct_class_prefix(monkeypatch
assert vector_cls.call_args.kwargs["collection_name"] == "existing_collection"
-def test_factory_init_vector_generates_collection_name_when_index_struct_is_missing(monkeypatch: pytest.MonkeyPatch):
+def test_factory_init_vector_generates_collection_name_when_index_struct_is_missing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
factory = AlibabaCloudMySQLVectorFactory()
dataset = Dataset(id="dataset-2")
@@ -81,7 +83,7 @@ try:
except ImportError:
# Fallback for testing environments where mysql-connector-python might not be installed
class MySQLError(Exception):
- def __init__(self, errno, msg):
+ def __init__(self, errno: int, msg: str) -> None:
self.errno = errno
self.msg = msg
super().__init__(msg)
@@ -89,7 +91,7 @@ except ImportError:
class TestAlibabaCloudMySQLVector(unittest.TestCase):
@override
- def setUp(self):
+ def setUp(self) -> None:
self.config = AlibabaCloudMySQLVectorConfig(
host="localhost",
port=3306,
@@ -117,7 +119,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
self.sample_embeddings = [[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8]]
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_init(self, mock_pool_class):
+ def test_init(self, mock_pool_class: MagicMock) -> None:
"""Test AlibabaCloudMySQLVector initialization."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -143,7 +145,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.redis_client")
- def test_create_collection(self, mock_redis, mock_pool_class):
+ def test_create_collection(self, mock_redis: MagicMock, mock_pool_class: MagicMock) -> None:
"""Test collection creation."""
# Mock Redis operations
mock_redis.lock.return_value.__enter__ = MagicMock()
@@ -174,7 +176,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
mock_redis.set.assert_called_once()
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_vector_support_check_success(self, mock_pool_class):
+ def test_vector_support_check_success(self, mock_pool_class: MagicMock) -> None:
"""Test successful vector support check."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -191,7 +193,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert vector_store is not None
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_vector_support_check_failure(self, mock_pool_class):
+ def test_vector_support_check_failure(self, mock_pool_class: MagicMock) -> None:
"""Test vector support check failure."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -215,7 +217,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert "RDS MySQL Vector functions are not available" in str(context.value)
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_vector_support_check_function_error(self, mock_pool_class):
+ def test_vector_support_check_function_error(self, mock_pool_class: MagicMock) -> None:
"""Test vector support check with function not found error."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -241,7 +243,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.redis_client")
- def test_create_documents(self, mock_redis, mock_pool_class):
+ def test_create_documents(self, mock_redis: MagicMock, mock_pool_class: MagicMock) -> None:
"""Test creating documents with embeddings."""
# Setup mocks
self._setup_mocks(mock_redis, mock_pool_class)
@@ -254,7 +256,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert "doc2" in result
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_add_texts(self, mock_pool_class):
+ def test_add_texts(self, mock_pool_class: MagicMock) -> None:
"""Test adding texts to the vector store."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -273,7 +275,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
mock_cursor.executemany.assert_called_once()
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_text_exists(self, mock_pool_class):
+ def test_text_exists(self, mock_pool_class: MagicMock) -> None:
"""Test checking if text exists."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -300,7 +302,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert last_call[0][1] == ("doc1",)
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_text_not_exists(self, mock_pool_class):
+ def test_text_not_exists(self, mock_pool_class: MagicMock) -> None:
"""Test checking if text does not exist."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -322,7 +324,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert not exists
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_get_by_ids(self, mock_pool_class):
+ def test_get_by_ids(self, mock_pool_class: MagicMock) -> None:
"""Test getting documents by IDs."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -348,7 +350,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert docs[1].page_content == "Test document 2"
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_get_by_ids_empty_list(self, mock_pool_class):
+ def test_get_by_ids_empty_list(self, mock_pool_class: MagicMock) -> None:
"""Test getting documents with empty ID list."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -366,7 +368,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert len(docs) == 0
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_delete_by_ids(self, mock_pool_class):
+ def test_delete_by_ids(self, mock_pool_class: MagicMock) -> None:
"""Test deleting documents by IDs."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -390,7 +392,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert delete_call[0][1] == ["doc1", "doc2"]
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_delete_by_ids_empty_list(self, mock_pool_class):
+ def test_delete_by_ids_empty_list(self, mock_pool_class: MagicMock) -> None:
"""Test deleting with empty ID list."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -411,7 +413,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert len(delete_calls) == 0
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_delete_by_ids_table_not_exists(self, mock_pool_class):
+ def test_delete_by_ids_table_not_exists(self, mock_pool_class: MagicMock) -> None:
"""Test deleting when table doesn't exist."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -436,7 +438,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
vector_store.delete_by_ids(["doc1"])
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_delete_by_metadata_field(self, mock_pool_class):
+ def test_delete_by_metadata_field(self, mock_pool_class: MagicMock) -> None:
"""Test deleting documents by metadata field."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -460,7 +462,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert delete_call[0][1] == ("$.document_id", "dataset1")
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_search_by_vector_cosine(self, mock_pool_class):
+ def test_search_by_vector_cosine(self, mock_pool_class: MagicMock) -> None:
"""Test vector search with cosine distance."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -485,7 +487,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert docs[0].metadata["distance"] == 0.1
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_search_by_vector_euclidean(self, mock_pool_class):
+ def test_search_by_vector_euclidean(self, mock_pool_class: MagicMock) -> None:
"""Test vector search with euclidean distance."""
config = AlibabaCloudMySQLVectorConfig(
host="localhost",
@@ -518,7 +520,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert abs(docs[0].metadata["score"] - 1.0 / 3.0) < 0.01 # 1/(1+2) = 1/3
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_search_by_vector_with_filter(self, mock_pool_class):
+ def test_search_by_vector_with_filter(self, mock_pool_class: MagicMock) -> None:
"""Test vector search with document ID filter."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -543,7 +545,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert "WHERE JSON_UNQUOTE" in search_call[0][0]
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_search_by_vector_with_score_threshold(self, mock_pool_class):
+ def test_search_by_vector_with_score_threshold(self, mock_pool_class: MagicMock) -> None:
"""Test vector search with score threshold."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -578,7 +580,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert docs[0].page_content == "High similarity document"
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_search_by_vector_invalid_top_k(self, mock_pool_class):
+ def test_search_by_vector_invalid_top_k(self, mock_pool_class: MagicMock) -> None:
"""Test vector search with invalid top_k."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -600,7 +602,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
vector_store.search_by_vector(query_vector, top_k="invalid")
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_search_by_full_text(self, mock_pool_class):
+ def test_search_by_full_text(self, mock_pool_class: MagicMock) -> None:
"""Test full-text search."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -629,7 +631,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert docs[0].metadata["score"] == 1.5
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_search_by_full_text_with_filter(self, mock_pool_class):
+ def test_search_by_full_text_with_filter(self, mock_pool_class: MagicMock) -> None:
"""Test full-text search with document ID filter."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -653,7 +655,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert "AND JSON_UNQUOTE" in search_call[0][0]
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_search_by_full_text_invalid_top_k(self, mock_pool_class):
+ def test_search_by_full_text_invalid_top_k(self, mock_pool_class: MagicMock) -> None:
"""Test full-text search with invalid top_k."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -674,7 +676,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
vector_store.search_by_full_text("test", top_k="invalid")
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_delete_collection(self, mock_pool_class):
+ def test_delete_collection(self, mock_pool_class: MagicMock) -> None:
"""Test deleting the entire collection."""
# Mock the connection pool
mock_pool = MagicMock()
@@ -697,7 +699,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
assert f"DROP TABLE IF EXISTS {self.collection_name.lower()}" in drop_call[0][0]
@patch("dify_vdb_alibabacloud_mysql.alibabacloud_mysql_vector.mysql.connector.pooling.MySQLConnectionPool")
- def test_unsupported_distance_function(self, mock_pool_class):
+ def test_unsupported_distance_function(self, mock_pool_class: MagicMock) -> None:
"""Test that Pydantic validation rejects unsupported distance functions."""
# Test that creating config with unsupported distance function raises ValidationError
with pytest.raises(
@@ -716,7 +718,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
# The error should be related to validation
assert "Input should be 'cosine' or 'euclidean'" in str(context.value) or "manhattan" in str(context.value)
- def _setup_mocks(self, mock_redis, mock_pool_class):
+ def _setup_mocks(self, mock_redis: MagicMock, mock_pool_class: MagicMock) -> None:
"""Helper method to setup common mocks."""
# Mock Redis operations
mock_redis.lock.return_value.__enter__ = MagicMock()
@@ -744,7 +746,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):
{"max_connection": 0}, # Test invalid max_connection
],
)
-def test_config_validation_parametrized(invalid_config_override):
+def test_config_validation_parametrized(invalid_config_override: dict[str, str | int]) -> None:
"""Test configuration validation for various invalid inputs using parametrize."""
config = {
"host": "localhost",
diff --git a/api/providers/vdb/vdb-clickzetta/tests/unit_tests/src/dify_vdb_clickzetta/test_clickzetta_vector.py b/api/providers/vdb/vdb-clickzetta/tests/unit_tests/src/dify_vdb_clickzetta/test_clickzetta_vector.py
index 00d3d198e64..681b2232a87 100644
--- a/api/providers/vdb/vdb-clickzetta/tests/unit_tests/src/dify_vdb_clickzetta/test_clickzetta_vector.py
+++ b/api/providers/vdb/vdb-clickzetta/tests/unit_tests/src/dify_vdb_clickzetta/test_clickzetta_vector.py
@@ -1,8 +1,10 @@
import importlib
import queue
import sys
+from collections.abc import Callable, Generator
from contextlib import contextmanager
-from types import SimpleNamespace
+from types import ModuleType, SimpleNamespace
+from typing import Any, NoReturn, Self
from unittest.mock import MagicMock, patch
import pytest
@@ -12,33 +14,33 @@ from core.rag.models.document import Document
from models.dataset import Dataset
-def _build_fake_clickzetta_module():
+def _build_fake_clickzetta_module() -> FakeModule:
clickzetta = FakeModule("clickzetta")
class _FakeCursor:
- def __init__(self):
+ def __init__(self) -> None:
self.execute = MagicMock()
self.executemany = MagicMock()
self.fetchall = MagicMock(return_value=[])
self.fetchone = MagicMock(return_value=(0,))
- def __enter__(self):
+ def __enter__(self) -> Self:
return self
- def __exit__(self, exc_type, exc, tb):
+ def __exit__(self, exc_type: object, exc: object, tb: object) -> bool:
return False
class _FakeConnection:
- def __init__(self):
+ def __init__(self) -> None:
self.cursor_obj = _FakeCursor()
- def cursor(self):
+ def cursor(self) -> _FakeCursor:
return self.cursor_obj
- def close(self):
+ def close(self) -> None:
return None
- def connect(**_kwargs):
+ def connect(**_kwargs) -> _FakeConnection:
return _FakeConnection()
clickzetta.connect = connect
@@ -46,14 +48,14 @@ def _build_fake_clickzetta_module():
@pytest.fixture
-def clickzetta_module(monkeypatch: pytest.MonkeyPatch):
+def clickzetta_module(monkeypatch: pytest.MonkeyPatch) -> ModuleType:
monkeypatch.setitem(sys.modules, "clickzetta", _build_fake_clickzetta_module())
import dify_vdb_clickzetta.clickzetta_vector as module
return importlib.reload(module)
-def _config(module):
+def _config(module: ModuleType) -> Any:
return module.ClickzettaConfig(
username="username",
password="password",
@@ -77,14 +79,14 @@ def _config(module):
("schema_name", "CLICKZETTA_SCHEMA"),
],
)
-def test_clickzetta_config_validation(clickzetta_module, field, error_message):
+def test_clickzetta_config_validation(clickzetta_module: ModuleType, field: str, error_message: str) -> None:
values = _config(clickzetta_module).model_dump()
values[field] = ""
with pytest.raises(ValueError, match=error_message):
clickzetta_module.ClickzettaConfig.model_validate(values)
-def test_parse_metadata_handles_valid_double_encoded_and_invalid_json(clickzetta_module):
+def test_parse_metadata_handles_valid_double_encoded_and_invalid_json(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
parsed = vector._parse_metadata('{"document_id":"doc-1"}', "row-1")
@@ -100,7 +102,7 @@ def test_parse_metadata_handles_valid_double_encoded_and_invalid_json(clickzetta
assert parsed_fallback["document_id"] == "row-3"
-def test_safe_doc_id_and_vector_format_helpers(clickzetta_module):
+def test_safe_doc_id_and_vector_format_helpers(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
assert vector._format_vector_simple([0.1, 0.2, 0.3]) == "0.1,0.2,0.3"
@@ -109,13 +111,13 @@ def test_safe_doc_id_and_vector_format_helpers(clickzetta_module):
assert len(vector._safe_doc_id("a" * 300)) == 255
-def test_table_exists_returns_false_for_not_found_and_other_exceptions(clickzetta_module):
+def test_table_exists_returns_false_for_not_found_and_other_exceptions(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._table_name = "table_1"
@contextmanager
- def _ctx_not_found():
+ def _ctx_not_found() -> Generator[MagicMock]:
connection = MagicMock()
cursor = MagicMock()
cursor.__enter__.return_value = cursor
@@ -128,7 +130,7 @@ def test_table_exists_returns_false_for_not_found_and_other_exceptions(clickzett
assert vector._table_exists() is False
@contextmanager
- def _ctx_other_error():
+ def _ctx_other_error() -> Generator[MagicMock]:
connection = MagicMock()
cursor = MagicMock()
cursor.__enter__.return_value = cursor
@@ -141,7 +143,7 @@ def test_table_exists_returns_false_for_not_found_and_other_exceptions(clickzett
assert vector._table_exists() is False
-def test_text_exists_handles_missing_table_and_existing_rows(clickzetta_module):
+def test_text_exists_handles_missing_table_and_existing_rows(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._table_name = "table_1"
@@ -152,7 +154,7 @@ def test_text_exists_handles_missing_table_and_existing_rows(clickzetta_module):
vector._table_exists = MagicMock(return_value=True)
@contextmanager
- def _ctx():
+ def _ctx() -> Generator[MagicMock]:
connection = MagicMock()
cursor = MagicMock()
cursor.__enter__.return_value = cursor
@@ -165,7 +167,7 @@ def test_text_exists_handles_missing_table_and_existing_rows(clickzetta_module):
assert vector.text_exists("doc-1") is True
-def test_delete_by_ids_and_delete_by_metadata_field_short_circuit(clickzetta_module):
+def test_delete_by_ids_and_delete_by_metadata_field_short_circuit(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._table_name = "table_1"
@@ -182,7 +184,7 @@ def test_delete_by_ids_and_delete_by_metadata_field_short_circuit(clickzetta_mod
vector._execute_write.assert_not_called()
-def test_search_short_circuit_behaviors(clickzetta_module):
+def test_search_short_circuit_behaviors(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._table_name = "table_1"
@@ -194,7 +196,7 @@ def test_search_short_circuit_behaviors(clickzetta_module):
assert vector.search_by_full_text("query", top_k=2) == []
-def test_search_by_like_returns_documents_with_default_score(clickzetta_module):
+def test_search_by_like_returns_documents_with_default_score(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._table_name = "table_1"
@@ -202,7 +204,7 @@ def test_search_by_like_returns_documents_with_default_score(clickzetta_module):
vector._parse_metadata = MagicMock(return_value={"document_id": "doc-1", "doc_id": "seg-1"})
@contextmanager
- def _ctx():
+ def _ctx() -> Generator[MagicMock]:
connection = MagicMock()
cursor = MagicMock()
cursor.__enter__.return_value = cursor
@@ -219,7 +221,7 @@ def test_search_by_like_returns_documents_with_default_score(clickzetta_module):
assert docs[0].metadata["score"] == 0.5
-def test_factory_initializes_clickzetta_vector(clickzetta_module, monkeypatch: pytest.MonkeyPatch):
+def test_factory_initializes_clickzetta_vector(clickzetta_module: ModuleType, monkeypatch: pytest.MonkeyPatch) -> None:
factory = clickzetta_module.ClickzettaVectorFactory()
dataset = Dataset(id="dataset-1")
@@ -244,7 +246,9 @@ def test_factory_initializes_clickzetta_vector(clickzetta_module, monkeypatch: p
assert vector_cls.call_args.kwargs["collection_name"] == "collection"
-def test_connection_pool_singleton_and_config_key(clickzetta_module, monkeypatch: pytest.MonkeyPatch):
+def test_connection_pool_singleton_and_config_key(
+ clickzetta_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
clickzetta_module.ClickzettaConnectionPool._instance = None
monkeypatch.setattr(clickzetta_module.ClickzettaConnectionPool, "_start_cleanup_thread", MagicMock())
@@ -256,7 +260,9 @@ def test_connection_pool_singleton_and_config_key(clickzetta_module, monkeypatch
assert "username:instance:service:workspace:cluster:dify" in key
-def test_connection_pool_create_connection_retries_and_configures(clickzetta_module, monkeypatch: pytest.MonkeyPatch):
+def test_connection_pool_create_connection_retries_and_configures(
+ clickzetta_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
monkeypatch.setattr(clickzetta_module.ClickzettaConnectionPool, "_start_cleanup_thread", MagicMock())
pool = clickzetta_module.ClickzettaConnectionPool()
config = _config(clickzetta_module)
@@ -275,7 +281,9 @@ def test_connection_pool_create_connection_retries_and_configures(clickzetta_mod
pool._configure_connection.assert_called_once_with(connection)
-def test_connection_pool_create_connection_raises_after_retries(clickzetta_module, monkeypatch: pytest.MonkeyPatch):
+def test_connection_pool_create_connection_raises_after_retries(
+ clickzetta_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
monkeypatch.setattr(clickzetta_module.ClickzettaConnectionPool, "_start_cleanup_thread", MagicMock())
pool = clickzetta_module.ClickzettaConnectionPool()
config = _config(clickzetta_module)
@@ -287,7 +295,7 @@ def test_connection_pool_create_connection_raises_after_retries(clickzetta_modul
pool._create_connection(config)
-def test_connection_pool_configure_and_validate_connection(clickzetta_module):
+def test_connection_pool_configure_and_validate_connection(clickzetta_module: ModuleType) -> None:
monkeypatch = pytest.MonkeyPatch()
monkeypatch.setattr(clickzetta_module.ClickzettaConnectionPool, "_start_cleanup_thread", MagicMock())
pool = clickzetta_module.ClickzettaConnectionPool()
@@ -308,7 +316,7 @@ def test_connection_pool_configure_and_validate_connection(clickzetta_module):
monkeypatch.undo()
-def test_connection_pool_configure_connection_swallows_errors(clickzetta_module):
+def test_connection_pool_configure_connection_swallows_errors(clickzetta_module: ModuleType) -> None:
monkeypatch = pytest.MonkeyPatch()
monkeypatch.setattr(clickzetta_module.ClickzettaConnectionPool, "_start_cleanup_thread", MagicMock())
pool = clickzetta_module.ClickzettaConnectionPool()
@@ -319,7 +327,9 @@ def test_connection_pool_configure_connection_swallows_errors(clickzetta_module)
monkeypatch.undo()
-def test_connection_pool_get_return_cleanup_and_shutdown(clickzetta_module, monkeypatch: pytest.MonkeyPatch):
+def test_connection_pool_get_return_cleanup_and_shutdown(
+ clickzetta_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
monkeypatch.setattr(clickzetta_module.ClickzettaConnectionPool, "_start_cleanup_thread", MagicMock())
pool = clickzetta_module.ClickzettaConnectionPool()
config = _config(clickzetta_module)
@@ -361,7 +371,9 @@ def test_connection_pool_get_return_cleanup_and_shutdown(clickzetta_module, monk
assert pool._shutdown is True
-def test_connection_pool_start_cleanup_thread_runs_worker_once(clickzetta_module, monkeypatch: pytest.MonkeyPatch):
+def test_connection_pool_start_cleanup_thread_runs_worker_once(
+ clickzetta_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
pool = clickzetta_module.ClickzettaConnectionPool.__new__(clickzetta_module.ClickzettaConnectionPool)
pool._shutdown = False
pool._cleanup_expired_connections = MagicMock(side_effect=lambda: setattr(pool, "_shutdown", True))
@@ -369,12 +381,12 @@ def test_connection_pool_start_cleanup_thread_runs_worker_once(clickzetta_module
monkeypatch.setattr(clickzetta_module.time, "sleep", lambda _s: None)
class _Thread:
- def __init__(self, target, daemon):
+ def __init__(self, target: Callable[[], None], daemon: bool) -> None:
self._target = target
self.daemon = daemon
self.started = False
- def start(self):
+ def start(self) -> None:
self.started = True
self._target()
@@ -385,7 +397,9 @@ def test_connection_pool_start_cleanup_thread_runs_worker_once(clickzetta_module
pool._cleanup_expired_connections.assert_called_once()
-def test_vector_init_connection_context_and_helpers(clickzetta_module, monkeypatch: pytest.MonkeyPatch):
+def test_vector_init_connection_context_and_helpers(
+ clickzetta_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
pool = MagicMock()
pool.get_connection.return_value = "conn"
monkeypatch.setattr(clickzetta_module.ClickzettaConnectionPool, "get_instance", MagicMock(return_value=pool))
@@ -406,14 +420,16 @@ def test_vector_init_connection_context_and_helpers(clickzetta_module, monkeypat
assert vector._ensure_connection() == "conn"
-def test_write_queue_initialization_worker_and_execute_write(clickzetta_module, monkeypatch: pytest.MonkeyPatch):
+def test_write_queue_initialization_worker_and_execute_write(
+ clickzetta_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
class _Thread:
- def __init__(self, target, daemon):
+ def __init__(self, target: Callable[[], None], daemon: bool) -> None:
self.target = target
self.daemon = daemon
self.started = 0
- def start(self):
+ def start(self) -> None:
self.started += 1
monkeypatch.setattr(clickzetta_module.threading, "Thread", _Thread)
@@ -448,7 +464,10 @@ def test_write_queue_initialization_worker_and_execute_write(clickzetta_module,
vector._execute_write(lambda: None)
class _ImmediateSuccessQueue:
- def put(self, task):
+ def put(
+ self,
+ task: tuple[Callable[..., object], tuple[object, ...], dict[str, object], queue.Queue[tuple[bool, object]]],
+ ) -> None:
func, args, kwargs, result_q = task
result_q.put((True, func(*args, **kwargs)))
@@ -456,7 +475,10 @@ def test_write_queue_initialization_worker_and_execute_write(clickzetta_module,
assert vector._execute_write(lambda x: x * 2, 3) == 6
class _ImmediateFailQueue:
- def put(self, task):
+ def put(
+ self,
+ task: tuple[Callable[..., object], tuple[object, ...], dict[str, object], queue.Queue[tuple[bool, object]]],
+ ) -> None:
_, _, _, result_q = task
result_q.put((False, ValueError("write failed")))
@@ -465,13 +487,13 @@ def test_write_queue_initialization_worker_and_execute_write(clickzetta_module,
vector._execute_write(lambda: None)
-def test_table_exists_true_and_create_invokes_write_and_add_texts(clickzetta_module):
+def test_table_exists_true_and_create_invokes_write_and_add_texts(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._table_name = "table_1"
@contextmanager
- def _ctx_exists():
+ def _ctx_exists() -> Generator[MagicMock]:
connection = MagicMock()
cursor = MagicMock()
cursor.__enter__.return_value = cursor
@@ -490,7 +512,7 @@ def test_table_exists_true_and_create_invokes_write_and_add_texts(clickzetta_mod
vector.add_texts.assert_called_once_with(docs, [[0.1, 0.2]])
-def test_create_table_and_indexes_paths(clickzetta_module):
+def test_create_table_and_indexes_paths(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._table_name = "table_1"
@@ -504,7 +526,7 @@ def test_create_table_and_indexes_paths(clickzetta_module):
vector._table_exists = MagicMock(return_value=False)
@contextmanager
- def _ctx():
+ def _ctx() -> Generator[MagicMock]:
connection = MagicMock()
cursor = MagicMock()
cursor.__enter__.return_value = cursor
@@ -525,7 +547,7 @@ def test_create_table_and_indexes_paths(clickzetta_module):
vector._create_inverted_index.assert_not_called()
-def test_create_vector_index_branches(clickzetta_module):
+def test_create_vector_index_branches(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._table_name = "table_1"
@@ -542,17 +564,17 @@ def test_create_vector_index_branches(clickzetta_module):
cursor.reset_mock()
cursor.execute.side_effect = [None, RuntimeError("already exists")]
- cursor.fetchall.return_value = []
+ cursor.fetchall.return_value = list[object]()
vector._create_vector_index(cursor)
cursor.reset_mock()
cursor.execute.side_effect = [None, RuntimeError("unexpected")]
- cursor.fetchall.return_value = []
+ cursor.fetchall.return_value = list[object]()
with pytest.raises(RuntimeError, match="unexpected"):
vector._create_vector_index(cursor)
-def test_create_inverted_index_branches(clickzetta_module):
+def test_create_inverted_index_branches(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._table_name = "table_1"
@@ -578,11 +600,13 @@ def test_create_inverted_index_branches(clickzetta_module):
cursor.reset_mock()
cursor.execute.side_effect = [None, RuntimeError("other create failure")]
- cursor.fetchall.return_value = []
+ cursor.fetchall.return_value = list[object]()
vector._create_inverted_index(cursor)
-def test_add_texts_batches_and_insert_batch_behaviors(clickzetta_module, monkeypatch: pytest.MonkeyPatch):
+def test_add_texts_batches_and_insert_batch_behaviors(
+ clickzetta_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._config.batch_size = 2
@@ -629,7 +653,7 @@ def test_add_texts_batches_and_insert_batch_behaviors(clickzetta_module, monkeyp
good_doc = Document(page_content="doc-good", metadata={"doc_id": "id-good"})
@contextmanager
- def _ctx():
+ def _ctx() -> Generator[MagicMock]:
connection = MagicMock()
cursor = MagicMock()
cursor.__enter__.return_value = cursor
@@ -648,7 +672,7 @@ def test_add_texts_batches_and_insert_batch_behaviors(clickzetta_module, monkeyp
)
@contextmanager
- def _ctx_error():
+ def _ctx_error() -> Generator[MagicMock]:
connection = MagicMock()
cursor = MagicMock()
cursor.__enter__.return_value = cursor
@@ -667,7 +691,7 @@ def test_add_texts_batches_and_insert_batch_behaviors(clickzetta_module, monkeyp
assert vector._safe_doc_id("!!!") == "generated-id"
-def test_delete_by_ids_and_metadata_impl_paths(clickzetta_module):
+def test_delete_by_ids_and_metadata_impl_paths(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._table_name = "table_1"
@@ -686,7 +710,7 @@ def test_delete_by_ids_and_metadata_impl_paths(clickzetta_module):
vector._safe_doc_id = MagicMock(side_effect=lambda x: x)
@contextmanager
- def _ctx():
+ def _ctx() -> Generator[MagicMock]:
connection = MagicMock()
cursor = MagicMock()
cursor.__enter__.return_value = cursor
@@ -699,7 +723,7 @@ def test_delete_by_ids_and_metadata_impl_paths(clickzetta_module):
vector._delete_by_metadata_field_impl("document_id", "doc-1")
-def test_search_by_vector_covers_cosine_and_l2_paths(clickzetta_module):
+def test_search_by_vector_covers_cosine_and_l2_paths(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._config.vector_distance_function = "cosine_distance"
@@ -708,7 +732,7 @@ def test_search_by_vector_covers_cosine_and_l2_paths(clickzetta_module):
vector._parse_metadata = MagicMock(return_value={"document_id": "doc-1", "doc_id": "seg-1"})
@contextmanager
- def _ctx():
+ def _ctx() -> Generator[MagicMock]:
connection = MagicMock()
cursor = MagicMock()
cursor.__enter__.return_value = cursor
@@ -728,14 +752,14 @@ def test_search_by_vector_covers_cosine_and_l2_paths(clickzetta_module):
assert l2_docs[0].metadata["score"] == pytest.approx(1 / 1.2)
-def test_search_by_full_text_success_and_fallback(clickzetta_module):
+def test_search_by_full_text_success_and_fallback(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._table_name = "table_1"
vector._table_exists = MagicMock(return_value=True)
@contextmanager
- def _ctx_success():
+ def _ctx_success() -> Generator[MagicMock]:
connection = MagicMock()
cursor = MagicMock()
cursor.__enter__.return_value = cursor
@@ -754,7 +778,7 @@ def test_search_by_full_text_success_and_fallback(clickzetta_module):
assert docs[1].metadata["doc_id"] == "seg-2"
@contextmanager
- def _ctx_failure():
+ def _ctx_failure() -> Generator[MagicMock]:
connection = MagicMock()
cursor = MagicMock()
cursor.__enter__.return_value = cursor
@@ -769,7 +793,7 @@ def test_search_by_full_text_success_and_fallback(clickzetta_module):
assert fallback_docs == vector._search_by_like.return_value
-def test_search_by_like_missing_table_and_delete_table(clickzetta_module):
+def test_search_by_like_missing_table_and_delete_table(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._table_name = "table_1"
@@ -777,7 +801,7 @@ def test_search_by_like_missing_table_and_delete_table(clickzetta_module):
assert vector._search_by_like("query", top_k=1) == []
@contextmanager
- def _ctx():
+ def _ctx() -> Generator[MagicMock]:
connection = MagicMock()
cursor = MagicMock()
cursor.__enter__.return_value = cursor
@@ -789,10 +813,10 @@ def test_search_by_like_missing_table_and_delete_table(clickzetta_module):
vector.delete()
-def test_clickzetta_pool_cleanup_and_shutdown_edge_paths(clickzetta_module):
+def test_clickzetta_pool_cleanup_and_shutdown_edge_paths(clickzetta_module: ModuleType) -> None:
pool = clickzetta_module.ClickzettaConnectionPool.__new__(clickzetta_module.ClickzettaConnectionPool)
- pool._pools = {}
- pool._pool_locks = {}
+ pool._pools = dict[str, object]()
+ pool._pool_locks = dict[str, object]()
pool._max_pool_size = 1
pool._connection_timeout = 10
pool._lock = clickzetta_module.threading.Lock()
@@ -814,11 +838,13 @@ def test_clickzetta_pool_cleanup_and_shutdown_edge_paths(clickzetta_module):
assert pool._shutdown is True # pyrefly: ignore[unnecessary-comparison]
-def test_clickzetta_pool_cleanup_thread_and_worker_exception_paths(clickzetta_module, monkeypatch: pytest.MonkeyPatch):
+def test_clickzetta_pool_cleanup_thread_and_worker_exception_paths(
+ clickzetta_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
pool = clickzetta_module.ClickzettaConnectionPool.__new__(clickzetta_module.ClickzettaConnectionPool)
pool._shutdown = False
- def _cleanup_then_fail():
+ def _cleanup_then_fail() -> NoReturn:
pool._shutdown = True
raise RuntimeError("cleanup failed")
@@ -826,11 +852,11 @@ def test_clickzetta_pool_cleanup_thread_and_worker_exception_paths(clickzetta_mo
monkeypatch.setattr(clickzetta_module.time, "sleep", lambda _s: None)
class _Thread:
- def __init__(self, target, daemon):
+ def __init__(self, target: Callable[[], None], daemon: bool) -> None:
self._target = target
self.daemon = daemon
- def start(self):
+ def start(self) -> None:
self._target()
monkeypatch.setattr(clickzetta_module.threading, "Thread", _Thread)
@@ -838,7 +864,7 @@ def test_clickzetta_pool_cleanup_thread_and_worker_exception_paths(clickzetta_mo
pool._cleanup_expired_connections.assert_called_once()
-def test_clickzetta_parse_metadata_and_write_worker_additional_branches(clickzetta_module):
+def test_clickzetta_parse_metadata_and_write_worker_additional_branches(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
parsed_non_dict = vector._parse_metadata("[1,2,3]", "row-1")
@@ -854,7 +880,7 @@ def test_clickzetta_parse_metadata_and_write_worker_additional_branches(clickzet
clickzetta_module.ClickzettaVector._write_worker()
class _BadQueue:
- def get(self, timeout):
+ def get(self, timeout: float | None) -> NoReturn:
clickzetta_module.ClickzettaVector._shutdown = True
raise RuntimeError("queue failed")
@@ -863,7 +889,7 @@ def test_clickzetta_parse_metadata_and_write_worker_additional_branches(clickzet
clickzetta_module.ClickzettaVector._write_worker()
-def test_clickzetta_inverted_index_existing_and_insert_non_dict_metadata(clickzetta_module):
+def test_clickzetta_inverted_index_existing_and_insert_non_dict_metadata(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._table_name = "table_1"
@@ -880,7 +906,7 @@ def test_clickzetta_inverted_index_existing_and_insert_non_dict_metadata(clickze
vector._safe_doc_id = MagicMock(side_effect=lambda value: str(value))
@contextmanager
- def _ctx():
+ def _ctx() -> Generator[MagicMock]:
connection = MagicMock()
cursor_obj = MagicMock()
cursor_obj.__enter__.return_value = cursor_obj
@@ -899,7 +925,7 @@ def test_clickzetta_inverted_index_existing_and_insert_non_dict_metadata(clickze
)
-def test_clickzetta_full_text_table_missing_and_non_dict_metadata(clickzetta_module):
+def test_clickzetta_full_text_table_missing_and_non_dict_metadata(clickzetta_module: ModuleType) -> None:
vector = clickzetta_module.ClickzettaVector.__new__(clickzetta_module.ClickzettaVector)
vector._config = _config(clickzetta_module)
vector._config.enable_inverted_index = True
@@ -911,7 +937,7 @@ def test_clickzetta_full_text_table_missing_and_non_dict_metadata(clickzetta_mod
vector._table_exists = MagicMock(return_value=True)
@contextmanager
- def _ctx():
+ def _ctx() -> Generator[MagicMock]:
connection = MagicMock()
cursor = MagicMock()
cursor.__enter__.return_value = cursor
diff --git a/api/providers/vdb/vdb-oceanbase/tests/unit_tests/src/dify_vdb_oceanbase/test_oceanbase_vector.py b/api/providers/vdb/vdb-oceanbase/tests/unit_tests/src/dify_vdb_oceanbase/test_oceanbase_vector.py
index 2e00d65feba..7a929aabbd4 100644
--- a/api/providers/vdb/vdb-oceanbase/tests/unit_tests/src/dify_vdb_oceanbase/test_oceanbase_vector.py
+++ b/api/providers/vdb/vdb-oceanbase/tests/unit_tests/src/dify_vdb_oceanbase/test_oceanbase_vector.py
@@ -2,7 +2,9 @@ import enum
import importlib
import json
import sys
-from types import SimpleNamespace
+from dataclasses import dataclass
+from types import ModuleType, SimpleNamespace
+from typing import Any
from unittest.mock import MagicMock, patch
import pytest
@@ -14,27 +16,27 @@ from core.rag.models.document import Document
from models.dataset import Dataset
-def _build_fake_pyobvector_module():
+def _build_fake_pyobvector_module() -> FakeModule:
pyobvector = FakeModule("pyobvector")
+ @dataclass
class VECTOR:
- def __init__(self, dim):
- self.dim = dim
+ dim: int
class VecIndexType(enum.IntEnum):
HNSW = 0
- def l2_distance(*_args, **_kwargs):
+ def l2_distance(*_args, **_kwargs) -> str:
return "l2"
- def cosine_distance(*_args, **_kwargs):
+ def cosine_distance(*_args, **_kwargs) -> str:
return "cosine"
- def inner_product(*_args, **_kwargs):
+ def inner_product(*_args, **_kwargs) -> str:
return "inner_product"
class ObVecClient:
- def __init__(self, **_kwargs):
+ def __init__(self, **_kwargs) -> None:
self.metadata_obj = SimpleNamespace(tables={})
self.engine = MagicMock()
self.check_table_exists = MagicMock(return_value=False)
@@ -60,7 +62,7 @@ def _build_fake_pyobvector_module():
@pytest.fixture
-def oceanbase_module(monkeypatch: pytest.MonkeyPatch):
+def oceanbase_module(monkeypatch: pytest.MonkeyPatch) -> ModuleType:
monkeypatch.setitem(sys.modules, "pyobvector", _build_fake_pyobvector_module())
import dify_vdb_oceanbase.oceanbase_vector as module
@@ -68,7 +70,7 @@ def oceanbase_module(monkeypatch: pytest.MonkeyPatch):
return importlib.reload(module)
-def _config(module):
+def _config(module: ModuleType) -> Any:
return module.OceanBaseVectorConfig(
host="127.0.0.1",
port=2881,
@@ -89,7 +91,7 @@ def _config(module):
("database", "", "config OCEANBASE_VECTOR_DATABASE is required"),
],
)
-def test_oceanbase_config_validation(oceanbase_module, field, value, message):
+def test_oceanbase_config_validation(oceanbase_module: ModuleType, field: str, value: str | int, message: str) -> None:
values = _config(oceanbase_module).model_dump()
values[field] = value
@@ -97,12 +99,12 @@ def test_oceanbase_config_validation(oceanbase_module, field, value, message):
oceanbase_module.OceanBaseVectorConfig.model_validate(values)
-def test_init_rejects_invalid_collection_name(oceanbase_module):
+def test_init_rejects_invalid_collection_name(oceanbase_module: ModuleType) -> None:
with pytest.raises(ValueError, match="Invalid collection name"):
oceanbase_module.OceanBaseVector("invalid-name", _config(oceanbase_module))
-def test_distance_to_score_for_supported_metrics(oceanbase_module):
+def test_distance_to_score_for_supported_metrics(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._config = SimpleNamespace(metric_type="l2")
assert vector._distance_to_score(3.0) == pytest.approx(0.25)
@@ -114,7 +116,7 @@ def test_distance_to_score_for_supported_metrics(oceanbase_module):
assert vector._distance_to_score(-0.2) == pytest.approx(0.2)
-def test_get_distance_func_raises_for_unknown_metric(oceanbase_module):
+def test_get_distance_func_raises_for_unknown_metric(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._config = SimpleNamespace(metric_type="manhattan")
@@ -122,7 +124,7 @@ def test_get_distance_func_raises_for_unknown_metric(oceanbase_module):
vector._get_distance_func()
-def test_process_search_results_handles_json_and_score_threshold(oceanbase_module):
+def test_process_search_results_handles_json_and_score_threshold(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
rows = [
("doc-1", '{"doc_id":"1"}', 0.9),
@@ -138,7 +140,7 @@ def test_process_search_results_handles_json_and_score_threshold(oceanbase_modul
assert docs[1].metadata["rank"] == 0.8
-def test_search_by_vector_validates_document_id_format(oceanbase_module):
+def test_search_by_vector_validates_document_id_format(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._collection_name = "collection_1"
vector._hnsw_ef_search = -1
@@ -149,7 +151,7 @@ def test_search_by_vector_validates_document_id_format(oceanbase_module):
vector.search_by_vector([0.1, 0.2], document_ids_filter=["bad id"])
-def test_search_by_full_text_returns_empty_when_disabled(oceanbase_module):
+def test_search_by_full_text_returns_empty_when_disabled(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._hybrid_search_enabled = False
vector._collection_name = "collection_1"
@@ -157,7 +159,7 @@ def test_search_by_full_text_returns_empty_when_disabled(oceanbase_module):
assert vector.search_by_full_text("query") == []
-def test_check_hybrid_search_support_uses_version_comment(oceanbase_module):
+def test_check_hybrid_search_support_uses_version_comment(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._config = SimpleNamespace(enable_hybrid_search=True)
vector._client = MagicMock()
@@ -174,7 +176,7 @@ def test_check_hybrid_search_support_uses_version_comment(oceanbase_module):
assert vector._check_hybrid_search_support() is False
-def test_init_get_type_and_field_loading(oceanbase_module):
+def test_init_get_type_and_field_loading(oceanbase_module: ModuleType) -> None:
config = _config(oceanbase_module)
config.enable_hybrid_search = False
@@ -190,12 +192,12 @@ def test_init_get_type_and_field_loading(oceanbase_module):
assert vector.field_exists("text") is True
-def test_load_collection_fields_handles_missing_table_and_exception(oceanbase_module):
+def test_load_collection_fields_handles_missing_table_and_exception(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._collection_name = "collection_1"
- vector._fields = []
+ vector._fields = list[object]()
vector._client = MagicMock()
- vector._client.metadata_obj.tables = {}
+ vector._client.metadata_obj.tables = dict[str, object]()
vector._load_collection_fields()
assert vector._fields == []
@@ -205,7 +207,7 @@ def test_load_collection_fields_handles_missing_table_and_exception(oceanbase_mo
assert vector._fields == []
-def test_create_delegates_to_collection_and_insert(oceanbase_module):
+def test_create_delegates_to_collection_and_insert(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._create_collection = MagicMock()
vector.add_texts = MagicMock()
@@ -218,7 +220,9 @@ def test_create_delegates_to_collection_and_insert(oceanbase_module):
vector.add_texts.assert_called_once_with(docs, [[0.1, 0.2]])
-def test_create_collection_cache_and_existing_table_short_circuits(oceanbase_module, monkeypatch: pytest.MonkeyPatch):
+def test_create_collection_cache_and_existing_table_short_circuits(
+ oceanbase_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
lock = MagicMock()
lock.__enter__.return_value = None
lock.__exit__.return_value = None
@@ -244,7 +248,9 @@ def test_create_collection_cache_and_existing_table_short_circuits(oceanbase_mod
vector.delete.assert_not_called()
-def test_create_collection_happy_path_with_hybrid_and_index(oceanbase_module, monkeypatch: pytest.MonkeyPatch):
+def test_create_collection_happy_path_with_hybrid_and_index(
+ oceanbase_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
lock = MagicMock()
lock.__enter__.return_value = None
lock.__exit__.return_value = None
@@ -284,7 +290,7 @@ def test_create_collection_happy_path_with_hybrid_and_index(oceanbase_module, mo
class _ParamRow:
"""Row-like object mimicking SQLAlchemy's Row, which exposes columns via ``_mapping``."""
- def __init__(self, **columns):
+ def __init__(self, **columns: object) -> None:
self._mapping = columns
@@ -293,7 +299,9 @@ def _seekdb_param_row(value: str) -> _ParamRow:
return _ParamRow(name="ob_vector_memory_limit_percentage", data_type="INT", value=value)
-def test_create_collection_resolves_parameter_value_by_column_name(oceanbase_module, monkeypatch: pytest.MonkeyPatch):
+def test_create_collection_resolves_parameter_value_by_column_name(
+ oceanbase_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
lock = MagicMock()
lock.__enter__.return_value = None
lock.__exit__.return_value = None
@@ -303,7 +311,7 @@ def test_create_collection_resolves_parameter_value_by_column_name(oceanbase_mod
monkeypatch.setattr(oceanbase_module, "Column", lambda *args, **kwargs: SimpleNamespace(args=args, kwargs=kwargs))
monkeypatch.setattr(oceanbase_module, "VECTOR", lambda dim: SimpleNamespace(dim=dim))
- def _build(rows):
+ def _build(rows: list[list[_ParamRow] | None]) -> Any:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._collection_name = "collection_1"
vector._vec_dim = 2
@@ -329,7 +337,7 @@ def test_create_collection_resolves_parameter_value_by_column_name(oceanbase_mod
)
-def test_create_collection_error_paths(oceanbase_module, monkeypatch: pytest.MonkeyPatch):
+def test_create_collection_error_paths(oceanbase_module: ModuleType, monkeypatch: pytest.MonkeyPatch) -> None:
lock = MagicMock()
lock.__enter__.return_value = None
lock.__exit__.return_value = None
@@ -349,7 +357,7 @@ def test_create_collection_error_paths(oceanbase_module, monkeypatch: pytest.Mon
vector.delete = MagicMock()
vector._load_collection_fields = MagicMock()
- vector._client.perform_raw_text_sql.return_value = []
+ vector._client.perform_raw_text_sql.return_value = list[object]()
with pytest.raises(ValueError, match="ob_vector_memory_limit_percentage not found"):
vector._create_collection()
@@ -366,7 +374,9 @@ def test_create_collection_error_paths(oceanbase_module, monkeypatch: pytest.Mon
vector._create_collection()
-def test_create_collection_fulltext_and_metadata_index_exceptions(oceanbase_module, monkeypatch: pytest.MonkeyPatch):
+def test_create_collection_fulltext_and_metadata_index_exceptions(
+ oceanbase_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
lock = MagicMock()
lock.__enter__.return_value = None
lock.__exit__.return_value = None
@@ -404,7 +414,7 @@ def test_create_collection_fulltext_and_metadata_index_exceptions(oceanbase_modu
vector._client.refresh_metadata.assert_called_once_with(["collection_1"])
-def test_check_hybrid_search_support_false_and_exception(oceanbase_module):
+def test_check_hybrid_search_support_false_and_exception(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._config = SimpleNamespace(enable_hybrid_search=False)
vector._client = MagicMock()
@@ -415,7 +425,7 @@ def test_check_hybrid_search_support_false_and_exception(oceanbase_module):
assert vector._check_hybrid_search_support() is False
-def test_add_texts_batches_refresh_and_exceptions(oceanbase_module):
+def test_add_texts_batches_refresh_and_exceptions(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._collection_name = "collection_1"
vector._config = SimpleNamespace(batch_size=2, hnsw_refresh_threshold=2)
@@ -445,7 +455,7 @@ def test_add_texts_batches_refresh_and_exceptions(oceanbase_module):
vector.add_texts([docs[0]], [[0.1]])
-def test_text_exists_and_delete_by_ids(oceanbase_module):
+def test_text_exists_and_delete_by_ids(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._collection_name = "collection_1"
vector._client = MagicMock()
@@ -468,7 +478,7 @@ def test_text_exists_and_delete_by_ids(oceanbase_module):
vector.delete_by_ids(["id-1"])
-def test_get_ids_and_delete_by_metadata_field(oceanbase_module):
+def test_get_ids_and_delete_by_metadata_field(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._collection_name = "collection_1"
vector._client = MagicMock()
@@ -497,7 +507,7 @@ def test_get_ids_and_delete_by_metadata_field(oceanbase_module):
vector.delete_by_ids.assert_not_called()
-def test_search_by_full_text_paths(oceanbase_module):
+def test_search_by_full_text_paths(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._collection_name = "collection_1"
vector._hybrid_search_enabled = True
@@ -525,7 +535,7 @@ def test_search_by_full_text_paths(oceanbase_module):
vector.search_by_full_text("query", top_k=0)
-def test_search_by_vector_paths(oceanbase_module):
+def test_search_by_vector_paths(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._collection_name = "collection_1"
vector._hnsw_ef_search = -1
@@ -552,7 +562,7 @@ def test_search_by_vector_paths(oceanbase_module):
vector.search_by_vector([0.1], score_threshold=0.1)
-def test_get_distance_func_and_distance_to_score_errors(oceanbase_module):
+def test_get_distance_func_and_distance_to_score_errors(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._config = SimpleNamespace(metric_type="cosine")
assert vector._get_distance_func() is oceanbase_module.cosine_distance
@@ -562,7 +572,7 @@ def test_get_distance_func_and_distance_to_score_errors(oceanbase_module):
vector._distance_to_score(0.1)
-def test_delete_success_and_exception(oceanbase_module):
+def test_delete_success_and_exception(oceanbase_module: ModuleType) -> None:
vector = oceanbase_module.OceanBaseVector.__new__(oceanbase_module.OceanBaseVector)
vector._collection_name = "collection_1"
vector._client = MagicMock()
@@ -575,7 +585,9 @@ def test_delete_success_and_exception(oceanbase_module):
vector.delete()
-def test_oceanbase_factory_uses_existing_or_generated_collection(oceanbase_module, monkeypatch: pytest.MonkeyPatch):
+def test_oceanbase_factory_uses_existing_or_generated_collection(
+ oceanbase_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
factory = oceanbase_module.OceanBaseVectorFactory()
dataset_with_index = Dataset(
id="dataset-1", index_struct=json.dumps({"vector_store": {"class_prefix": "EXISTING_COLLECTION"}})
@@ -617,7 +629,9 @@ def test_oceanbase_factory_uses_existing_or_generated_collection(oceanbase_modul
"doc-123\r\n", # trailing CRLF
],
)
-def test_search_by_vector_rejects_document_id_with_trailing_newline(oceanbase_module, bad_doc_id):
+def test_search_by_vector_rejects_document_id_with_trailing_newline(
+ oceanbase_module: ModuleType, bad_doc_id: str
+) -> None:
"""Regression for #39884 (sibling of #39234 / #39548 / #39666 / #39730 / #39880).
The old `re.match(r"^[a-zA-Z0-9_-]+$", doc_id)` accepted a doc_id ending in
@@ -644,7 +658,9 @@ def test_search_by_vector_rejects_document_id_with_trailing_newline(oceanbase_mo
"user_id\r\n", # trailing CRLF
],
)
-def test_get_ids_by_metadata_field_rejects_key_with_trailing_newline(oceanbase_module, bad_key):
+def test_get_ids_by_metadata_field_rejects_key_with_trailing_newline(
+ oceanbase_module: ModuleType, bad_key: str
+) -> None:
"""Regression for #39884 (sibling of #39234 / #39548 / #39666 / #39730 / #39880).
The old `re.match(r"^[a-zA-Z0-9_.]+$", key)` accepted a key ending in `\n`.
diff --git a/api/providers/vdb/vdb-pgvecto-rs/tests/unit_tests/src/dify_vdb_pgvecto_rs/test_pgvecto_rs.py b/api/providers/vdb/vdb-pgvecto-rs/tests/unit_tests/src/dify_vdb_pgvecto_rs/test_pgvecto_rs.py
index 436df5525ad..74f5e7e285c 100644
--- a/api/providers/vdb/vdb-pgvecto-rs/tests/unit_tests/src/dify_vdb_pgvecto_rs/test_pgvecto_rs.py
+++ b/api/providers/vdb/vdb-pgvecto-rs/tests/unit_tests/src/dify_vdb_pgvecto_rs/test_pgvecto_rs.py
@@ -1,7 +1,9 @@
import importlib
import json
import sys
-from types import SimpleNamespace
+from collections.abc import Callable
+from types import ModuleType, SimpleNamespace
+from typing import Any, Self
from unittest.mock import MagicMock, patch
from uuid import UUID
@@ -14,12 +16,12 @@ from core.rag.models.document import Document
from models.dataset import Dataset
-def _build_fake_pgvecto_modules():
+def _build_fake_pgvecto_modules() -> dict[str, FakeModule]:
pgvecto_rs = FakeModule("pgvecto_rs")
pgvecto_rs_sqlalchemy = FakeModule("pgvecto_rs.sqlalchemy")
class VECTOR(UserDefinedType):
- def __init__(self, dim):
+ def __init__(self, dim: int) -> None:
self.dim = dim
pgvecto_rs_sqlalchemy.VECTOR = VECTOR
@@ -30,59 +32,70 @@ def _build_fake_pgvecto_modules():
class _FakeSessionContext:
- def __init__(self, calls, execute_results=None):
+ def __init__(
+ self, calls: list[tuple[tuple[Any, ...], dict[str, Any]]], execute_results: list[object] | None = None
+ ) -> None:
self.calls = calls
self.execute_results = execute_results or []
self.execute = MagicMock(side_effect=self._execute_side_effect)
self.commit = MagicMock()
- def _execute_side_effect(self, *args, **kwargs):
+ def _execute_side_effect(self, *args: object, **kwargs: object) -> object:
self.calls.append((args, kwargs))
if self.execute_results:
return self.execute_results.pop(0)
return MagicMock()
- def __enter__(self):
+ def __enter__(self) -> Self:
return self
- def __exit__(self, exc_type, exc, tb):
+ def __exit__(self, exc_type: object, exc: object, tb: object) -> None:
return None
-def _session_factory(calls, execute_results=None):
- def _session(_client):
+def _session_factory(
+ calls: list[tuple[tuple[Any, ...], dict[str, Any]]], execute_results: list[object] | None = None
+) -> Callable[[object], _FakeSessionContext]:
+ def _session(_client) -> _FakeSessionContext:
return _FakeSessionContext(calls=calls, execute_results=execute_results)
return _session
class _FakeBeginContext:
- def __init__(self, session):
+ def __init__(self, session: _FakeSessionContext) -> None:
self._session = session
- def __enter__(self):
+ def __enter__(self) -> _FakeSessionContext:
return self._session
- def __exit__(self, exc_type, exc, tb):
+ def __exit__(self, exc_type: object, exc: object, tb: object) -> None:
return None
-def _sessionmaker_factory(calls, execute_results=None):
- def _sessionmaker[**P](*args: P.args, **kwargs: P.kwargs):
+def _sessionmaker_factory(
+ calls: list[tuple[tuple[Any, ...], dict[str, Any]]], execute_results: list[object] | None = None
+) -> Callable[..., MagicMock]:
+ def _sessionmaker[**P](*args: P.args, **kwargs: P.kwargs) -> MagicMock:
session = _FakeSessionContext(calls=calls, execute_results=execute_results)
return MagicMock(begin=MagicMock(return_value=_FakeBeginContext(session)))
return _sessionmaker
-def _patch_both(monkeypatch, module, calls, execute_results=None):
+def _patch_both(
+ monkeypatch: pytest.MonkeyPatch,
+ module: ModuleType,
+ calls: list[tuple[tuple[Any, ...], dict[str, Any]]],
+ execute_results: list[object] | None = None,
+) -> None:
"""Patch both Session and sessionmaker on the module with the same call tracker."""
monkeypatch.setattr(module, "Session", _session_factory(calls, execute_results))
monkeypatch.setattr(module, "sessionmaker", _sessionmaker_factory(calls, execute_results))
@pytest.fixture
-def pgvecto_module(monkeypatch: pytest.MonkeyPatch):
+def pgvecto_module(monkeypatch: pytest.MonkeyPatch) -> tuple[ModuleType, ModuleType]:
for name, module in _build_fake_pgvecto_modules().items():
monkeypatch.setitem(sys.modules, name, module)
@@ -92,8 +105,8 @@ def pgvecto_module(monkeypatch: pytest.MonkeyPatch):
return importlib.reload(module), importlib.reload(collection_module)
-def _config(module, **overrides):
- values = {
+def _config(module: ModuleType, **overrides: object) -> Any:
+ values: dict[str, object] = {
"host": "localhost",
"port": 5432,
"user": "postgres",
@@ -114,7 +127,7 @@ def _config(module, **overrides):
("database", "", "config PGVECTO_RS_DATABASE is required"),
],
)
-def test_pgvecto_config_validation(pgvecto_module, field, value, message):
+def test_pgvecto_config_validation(pgvecto_module: ModuleType, field: str, value: str | int, message: str) -> None:
module, _ = pgvecto_module
values = _config(module).model_dump()
values[field] = value
@@ -123,13 +136,13 @@ def test_pgvecto_config_validation(pgvecto_module, field, value, message):
module.PgvectoRSConfig.model_validate(values)
-def test_collection_base_has_expected_annotations(pgvecto_module):
+def test_collection_base_has_expected_annotations(pgvecto_module: ModuleType) -> None:
_, collection_module = pgvecto_module
annotations = collection_module.CollectionORM.__annotations__
assert {"id", "text", "meta", "vector"} <= set(annotations)
-def test_init_get_type_and_create_delegate(pgvecto_module, monkeypatch: pytest.MonkeyPatch):
+def test_init_get_type_and_create_delegate(pgvecto_module: ModuleType, monkeypatch: pytest.MonkeyPatch) -> None:
module, _ = pgvecto_module
session_calls = []
monkeypatch.setattr(module, "create_engine", MagicMock(return_value="engine"))
@@ -148,7 +161,7 @@ def test_init_get_type_and_create_delegate(pgvecto_module, monkeypatch: pytest.M
vector.add_texts.assert_called_once_with(docs, [[0.1, 0.2]])
-def test_create_collection_cache_and_sql_execution(pgvecto_module, monkeypatch: pytest.MonkeyPatch):
+def test_create_collection_cache_and_sql_execution(pgvecto_module: ModuleType, monkeypatch: pytest.MonkeyPatch) -> None:
module, _ = pgvecto_module
session_calls = []
monkeypatch.setattr(module, "create_engine", MagicMock(return_value="engine"))
@@ -172,7 +185,7 @@ def test_create_collection_cache_and_sql_execution(pgvecto_module, monkeypatch:
module.redis_client.set.assert_called()
-def test_add_texts_get_ids_and_delete_methods(pgvecto_module, monkeypatch: pytest.MonkeyPatch):
+def test_add_texts_get_ids_and_delete_methods(pgvecto_module: ModuleType, monkeypatch: pytest.MonkeyPatch) -> None:
module, _ = pgvecto_module
init_calls = []
runtime_calls = []
@@ -185,10 +198,10 @@ def test_add_texts_get_ids_and_delete_methods(pgvecto_module, monkeypatch: pytes
_patch_both(monkeypatch, module, runtime_calls, execute_results=list(execute_results))
class _InsertBuilder:
- def __init__(self, table):
+ def __init__(self, table: object) -> None:
self.table = table
- def values(self, **kwargs):
+ def values(self, **kwargs: object) -> tuple[str, dict[str, object]]:
return ("insert", kwargs)
monkeypatch.setattr(module, "insert", lambda table: _InsertBuilder(table))
@@ -245,7 +258,7 @@ def test_add_texts_get_ids_and_delete_methods(pgvecto_module, monkeypatch: pytes
assert any("DROP TABLE IF EXISTS collection_1" in str(args[0]) for args, _ in runtime_calls)
-def test_text_exists_search_and_full_text(pgvecto_module, monkeypatch: pytest.MonkeyPatch):
+def test_text_exists_search_and_full_text(pgvecto_module: ModuleType, monkeypatch: pytest.MonkeyPatch) -> None:
module, _ = pgvecto_module
init_calls = []
monkeypatch.setattr(module, "create_engine", MagicMock(return_value="engine"))
@@ -268,35 +281,35 @@ def test_text_exists_search_and_full_text(pgvecto_module, monkeypatch: pytest.Mo
assert vector.text_exists("doc-1") is False
class _DistanceExpr:
- def label(self, _name):
+ def label(self, _name) -> Self:
return self
class _VectorColumn:
- def op(self, _operator, return_type=None):
- def _call(_query_vector):
+ def op(self, _operator, return_type: object = None) -> Callable[[object], _DistanceExpr]:
+ def _call(_query_vector) -> _DistanceExpr:
return _DistanceExpr()
return _call
class _MetaFilter:
- def in_(self, values):
+ def in_(self, values: object) -> tuple[str, object]:
return ("in", values)
class _MetaColumn:
- def __getitem__(self, _item):
+ def __getitem__(self, _item) -> _MetaFilter:
return _MetaFilter()
class _Stmt:
- def __init__(self):
+ def __init__(self) -> None:
self.where_called = False
- def limit(self, _value):
+ def limit(self, _value) -> Self:
return self
- def order_by(self, _value):
+ def order_by(self, _value) -> Self:
return self
- def where(self, _value):
+ def where(self, _value) -> Self:
self.where_called = True
return self
@@ -317,7 +330,9 @@ def test_text_exists_search_and_full_text(pgvecto_module, monkeypatch: pytest.Mo
assert vector.search_by_full_text("hello") == []
-def test_factory_uses_existing_or_generated_collection(pgvecto_module, monkeypatch: pytest.MonkeyPatch):
+def test_factory_uses_existing_or_generated_collection(
+ pgvecto_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
module, _ = pgvecto_module
factory = module.PGVectoRSFactory()
dataset_with_index = Dataset(