Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(test): 修复测试稳定性问题,清理废弃代码 (#353)

Qin Haojie4d7d2226582d
diff --git a/openviking/storage/collection_schemas.py b/openviking/storage/collection_schemas.py
index b12c8e66d..d095f3ba1 100644
--- a/openviking/storage/collection_schemas.py
+++ b/openviking/storage/collection_schemas.py
@@ -157,7 +157,7 @@ class TextEmbeddingHandler(DequeueHandlerBase):
embedding_msg = EmbeddingMsg.from_dict(queue_data)
inserted_data = embedding_msg.context_data
- if getattr(self._vikingdb, "is_closing", False):
+ if self._vikingdb.is_closing:
logger.debug("Skip embedding dequeue during shutdown")
self.report_success()
return None
@@ -219,7 +219,7 @@ class TextEmbeddingHandler(DequeueHandlerBase):
)
except CollectionNotFoundError as db_err:
# During shutdown, queue workers may finish one dequeued item.
- if getattr(self._vikingdb, "is_closing", False):
+ if self._vikingdb.is_closing:
logger.debug(f"Skip embedding write during shutdown: {db_err}")
self.report_success()
return None
@@ -227,7 +227,7 @@ class TextEmbeddingHandler(DequeueHandlerBase):
self.report_error(str(db_err), data)
return None
except Exception as db_err:
- if getattr(self._vikingdb, "is_closing", False):
+ if self._vikingdb.is_closing:
logger.debug(f"Skip embedding write during shutdown: {db_err}")
self.report_success()
return None
diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.py
index 0c1c09f8f..64768ea85 100644
--- a/openviking/storage/viking_vector_index_backend.py
+++ b/openviking/storage/viking_vector_index_backend.py
@@ -583,6 +583,11 @@ class VikingVectorIndexBackend:
"error": str(e),
}
+ @property
+ def is_closing(self) -> bool:
+ """Whether the backend is in shutdown flow. Always False for the base class."""
+ return False
+
@property
def mode(self) -> str:
return self._mode
diff --git a/pyproject.toml b/pyproject.toml
index 901869726..00a5f2f50 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -74,6 +74,9 @@ test = [
"pytest-asyncio>=0.21.0",
"boto3>=1.42.44",
"pytest-cov>=4.0.0",
+ "ragas>=0.1.0",
+ "datasets>=2.0.0",
+ "pandas>=2.0.0",
]
dev = [
"mypy>=1.0.0",
diff --git a/tests/agfs/test_fs_binding.py b/tests/agfs/test_fs_binding.py
index 55986f829..cf71d44b0 100644
--- a/tests/agfs/test_fs_binding.py
+++ b/tests/agfs/test_fs_binding.py
@@ -70,6 +70,9 @@ async def viking_fs_binding_instance():
# Initialize VikingFS with client
vfs = init_viking_fs(agfs=agfs_client)
+ # Ensure test directory exists
+ await vfs.mkdir("viking://temp/", exist_ok=True)
+
yield vfs
diff --git a/tests/cli/conftest.py b/tests/cli/conftest.py
index a28f9968f..9e1f0c2c2 100644
--- a/tests/cli/conftest.py
+++ b/tests/cli/conftest.py
@@ -55,12 +55,11 @@ def openviking_server(tmp_path_factory: pytest.TempPathFactory) -> Generator[str
conf_data["server"]["port"] = port
conf_data.setdefault("storage", {})
+ conf_data["storage"]["workspace"] = str(storage_dir)
conf_data["storage"].setdefault("vectordb", {})
conf_data["storage"]["vectordb"]["backend"] = "local"
- conf_data["storage"]["vectordb"]["path"] = str(storage_dir)
conf_data["storage"].setdefault("agfs", {})
conf_data["storage"]["agfs"]["backend"] = "local"
- conf_data["storage"]["agfs"]["path"] = str(storage_dir)
# Write temporary ov.conf
tmp_conf = storage_dir / "ov.conf"
@@ -92,10 +91,22 @@ def openviking_server(tmp_path_factory: pytest.TempPathFactory) -> Generator[str
try:
_wait_for_health(url)
yield url
+ except RuntimeError:
+ # Capture server output for debugging
+ stdout, stderr = "", ""
+ if proc.poll() is not None:
+ stdout, stderr = proc.communicate(timeout=5)
+ else:
+ proc.terminate()
+ stdout, stderr = proc.communicate(timeout=10)
+ raise RuntimeError(
+ f"OpenViking server failed to start.\nstdout:\n{stdout}\nstderr:\n{stderr}"
+ )
finally:
- proc.terminate()
- try:
- proc.wait(timeout=10)
- except subprocess.TimeoutExpired:
- proc.kill()
- proc.wait(timeout=10)
+ if proc.poll() is None:
+ proc.terminate()
+ try:
+ proc.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait(timeout=10)
diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.py
index 8edf7b484..47a8ef80b 100644
--- a/tests/cli/test_cli.py
+++ b/tests/cli/test_cli.py
@@ -183,7 +183,7 @@ def test_cli_real_requests(openviking_server, tmp_path):
_run_cli(["overview", "viking://resources"], server_url)
# -- search --
- _run_cli(["grep", root_uri, "OpenViking"], server_url)
+ _run_cli(["grep", "OpenViking", "--uri", root_uri], server_url)
_run_cli(["glob", "*.txt", "--uri", root_uri], server_url)
_run_cli(["search", "OpenViking", "--uri", root_uri], server_url)
diff --git a/tests/misc/test_port_check.py b/tests/misc/test_port_check.py
index e6960dc1a..1c7ac7e6b 100644
--- a/tests/misc/test_port_check.py
+++ b/tests/misc/test_port_check.py
@@ -55,10 +55,15 @@ class TestCheckPortAvailable:
mgr = _make_manager(port)
try:
+ # Flush any ResourceWarnings accumulated from previous tests
+ with warnings.catch_warnings(record=True):
+ warnings.simplefilter("always", ResourceWarning)
+ gc.collect()
+
with pytest.raises(RuntimeError):
mgr._check_port_available()
- # Force GC and check for ResourceWarning about unclosed socket
+ # Now check only for new ResourceWarnings from _check_port_available
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", ResourceWarning)
gc.collect()
diff --git a/tests/server/conftest.py b/tests/server/conftest.py
index 4ed3586e0..c38c7eab4 100644
--- a/tests/server/conftest.py
+++ b/tests/server/conftest.py
@@ -51,11 +51,13 @@ This is a sample markdown document for server testing.
@pytest.fixture(scope="function")
def temp_dir():
- """Create temp directory, auto-cleanup."""
- shutil.rmtree(TEST_TMP_DIR, ignore_errors=True)
- TEST_TMP_DIR.mkdir(parents=True, exist_ok=True)
- yield TEST_TMP_DIR
- shutil.rmtree(TEST_TMP_DIR, ignore_errors=True)
+ """Create a unique temp directory per test, auto-cleanup."""
+ import uuid
+
+ unique_dir = TEST_TMP_DIR / uuid.uuid4().hex[:8]
+ unique_dir.mkdir(parents=True, exist_ok=True)
+ yield unique_dir
+ shutil.rmtree(unique_dir, ignore_errors=True)
@pytest.fixture(scope="function")
diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.py
index 4a66d32d3..a819be19d 100644
--- a/tests/server/test_admin_api.py
+++ b/tests/server/test_admin_api.py
@@ -3,6 +3,8 @@
"""Tests for Admin API endpoints (openviking/server/routers/admin.py)."""
+import uuid
+
import httpx
import pytest_asyncio
@@ -13,6 +15,11 @@ from openviking.server.dependencies import set_service
from openviking.service.core import OpenVikingService
from openviking_cli.session.user_id import UserIdentifier
+
+def _uid() -> str:
+ return f"acme_{uuid.uuid4().hex[:8]}"
+
+
ROOT_KEY = "admin-api-test-root-key-abcdef1234567890ab"
@@ -55,23 +62,25 @@ def root_headers():
async def test_create_account(admin_client: httpx.AsyncClient):
"""ROOT can create an account with first admin."""
+ acct = _uid()
resp = await admin_client.post(
"/api/v1/admin/accounts",
- json={"account_id": "acme", "admin_user_id": "alice"},
+ json={"account_id": acct, "admin_user_id": "alice"},
headers=root_headers(),
)
assert resp.status_code == 200
body = resp.json()
- assert body["result"]["account_id"] == "acme"
+ assert body["result"]["account_id"] == acct
assert body["result"]["admin_user_id"] == "alice"
assert "user_key" in body["result"]
async def test_list_accounts(admin_client: httpx.AsyncClient):
"""ROOT can list all accounts."""
+ acct = _uid()
await admin_client.post(
"/api/v1/admin/accounts",
- json={"account_id": "acme", "admin_user_id": "alice"},
+ json={"account_id": acct, "admin_user_id": "alice"},
headers=root_headers(),
)
resp = await admin_client.get("/api/v1/admin/accounts", headers=root_headers())
@@ -79,19 +88,20 @@ async def test_list_accounts(admin_client: httpx.AsyncClient):
accounts = resp.json()["result"]
account_ids = {a["account_id"] for a in accounts}
assert "default" in account_ids
- assert "acme" in account_ids
+ assert acct in account_ids
async def test_delete_account(admin_client: httpx.AsyncClient):
"""ROOT can delete an account."""
+ acct = _uid()
resp = await admin_client.post(
"/api/v1/admin/accounts",
- json={"account_id": "acme", "admin_user_id": "alice"},
+ json={"account_id": acct, "admin_user_id": "alice"},
headers=root_headers(),
)
user_key = resp.json()["result"]["user_key"]
- resp = await admin_client.delete("/api/v1/admin/accounts/acme", headers=root_headers())
+ resp = await admin_client.delete(f"/api/v1/admin/accounts/{acct}", headers=root_headers())
assert resp.status_code == 200
assert resp.json()["result"]["deleted"] is True
@@ -105,14 +115,15 @@ async def test_delete_account(admin_client: httpx.AsyncClient):
async def test_create_duplicate_account_fails(admin_client: httpx.AsyncClient):
"""Creating duplicate account should fail."""
+ acct = _uid()
await admin_client.post(
"/api/v1/admin/accounts",
- json={"account_id": "acme", "admin_user_id": "alice"},
+ json={"account_id": acct, "admin_user_id": "alice"},
headers=root_headers(),
)
resp = await admin_client.post(
"/api/v1/admin/accounts",
- json={"account_id": "acme", "admin_user_id": "bob"},
+ json={"account_id": acct, "admin_user_id": "bob"},
headers=root_headers(),
)
assert resp.status_code == 409 # ALREADY_EXISTS
@@ -123,13 +134,14 @@ async def test_create_duplicate_account_fails(admin_client: httpx.AsyncClient):
async def test_register_user(admin_client: httpx.AsyncClient):
"""ROOT can register a user in an account."""
+ acct = _uid()
await admin_client.post(
"/api/v1/admin/accounts",
- json={"account_id": "acme", "admin_user_id": "alice"},
+ json={"account_id": acct, "admin_user_id": "alice"},
headers=root_headers(),
)
resp = await admin_client.post(
- "/api/v1/admin/accounts/acme/users",
+ f"/api/v1/admin/accounts/{acct}/users",
json={"user_id": "bob", "role": "user"},
headers=root_headers(),
)
@@ -149,15 +161,16 @@ async def test_register_user(admin_client: httpx.AsyncClient):
async def test_admin_can_register_user_in_own_account(admin_client: httpx.AsyncClient):
"""ADMIN can register users in their own account."""
+ acct = _uid()
resp = await admin_client.post(
"/api/v1/admin/accounts",
- json={"account_id": "acme", "admin_user_id": "alice"},
+ json={"account_id": acct, "admin_user_id": "alice"},
headers=root_headers(),
)
alice_key = resp.json()["result"]["user_key"]
resp = await admin_client.post(
- "/api/v1/admin/accounts/acme/users",
+ f"/api/v1/admin/accounts/{acct}/users",
json={"user_id": "bob", "role": "user"},
headers={"X-API-Key": alice_key},
)
@@ -166,21 +179,23 @@ async def test_admin_can_register_user_in_own_account(admin_client: httpx.AsyncC
async def test_admin_cannot_register_user_in_other_account(admin_client: httpx.AsyncClient):
"""ADMIN cannot register users in another account."""
+ acct = _uid()
+ other = _uid()
resp = await admin_client.post(
"/api/v1/admin/accounts",
- json={"account_id": "acme", "admin_user_id": "alice"},
+ json={"account_id": acct, "admin_user_id": "alice"},
headers=root_headers(),
)
alice_key = resp.json()["result"]["user_key"]
await admin_client.post(
"/api/v1/admin/accounts",
- json={"account_id": "other_corp", "admin_user_id": "eve"},
+ json={"account_id": other, "admin_user_id": "eve"},
headers=root_headers(),
)
resp = await admin_client.post(
- "/api/v1/admin/accounts/other_corp/users",
+ f"/api/v1/admin/accounts/{other}/users",
json={"user_id": "bob", "role": "user"},
headers={"X-API-Key": alice_key},
)
@@ -189,17 +204,18 @@ async def test_admin_cannot_register_user_in_other_account(admin_client: httpx.A
async def test_list_users(admin_client: httpx.AsyncClient):
"""ROOT can list users in an account."""
+ acct = _uid()
await admin_client.post(
"/api/v1/admin/accounts",
- json={"account_id": "acme", "admin_user_id": "alice"},
+ json={"account_id": acct, "admin_user_id": "alice"},
headers=root_headers(),
)
await admin_client.post(
- "/api/v1/admin/accounts/acme/users",
+ f"/api/v1/admin/accounts/{acct}/users",
json={"user_id": "bob", "role": "user"},
headers=root_headers(),
)
- resp = await admin_client.get("/api/v1/admin/accounts/acme/users", headers=root_headers())
+ resp = await admin_client.get(f"/api/v1/admin/accounts/{acct}/users", headers=root_headers())
assert resp.status_code == 200
users = resp.json()["result"]
user_ids = {u["user_id"] for u in users}
@@ -208,20 +224,21 @@ async def test_list_users(admin_client: httpx.AsyncClient):
async def test_remove_user(admin_client: httpx.AsyncClient):
"""ROOT can remove a user."""
+ acct = _uid()
await admin_client.post(
"/api/v1/admin/accounts",
- json={"account_id": "acme", "admin_user_id": "alice"},
+ json={"account_id": acct, "admin_user_id": "alice"},
headers=root_headers(),
)
resp = await admin_client.post(
- "/api/v1/admin/accounts/acme/users",
+ f"/api/v1/admin/accounts/{acct}/users",
json={"user_id": "bob", "role": "user"},
headers=root_headers(),
)
bob_key = resp.json()["result"]["user_key"]
resp = await admin_client.delete(
- "/api/v1/admin/accounts/acme/users/bob", headers=root_headers()
+ f"/api/v1/admin/accounts/{acct}/users/bob", headers=root_headers()
)
assert resp.status_code == 200
@@ -238,18 +255,19 @@ async def test_remove_user(admin_client: httpx.AsyncClient):
async def test_set_role(admin_client: httpx.AsyncClient):
"""ROOT can change a user's role."""
+ acct = _uid()
await admin_client.post(
"/api/v1/admin/accounts",
- json={"account_id": "acme", "admin_user_id": "alice"},
+ json={"account_id": acct, "admin_user_id": "alice"},
headers=root_headers(),
)
await admin_client.post(
- "/api/v1/admin/accounts/acme/users",
+ f"/api/v1/admin/accounts/{acct}/users",
json={"user_id": "bob", "role": "user"},
headers=root_headers(),
)
resp = await admin_client.put(
- "/api/v1/admin/accounts/acme/users/bob/role",
+ f"/api/v1/admin/accounts/{acct}/users/bob/role",
json={"role": "admin"},
headers=root_headers(),
)
@@ -259,20 +277,21 @@ async def test_set_role(admin_client: httpx.AsyncClient):
async def test_regenerate_key(admin_client: httpx.AsyncClient):
"""ROOT can regenerate a user's key."""
+ acct = _uid()
await admin_client.post(
"/api/v1/admin/accounts",
- json={"account_id": "acme", "admin_user_id": "alice"},
+ json={"account_id": acct, "admin_user_id": "alice"},
headers=root_headers(),
)
resp = await admin_client.post(
- "/api/v1/admin/accounts/acme/users",
+ f"/api/v1/admin/accounts/{acct}/users",
json={"user_id": "bob", "role": "user"},
headers=root_headers(),
)
old_key = resp.json()["result"]["user_key"]
resp = await admin_client.post(
- "/api/v1/admin/accounts/acme/users/bob/key",
+ f"/api/v1/admin/accounts/{acct}/users/bob/key",
headers=root_headers(),
)
assert resp.status_code == 200
@@ -299,13 +318,14 @@ async def test_regenerate_key(admin_client: httpx.AsyncClient):
async def test_user_role_cannot_access_admin_api(admin_client: httpx.AsyncClient):
"""USER role should not access admin endpoints."""
+ acct = _uid()
await admin_client.post(
"/api/v1/admin/accounts",
- json={"account_id": "acme", "admin_user_id": "alice"},
+ json={"account_id": acct, "admin_user_id": "alice"},
headers=root_headers(),
)
resp = await admin_client.post(
- "/api/v1/admin/accounts/acme/users",
+ f"/api/v1/admin/accounts/{acct}/users",
json={"user_id": "bob", "role": "user"},
headers=root_headers(),
)
@@ -313,7 +333,7 @@ async def test_user_role_cannot_access_admin_api(admin_client: httpx.AsyncClient
# USER cannot register users
resp = await admin_client.post(
- "/api/v1/admin/accounts/acme/users",
+ f"/api/v1/admin/accounts/{acct}/users",
json={"user_id": "charlie", "role": "user"},
headers={"X-API-Key": bob_key},
)
diff --git a/tests/server/test_api_key_manager.py b/tests/server/test_api_key_manager.py
index b2badd136..9b5e2e235 100644
--- a/tests/server/test_api_key_manager.py
+++ b/tests/server/test_api_key_manager.py
@@ -3,6 +3,8 @@
"""Tests for APIKeyManager (openviking/server/api_keys.py)."""
+import uuid
+
import pytest
import pytest_asyncio
@@ -12,6 +14,12 @@ from openviking.service.core import OpenVikingService
from openviking_cli.exceptions import AlreadyExistsError, NotFoundError, UnauthenticatedError
from openviking_cli.session.user_id import UserIdentifier
+
+def _uid() -> str:
+ """Generate a unique account name to avoid cross-test collisions."""
+ return f"acme_{uuid.uuid4().hex[:8]}"
+
+
ROOT_KEY = "test-root-key-abcdef1234567890abcdef1234567890"
@@ -62,30 +70,33 @@ async def test_resolve_empty_key_raises(manager: APIKeyManager):
async def test_create_account(manager: APIKeyManager):
"""create_account should create workspace + first admin user."""
- key = await manager.create_account("acme", "alice")
+ acct = _uid()
+ key = await manager.create_account(acct, "alice")
assert isinstance(key, str)
assert len(key) == 64 # hex(32)
identity = manager.resolve(key)
assert identity.role == Role.ADMIN
- assert identity.account_id == "acme"
+ assert identity.account_id == acct
assert identity.user_id == "alice"
async def test_create_duplicate_account_raises(manager: APIKeyManager):
"""Creating duplicate account should raise AlreadyExistsError."""
- await manager.create_account("acme", "alice")
+ acct = _uid()
+ await manager.create_account(acct, "alice")
with pytest.raises(AlreadyExistsError):
- await manager.create_account("acme", "bob")
+ await manager.create_account(acct, "bob")
async def test_delete_account(manager: APIKeyManager):
"""Deleting account should invalidate all its user keys."""
- key = await manager.create_account("acme", "alice")
+ acct = _uid()
+ key = await manager.create_account(acct, "alice")
identity = manager.resolve(key)
- assert identity.account_id == "acme"
+ assert identity.account_id == acct
- await manager.delete_account("acme")
+ await manager.delete_account(acct)
with pytest.raises(UnauthenticatedError):
manager.resolve(key)
@@ -107,20 +118,22 @@ async def test_default_account_exists(manager: APIKeyManager):
async def test_register_user(manager: APIKeyManager):
"""register_user should create a user with given role."""
- await manager.create_account("acme", "alice")
- key = await manager.register_user("acme", "bob", "user")
+ acct = _uid()
+ await manager.create_account(acct, "alice")
+ key = await manager.register_user(acct, "bob", "user")
identity = manager.resolve(key)
assert identity.role == Role.USER
- assert identity.account_id == "acme"
+ assert identity.account_id == acct
assert identity.user_id == "bob"
async def test_register_duplicate_user_raises(manager: APIKeyManager):
"""Registering duplicate user should raise AlreadyExistsError."""
- await manager.create_account("acme", "alice")
+ acct = _uid()
+ await manager.create_account(acct, "alice")
with pytest.raises(AlreadyExistsError):
- await manager.register_user("acme", "alice", "user")
+ await manager.register_user(acct, "alice", "user")
async def test_register_user_in_nonexistent_account_raises(manager: APIKeyManager):
@@ -131,23 +144,25 @@ async def test_register_user_in_nonexistent_account_raises(manager: APIKeyManage
async def test_remove_user(manager: APIKeyManager):
"""Removing user should invalidate their key."""
- await manager.create_account("acme", "alice")
- bob_key = await manager.register_user("acme", "bob", "user")
+ acct = _uid()
+ await manager.create_account(acct, "alice")
+ bob_key = await manager.register_user(acct, "bob", "user")
identity = manager.resolve(bob_key)
assert identity.user_id == "bob"
- await manager.remove_user("acme", "bob")
+ await manager.remove_user(acct, "bob")
with pytest.raises(UnauthenticatedError):
manager.resolve(bob_key)
async def test_regenerate_key(manager: APIKeyManager):
"""Regenerating key should invalidate old key and return new valid key."""
- await manager.create_account("acme", "alice")
- old_key = await manager.register_user("acme", "bob", "user")
+ acct = _uid()
+ await manager.create_account(acct, "alice")
+ old_key = await manager.register_user(acct, "bob", "user")
- new_key = await manager.regenerate_key("acme", "bob")
+ new_key = await manager.regenerate_key(acct, "bob")
assert new_key != old_key
# Old key invalid
@@ -157,26 +172,28 @@ async def test_regenerate_key(manager: APIKeyManager):
# New key valid
identity = manager.resolve(new_key)
assert identity.user_id == "bob"
- assert identity.account_id == "acme"
+ assert identity.account_id == acct
async def test_set_role(manager: APIKeyManager):
"""set_role should update user's role in both storage and index."""
- await manager.create_account("acme", "alice")
- bob_key = await manager.register_user("acme", "bob", "user")
+ acct = _uid()
+ await manager.create_account(acct, "alice")
+ bob_key = await manager.register_user(acct, "bob", "user")
assert manager.resolve(bob_key).role == Role.USER
- await manager.set_role("acme", "bob", "admin")
+ await manager.set_role(acct, "bob", "admin")
assert manager.resolve(bob_key).role == Role.ADMIN
async def test_get_users(manager: APIKeyManager):
"""get_users should list all users in an account."""
- await manager.create_account("acme", "alice")
- await manager.register_user("acme", "bob", "user")
+ acct = _uid()
+ await manager.create_account(acct, "alice")
+ await manager.register_user(acct, "bob", "user")
- users = manager.get_users("acme")
+ users = manager.get_users(acct)
user_ids = {u["user_id"] for u in users}
assert user_ids == {"alice", "bob"}
@@ -193,13 +210,14 @@ async def test_persistence_across_reload(manager_service):
mgr1 = APIKeyManager(root_key=ROOT_KEY, agfs_url=manager_service._agfs_url)
await mgr1.load()
- key = await mgr1.create_account("acme", "alice")
+ acct = _uid()
+ key = await mgr1.create_account(acct, "alice")
# Create new manager instance and reload
mgr2 = APIKeyManager(root_key=ROOT_KEY, agfs_url=manager_service._agfs_url)
await mgr2.load()
identity = mgr2.resolve(key)
- assert identity.account_id == "acme"
+ assert identity.account_id == acct
assert identity.user_id == "alice"
assert identity.role == Role.ADMIN
diff --git a/tests/server/test_auth.py b/tests/server/test_auth.py
index ce919e44e..849bc2a36 100644
--- a/tests/server/test_auth.py
+++ b/tests/server/test_auth.py
@@ -3,6 +3,8 @@
"""Tests for multi-tenant authentication (openviking/server/auth.py)."""
+import uuid
+
import httpx
import pytest
import pytest_asyncio
@@ -13,6 +15,11 @@ from openviking.server.dependencies import set_service
from openviking.service.core import OpenVikingService
from openviking_cli.session.user_id import UserIdentifier
+
+def _uid() -> str:
+ return f"acct_{uuid.uuid4().hex[:8]}"
+
+
ROOT_KEY = "root-secret-key-for-testing-only-1234567890abcdef"
@@ -56,7 +63,7 @@ async def auth_client(auth_app):
async def user_key(auth_app):
"""Create a test user and return its key."""
manager = auth_app.state.api_key_manager
- key = await manager.create_account("test_account", "test_admin")
+ key = await manager.create_account(_uid(), "test_admin")
return key
@@ -173,8 +180,8 @@ async def test_agent_id_header_forwarded(auth_client: httpx.AsyncClient):
async def test_cross_tenant_session_get_returns_not_found(auth_client: httpx.AsyncClient, auth_app):
"""A user must not access another tenant's session by session_id."""
manager = auth_app.state.api_key_manager
- alice_key = await manager.create_account("acme", "alice")
- bob_key = await manager.create_account("beta", "bob")
+ alice_key = await manager.create_account(_uid(), "alice")
+ bob_key = await manager.create_account(_uid(), "bob")
create_resp = await auth_client.post(
"/api/v1/sessions", json={}, headers={"X-API-Key": alice_key}
diff --git a/tests/test_edge_cases.py b/tests/test_edge_cases.py
index f6bd2702d..20e7e6bee 100644
--- a/tests/test_edge_cases.py
+++ b/tests/test_edge_cases.py
@@ -29,7 +29,6 @@ from openviking.parse.parsers.upload_utils import ( # noqa: I001
is_text_file,
upload_directory,
)
-from openviking.utils.compression import CompressManager
from openviking_cli.utils.uri import VikingURI
@@ -135,7 +134,7 @@ class TestLongFilenames:
assert ".txt" in sanitized # Extension should be preserved
def test_filename_with_path_traversal_attempts(self):
- """Test filename containing path traversal sequences."""
+ """Test filename containing path traversal sequences are rejected."""
dangerous_filenames = [
"../../../etc/passwd",
"..\\..\\windows\\system32\\config",
@@ -144,10 +143,8 @@ class TestLongFilenames:
]
for filename in dangerous_filenames:
- sanitized = _sanitize_rel_path(filename)
- # Should not contain path traversal sequences
- assert ".." not in sanitized
- assert "\\" not in sanitized or sanitized.count("\\") == 0
+ with pytest.raises(ValueError, match="Unsafe relative path rejected"):
+ _sanitize_rel_path(filename)
class TestSearchByIdEdgeCases:
@@ -268,64 +265,6 @@ class TestDuplicateFilenameHandling:
assert sanitized_nfd is not None
-class TestCompressionEdgeCases:
- """Test compression with various edge cases."""
-
- def test_compress_empty_string(self):
- """Test compressing empty string."""
- compressor = CompressManager()
-
- empty_text = ""
- compressed = compressor.compress_text(empty_text)
-
- assert compressed is not None
- assert len(compressed) >= 0 # May be empty or minimal header
-
- def test_compress_emoji_only(self):
- """Test compressing string containing only emoji."""
- compressor = CompressManager()
-
- emoji_text = "😀😃😄😁😆😅😂🤣😊😇🙂🙃😉😌😍🥰😘😗😙😚"
- compressed = compressor.compress_text(emoji_text)
-
- assert compressed is not None
- # Emoji compression ratio might be poor due to lack of repetition
- assert len(compressed) > 0
-
- def test_compress_large_text(self):
- """Test compressing 1MB of text."""
- compressor = CompressManager()
-
- # Generate ~1MB of text with patterns (should compress well)
- large_text = "This is a repeating pattern for compression testing. " * 20000
-
- assert len(large_text.encode("utf-8")) > 1_000_000
-
- compressed = compressor.compress_text(large_text)
-
- assert compressed is not None
- # Should achieve significant compression due to repetition
- compression_ratio = len(compressed) / len(large_text.encode("utf-8"))
- assert compression_ratio < 0.1 # Should compress to less than 10%
-
- def test_compress_binary_like_data(self):
- """Test compressing text that looks like binary data."""
- compressor = CompressManager()
-
- # Pseudo-random looking text (poor compression expected)
- import hashlib
-
- binary_like = ""
- for i in range(1000):
- binary_like += hashlib.md5(f"seed{i}".encode()).hexdigest()
-
- compressed = compressor.compress_text(binary_like)
- assert compressed is not None
- # Compression ratio should be poor for random-looking data
- compression_ratio = len(compressed) / len(binary_like.encode("utf-8"))
- assert compression_ratio > 0.8 # Should not compress much
-
-
class TestConcurrentOperations:
"""Test concurrent operations for race conditions and thread safety."""