Skip to content

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

test: add comprehensive unit tests for core utilities (#990)

冰水泡枸杞3258acd2b2c1
diff --git a/tests/unit/test_circuit_breaker.py b/tests/unit/test_circuit_breaker.py
new file mode 100644
index 000000000..0528abc0f
--- /dev/null
+++ b/tests/unit/test_circuit_breaker.py
@@ -0,0 +1,335 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Comprehensive tests for circuit breaker utility."""
+
+import time
+
+import pytest
+
+from openviking.utils.circuit_breaker import (
+ CircuitBreaker,
+ CircuitBreakerOpen,
+ classify_api_error,
+)
+
+
+class TestClassifyApiError:
+ """Test API error classification."""
+
+ def test_classify_403_as_permanent(self):
+ """Test 403 Forbidden is classified as permanent."""
+ error = Exception("403 Forbidden")
+ assert classify_api_error(error) == "permanent"
+
+ def test_classify_401_as_permanent(self):
+ """Test 401 Unauthorized is classified as permanent."""
+ error = Exception("401 Unauthorized")
+ assert classify_api_error(error) == "permanent"
+
+ def test_classify_forbidden_as_permanent(self):
+ """Test 'Forbidden' string is classified as permanent."""
+ error = Exception("Access Forbidden")
+ assert classify_api_error(error) == "permanent"
+
+ def test_classify_unauthorized_as_permanent(self):
+ """Test 'Unauthorized' string is classified as permanent."""
+ error = Exception("Unauthorized access")
+ assert classify_api_error(error) == "permanent"
+
+ def test_classify_account_overdue_as_permanent(self):
+ """Test 'AccountOverdue' string is classified as permanent."""
+ error = Exception("AccountOverdue error")
+ assert classify_api_error(error) == "permanent"
+
+ def test_classify_429_as_transient(self):
+ """Test 429 TooManyRequests is classified as transient."""
+ error = Exception("429 TooManyRequests")
+ assert classify_api_error(error) == "transient"
+
+ def test_classify_500_as_transient(self):
+ """Test 500 Internal Server Error is classified as transient."""
+ error = Exception("500 Internal Server Error")
+ assert classify_api_error(error) == "transient"
+
+ def test_classify_502_as_transient(self):
+ """Test 502 Bad Gateway is classified as transient."""
+ error = Exception("502 Bad Gateway")
+ assert classify_api_error(error) == "transient"
+
+ def test_classify_503_as_transient(self):
+ """Test 503 Service Unavailable is classified as transient."""
+ error = Exception("503 Service Unavailable")
+ assert classify_api_error(error) == "transient"
+
+ def test_classify_504_as_transient(self):
+ """Test 504 Gateway Timeout is classified as transient."""
+ error = Exception("504 Gateway Timeout")
+ assert classify_api_error(error) == "transient"
+
+ def test_classify_rate_limit_as_transient(self):
+ """Test 'RateLimit' string is classified as transient."""
+ error = Exception("RateLimit exceeded")
+ assert classify_api_error(error) == "transient"
+
+ def test_classify_timeout_as_transient(self):
+ """Test 'timeout' string is classified as transient."""
+ error = Exception("Connection timeout")
+ assert classify_api_error(error) == "transient"
+
+ def test_classify_connection_error_as_transient(self):
+ """Test 'ConnectionError' string is classified as transient."""
+ error = Exception("ConnectionError: Connection refused")
+ assert classify_api_error(error) == "transient"
+
+ def test_classify_connection_refused_as_transient(self):
+ """Test 'Connection refused' string is classified as transient."""
+ error = Exception("Connection refused by server")
+ assert classify_api_error(error) == "transient"
+
+ def test_classify_connection_reset_as_transient(self):
+ """Test 'Connection reset' string is classified as transient."""
+ error = Exception("Connection reset by peer")
+ assert classify_api_error(error) == "transient"
+
+ def test_classify_unknown_error(self):
+ """Test unknown error type is classified as unknown."""
+ error = Exception("Some random error")
+ assert classify_api_error(error) == "unknown"
+
+ def test_classify_error_with_cause(self):
+ """Test classification checks error cause."""
+ error = Exception("Primary error")
+ error.__cause__ = Exception("403 Forbidden")
+ assert classify_api_error(error) == "permanent"
+
+ def test_classify_error_with_transient_cause(self):
+ """Test classification checks error cause for transient."""
+ error = Exception("Primary error")
+ error.__cause__ = Exception("429 Rate limit")
+ assert classify_api_error(error) == "transient"
+
+ def test_permanent_takes_precedence_over_transient(self):
+ """Test permanent error patterns are checked first."""
+ error = Exception("403 Forbidden 429 timeout")
+ assert classify_api_error(error) == "permanent"
+
+
+class TestCircuitBreaker:
+ """Test CircuitBreaker class."""
+
+ def test_initial_state_is_closed(self):
+ """Test circuit breaker starts in CLOSED state."""
+ cb = CircuitBreaker()
+ cb.check() # Should not raise
+
+ def test_record_success_keeps_closed(self):
+ """Test recording success keeps breaker closed."""
+ cb = CircuitBreaker()
+ cb.record_success()
+ cb.check() # Should not raise
+
+ def test_trip_on_threshold(self):
+ """Test breaker trips after reaching failure threshold."""
+ cb = CircuitBreaker(failure_threshold=3)
+
+ # Record 3 failures
+ for _ in range(3):
+ cb.record_failure(Exception("500 Error"))
+
+ with pytest.raises(CircuitBreakerOpen):
+ cb.check()
+
+ def test_no_trip_before_threshold(self):
+ """Test breaker doesn't trip before threshold."""
+ cb = CircuitBreaker(failure_threshold=5)
+
+ # Record 4 failures (below threshold)
+ for _ in range(4):
+ cb.record_failure(Exception("500 Error"))
+
+ cb.check() # Should not raise
+
+ def test_trip_immediately_on_permanent_error(self):
+ """Test breaker trips immediately on permanent error."""
+ cb = CircuitBreaker(failure_threshold=10)
+
+ # Single permanent error should trip immediately
+ cb.record_failure(Exception("403 Forbidden"))
+
+ with pytest.raises(CircuitBreakerOpen):
+ cb.check()
+
+ def test_success_resets_failure_count(self):
+ """Test success resets failure count."""
+ cb = CircuitBreaker(failure_threshold=3)
+
+ # Record 2 failures
+ cb.record_failure(Exception("500 Error"))
+ cb.record_failure(Exception("500 Error"))
+
+ # Success should reset count
+ cb.record_success()
+
+ # Now 2 more failures shouldn't trip (count reset to 0)
+ cb.record_failure(Exception("500 Error"))
+ cb.record_failure(Exception("500 Error"))
+
+ cb.check() # Should not raise
+
+ def test_half_open_allows_probe(self):
+ """Test HALF_OPEN state allows probe request."""
+ cb = CircuitBreaker(failure_threshold=1, reset_timeout=0.1)
+
+ # Trip the breaker
+ cb.record_failure(Exception("500 Error"))
+
+ # Wait for reset timeout
+ time.sleep(0.15)
+
+ # Should transition to HALF_OPEN and allow probe
+ cb.check() # Should not raise
+
+ def test_half_open_to_closed_on_success(self):
+ """Test HALF_OPEN transitions to CLOSED on success."""
+ cb = CircuitBreaker(failure_threshold=1, reset_timeout=0.1)
+
+ # Trip the breaker
+ cb.record_failure(Exception("500 Error"))
+ time.sleep(0.15)
+
+ # Transition to HALF_OPEN
+ cb.check()
+
+ # Success should close the breaker
+ cb.record_success()
+
+ # Should be closed now
+ cb.check() # Should not raise
+
+ def test_half_open_to_open_on_failure(self):
+ """Test HALF_OPEN transitions back to OPEN on failure."""
+ cb = CircuitBreaker(failure_threshold=1, reset_timeout=0.1)
+
+ # Trip the breaker
+ cb.record_failure(Exception("500 Error"))
+ time.sleep(0.15)
+
+ # Transition to HALF_OPEN
+ cb.check()
+
+ # Failure should reopen
+ cb.record_failure(Exception("500 Error"))
+
+ with pytest.raises(CircuitBreakerOpen):
+ cb.check()
+
+ def test_retry_after_returns_remaining_time(self):
+ """Test retry_after returns remaining time when OPEN."""
+ cb = CircuitBreaker(failure_threshold=1, reset_timeout=10.0)
+
+ # Trip the breaker
+ cb.record_failure(Exception("500 Error"))
+
+ # retry_after should be > 0
+ assert cb.retry_after > 0
+ assert cb.retry_after <= 30 # Capped at 30s
+
+ def test_retry_after_returns_zero_when_closed(self):
+ """Test retry_after returns 0 when CLOSED."""
+ cb = CircuitBreaker()
+ assert cb.retry_after == 0
+
+ def test_retry_after_capped_at_30(self):
+ """Test retry_after is capped at 30 seconds."""
+ cb = CircuitBreaker(failure_threshold=1, reset_timeout=1000.0)
+
+ # Trip the breaker
+ cb.record_failure(Exception("500 Error"))
+
+ # Should be capped at 30
+ assert cb.retry_after == 30
+
+ def test_thread_safety(self):
+ """Test circuit breaker is thread-safe."""
+ import threading
+
+ cb = CircuitBreaker(failure_threshold=100)
+ errors = []
+
+ def worker():
+ try:
+ for _ in range(100):
+ cb.record_failure(Exception("500 Error"))
+ cb.check()
+ except CircuitBreakerOpen:
+ errors.append("open")
+ except Exception as e:
+ errors.append(e)
+
+ threads = [threading.Thread(target=worker) for _ in range(10)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ # Should not have any unexpected errors
+ for e in errors:
+ assert e == "open"
+
+
+class TestCircuitBreakerEdgeCases:
+ """Test edge cases for circuit breaker."""
+
+ def test_zero_failure_threshold(self):
+ """Test with zero failure threshold (trips immediately)."""
+ cb = CircuitBreaker(failure_threshold=0)
+ # Zero threshold means any failure trips it
+ cb.record_failure(Exception("500 Error"))
+
+ with pytest.raises(CircuitBreakerOpen):
+ cb.check()
+
+ def test_negative_reset_timeout(self):
+ """Test with negative reset timeout (immediate reset)."""
+ cb = CircuitBreaker(failure_threshold=1, reset_timeout=-1.0)
+
+ cb.record_failure(Exception("500 Error"))
+
+ # With negative timeout, should immediately allow transition
+ cb.check() # Should not raise
+
+ def test_multiple_rapid_failures(self):
+ """Test multiple rapid failures."""
+ cb = CircuitBreaker(failure_threshold=3)
+
+ for _ in range(10):
+ cb.record_failure(Exception("500 Error"))
+
+ with pytest.raises(CircuitBreakerOpen):
+ cb.check()
+
+ def test_mixed_error_types(self):
+ """Test with mixed error types."""
+ cb = CircuitBreaker(failure_threshold=5)
+
+ cb.record_failure(Exception("500 Error"))
+ cb.record_failure(Exception("429 Rate limit"))
+ cb.record_failure(Exception("503 Unavailable"))
+ cb.record_failure(Exception("Timeout"))
+ cb.record_failure(Exception("Connection reset"))
+
+ with pytest.raises(CircuitBreakerOpen):
+ cb.check()
+
+ def test_permanent_error_mid_sequence(self):
+ """Test permanent error trips breaker regardless of sequence."""
+ cb = CircuitBreaker(failure_threshold=10)
+
+ cb.record_failure(Exception("500 Error"))
+ cb.record_failure(Exception("500 Error"))
+ cb.record_failure(Exception("403 Forbidden")) # Permanent error
+ cb.record_failure(Exception("500 Error"))
+
+ with pytest.raises(CircuitBreakerOpen):
+ cb.check()
diff --git a/tests/unit/test_context.py b/tests/unit/test_context.py
new file mode 100644
index 000000000..439583272
--- /dev/null
+++ b/tests/unit/test_context.py
@@ -0,0 +1,551 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Comprehensive tests for Context class."""
+
+from datetime import datetime, timezone
+
+from openviking.core.context import (
+ Context,
+ ContextLevel,
+ ContextType,
+ ResourceContentType,
+ Vectorize,
+)
+from openviking_cli.session.user_id import UserIdentifier
+
+
+class TestResourceContentType:
+ """Test ResourceContentType enum."""
+
+ def test_text_type(self):
+ """Test TEXT content type."""
+ assert ResourceContentType.TEXT == "text"
+ assert ResourceContentType.TEXT.value == "text"
+
+ def test_image_type(self):
+ """Test IMAGE content type."""
+ assert ResourceContentType.IMAGE == "image"
+ assert ResourceContentType.IMAGE.value == "image"
+
+ def test_video_type(self):
+ """Test VIDEO content type."""
+ assert ResourceContentType.VIDEO == "video"
+ assert ResourceContentType.VIDEO.value == "video"
+
+ def test_audio_type(self):
+ """Test AUDIO content type."""
+ assert ResourceContentType.AUDIO == "audio"
+ assert ResourceContentType.AUDIO.value == "audio"
+
+ def test_binary_type(self):
+ """Test BINARY content type."""
+ assert ResourceContentType.BINARY == "binary"
+ assert ResourceContentType.BINARY.value == "binary"
+
+
+class TestContextType:
+ """Test ContextType enum."""
+
+ def test_skill_type(self):
+ """Test SKILL context type."""
+ assert ContextType.SKILL == "skill"
+ assert ContextType.SKILL.value == "skill"
+
+ def test_memory_type(self):
+ """Test MEMORY context type."""
+ assert ContextType.MEMORY == "memory"
+ assert ContextType.MEMORY.value == "memory"
+
+ def test_resource_type(self):
+ """Test RESOURCE context type."""
+ assert ContextType.RESOURCE == "resource"
+ assert ContextType.RESOURCE.value == "resource"
+
+
+class TestContextLevel:
+ """Test ContextLevel enum."""
+
+ def test_abstract_level(self):
+ """Test ABSTRACT (L0) level."""
+ assert ContextLevel.ABSTRACT == 0
+ assert ContextLevel.ABSTRACT.value == 0
+
+ def test_overview_level(self):
+ """Test OVERVIEW (L1) level."""
+ assert ContextLevel.OVERVIEW == 1
+ assert ContextLevel.OVERVIEW.value == 1
+
+ def test_detail_level(self):
+ """Test DETAIL (L2) level."""
+ assert ContextLevel.DETAIL == 2
+ assert ContextLevel.DETAIL.value == 2
+
+
+class TestVectorize:
+ """Test Vectorize class."""
+
+ def test_default_text(self):
+ """Test default text is empty."""
+ v = Vectorize()
+ assert v.text == ""
+
+ def test_custom_text(self):
+ """Test custom text."""
+ v = Vectorize(text="Hello world")
+ assert v.text == "Hello world"
+
+
+class TestContextInit:
+ """Test Context initialization."""
+
+ def test_minimal_init(self):
+ """Test minimal initialization."""
+ ctx = Context(uri="viking://resources/test/")
+
+ assert ctx.uri == "viking://resources/test/"
+ assert ctx.is_leaf is False
+ assert ctx.abstract == ""
+ assert ctx.context_type == "resource"
+ assert ctx.active_count == 0
+ assert ctx.meta == {}
+
+ def test_full_init(self):
+ """Test full initialization."""
+ now = datetime.now(timezone.utc)
+ ctx = Context(
+ uri="viking://user/test/memories/profile/test.md",
+ parent_uri="viking://user/test/memories/profile/",
+ is_leaf=True,
+ abstract="Test abstract",
+ context_type="memory",
+ category="profile",
+ created_at=now,
+ updated_at=now,
+ active_count=5,
+ related_uri=["viking://other/"],
+ meta={"key": "value"},
+ level=1,
+ )
+
+ assert ctx.uri == "viking://user/test/memories/profile/test.md"
+ assert ctx.parent_uri == "viking://user/test/memories/profile/"
+ assert ctx.is_leaf is True
+ assert ctx.abstract == "Test abstract"
+ assert ctx.context_type == "memory"
+ assert ctx.category == "profile"
+ assert ctx.created_at == now
+ assert ctx.updated_at == now
+ assert ctx.active_count == 5
+ assert ctx.related_uri == ["viking://other/"]
+ assert ctx.meta == {"key": "value"}
+ assert ctx.level == 1
+
+ def test_auto_generated_id(self):
+ """Test auto-generated ID."""
+ ctx = Context(uri="viking://test/")
+
+ assert ctx.id is not None
+ assert len(ctx.id) == 36 # UUID format
+
+ def test_custom_id(self):
+ """Test custom ID."""
+ ctx = Context(uri="viking://test/", id="custom-id-123")
+
+ assert ctx.id == "custom-id-123"
+
+ def test_auto_timestamps(self):
+ """Test auto-generated timestamps."""
+ ctx = Context(uri="viking://test/")
+
+ assert ctx.created_at is not None
+ assert ctx.updated_at is not None
+ assert ctx.created_at.tzinfo is not None
+
+ def test_vectorize_initialized(self):
+ """Test vectorize is initialized."""
+ ctx = Context(uri="viking://test/", abstract="Test")
+
+ assert ctx.vectorize is not None
+ assert ctx.vectorize.text == "Test"
+
+
+class TestContextDeriveContextType:
+ """Test Context._derive_context_type."""
+
+ def test_derive_skill(self):
+ """Test deriving skill type from URI."""
+ ctx = Context(uri="viking://agent/test/skills/my-skill/")
+
+ assert ctx.context_type == "skill"
+
+ def test_derive_memory(self):
+ """Test deriving memory type from URI."""
+ ctx = Context(uri="viking://user/test/memories/preferences/test.md")
+
+ assert ctx.context_type == "memory"
+
+ def test_derive_resource_default(self):
+ """Test deriving resource type (default)."""
+ ctx = Context(uri="viking://resources/docs/readme.md")
+
+ assert ctx.context_type == "resource"
+
+ def test_explicit_context_type_overrides(self):
+ """Test explicit context_type overrides derivation."""
+ ctx = Context(uri="viking://resources/docs/readme.md", context_type="skill")
+
+ assert ctx.context_type == "skill"
+
+
+class TestContextDeriveCategory:
+ """Test Context._derive_category."""
+
+ def test_derive_patterns(self):
+ """Test deriving patterns category."""
+ ctx = Context(uri="viking://memories/patterns/test.md")
+
+ assert ctx.category == "patterns"
+
+ def test_derive_cases(self):
+ """Test deriving cases category."""
+ ctx = Context(uri="viking://memories/cases/test.md")
+
+ assert ctx.category == "cases"
+
+ def test_derive_profile(self):
+ """Test deriving profile category."""
+ ctx = Context(uri="viking://memories/profile/test.md")
+
+ assert ctx.category == "profile"
+
+ def test_derive_preferences(self):
+ """Test deriving preferences category."""
+ ctx = Context(uri="viking://memories/preferences/test.md")
+
+ assert ctx.category == "preferences"
+
+ def test_derive_entities(self):
+ """Test deriving entities category."""
+ ctx = Context(uri="viking://memories/entities/test.md")
+
+ assert ctx.category == "entities"
+
+ def test_derive_events(self):
+ """Test deriving events category."""
+ ctx = Context(uri="viking://memories/events/test.md")
+
+ assert ctx.category == "events"
+
+ def test_derive_empty_default(self):
+ """Test deriving empty category (default)."""
+ ctx = Context(uri="viking://resources/docs/test.md")
+
+ assert ctx.category == ""
+
+ def test_explicit_category_overrides(self):
+ """Test explicit category overrides derivation."""
+ ctx = Context(uri="viking://resources/docs/test.md", category="custom")
+
+ assert ctx.category == "custom"
+
+
+class TestContextMethods:
+ """Test Context methods."""
+
+ def test_get_context_type(self):
+ """Test get_context_type method."""
+ ctx = Context(uri="viking://test/", context_type="skill")
+
+ assert ctx.get_context_type() == "skill"
+
+ def test_set_vectorize(self):
+ """Test set_vectorize method."""
+ ctx = Context(uri="viking://test/")
+ v = Vectorize(text="New text")
+ ctx.set_vectorize(v)
+
+ assert ctx.vectorize.text == "New text"
+
+ def test_get_vectorization_text(self):
+ """Test get_vectorization_text method."""
+ ctx = Context(uri="viking://test/", abstract="Test abstract")
+
+ assert ctx.get_vectorization_text() == "Test abstract"
+
+ def test_update_activity(self):
+ """Test update_activity method."""
+ ctx = Context(uri="viking://test/", active_count=5)
+ old_updated = ctx.updated_at
+
+ ctx.update_activity()
+
+ assert ctx.active_count == 6
+ assert ctx.updated_at > old_updated
+
+
+class TestContextToDict:
+ """Test Context.to_dict."""
+
+ def test_to_dict_basic(self):
+ """Test basic to_dict conversion."""
+ ctx = Context(
+ uri="viking://test/",
+ is_leaf=True,
+ abstract="Test abstract",
+ )
+
+ d = ctx.to_dict()
+
+ assert d["uri"] == "viking://test/"
+ assert d["is_leaf"] is True
+ assert d["abstract"] == "Test abstract"
+ assert d["context_type"] == "resource"
+ assert "id" in d
+ assert "created_at" in d
+ assert "updated_at" in d
+
+ def test_to_dict_with_optional_fields(self):
+ """Test to_dict with optional fields."""
+ ctx = Context(
+ uri="viking://test/",
+ parent_uri="viking://parent/",
+ temp_uri="viking://temp/",
+ related_uri=["viking://related/"],
+ meta={"key": "value"},
+ level=1,
+ session_id="session-123",
+ )
+
+ d = ctx.to_dict()
+
+ assert d["parent_uri"] == "viking://parent/"
+ assert d["temp_uri"] == "viking://temp/"
+ assert d["related_uri"] == ["viking://related/"]
+ assert d["meta"] == {"key": "value"}
+ assert d["level"] == 1
+ assert d["session_id"] == "session-123"
+
+ def test_to_dict_skill_type(self):
+ """Test to_dict adds skill-specific fields."""
+ ctx = Context(
+ uri="viking://skills/test/",
+ context_type="skill",
+ meta={"name": "my-skill", "description": "A skill"},
+ )
+
+ d = ctx.to_dict()
+
+ assert d["name"] == "my-skill"
+ assert d["description"] == "A skill"
+
+ def test_to_dict_timestamps_format(self):
+ """Test timestamps are formatted as ISO strings."""
+ now = datetime(2026, 3, 26, 10, 30, 0, tzinfo=timezone.utc)
+ ctx = Context(
+ uri="viking://test/",
+ created_at=now,
+ updated_at=now,
+ )
+
+ d = ctx.to_dict()
+
+ assert d["created_at"] == "2026-03-26T10:30:00.000Z"
+ assert d["updated_at"] == "2026-03-26T10:30:00.000Z"
+
+
+class TestContextFromDict:
+ """Test Context.from_dict."""
+
+ def test_from_dict_basic(self):
+ """Test basic from_dict conversion."""
+ d = {
+ "uri": "viking://test/",
+ "is_leaf": True,
+ "abstract": "Test abstract",
+ "context_type": "memory",
+ "category": "profile",
+ }
+
+ ctx = Context.from_dict(d)
+
+ assert ctx.uri == "viking://test/"
+ assert ctx.is_leaf is True
+ assert ctx.abstract == "Test abstract"
+ assert ctx.context_type == "memory"
+ assert ctx.category == "profile"
+
+ def test_from_dict_with_timestamps(self):
+ """Test from_dict with ISO timestamps."""
+ d = {
+ "uri": "viking://test/",
+ "created_at": "2026-03-26T10:30:00Z",
+ "updated_at": "2026-03-26T11:30:00Z",
+ }
+
+ ctx = Context.from_dict(d)
+
+ assert ctx.created_at.year == 2026
+ assert ctx.created_at.month == 3
+ assert ctx.created_at.day == 26
+ assert ctx.created_at.hour == 10
+
+ def test_from_dict_with_level(self):
+ """Test from_dict with level."""
+ d = {
+ "uri": "viking://test/",
+ "level": 1,
+ }
+
+ ctx = Context.from_dict(d)
+
+ assert ctx.level == 1
+
+ def test_from_dict_with_user(self):
+ """Test from_dict with user."""
+ d = {
+ "uri": "viking://test/",
+ "user": {
+ "account_id": "account-123",
+ "user_id": "user-123",
+ "agent_id": "agent-456",
+ },
+ }
+
+ ctx = Context.from_dict(d)
+
+ assert ctx.user is not None
+ assert ctx.user.user_id == "user-123"
+ assert ctx.user.account_id == "account-123"
+
+ def test_from_dict_with_vector(self):
+ """Test from_dict with vector."""
+ d = {
+ "uri": "viking://test/",
+ "vector": [0.1, 0.2, 0.3],
+ }
+
+ ctx = Context.from_dict(d)
+
+ assert ctx.vector == [0.1, 0.2, 0.3]
+
+ def test_roundtrip(self):
+ """Test to_dict -> from_dict roundtrip."""
+ original = Context(
+ uri="viking://test/",
+ parent_uri="viking://parent/",
+ is_leaf=True,
+ abstract="Test abstract",
+ context_type="memory",
+ category="profile",
+ active_count=5,
+ related_uri=["viking://related/"],
+ meta={"key": "value"},
+ level=1,
+ session_id="session-123",
+ )
+
+ d = original.to_dict()
+ restored = Context.from_dict(d)
+
+ assert restored.uri == original.uri
+ assert restored.parent_uri == original.parent_uri
+ assert restored.is_leaf == original.is_leaf
+ assert restored.abstract == original.abstract
+ assert restored.context_type == original.context_type
+ assert restored.category == original.category
+ assert restored.active_count == original.active_count
+ assert restored.related_uri == original.related_uri
+ assert restored.meta == original.meta
+ assert restored.level == original.level
+ assert restored.session_id == original.session_id
+
+
+class TestContextWithUser:
+ """Test Context with UserIdentifier."""
+
+ def test_user_account_id_inheritance(self):
+ """Test account_id inherited from user."""
+ user = UserIdentifier(account_id="account-123", user_id="user-123", agent_id="agent-456")
+ ctx = Context(uri="viking://test/", user=user)
+
+ assert ctx.account_id == user.account_id
+
+ def test_owner_space_agent(self):
+ """Test owner_space for agent URI."""
+ user = UserIdentifier(account_id="account-123", user_id="user-123", agent_id="agent-456")
+ ctx = Context(uri="viking://agent/test/skills/my-skill/", user=user)
+
+ assert ctx.owner_space == user.agent_space_name()
+
+ def test_owner_space_user(self):
+ """Test owner_space for user URI."""
+ user = UserIdentifier(account_id="account-123", user_id="user-123", agent_id="agent-456")
+ ctx = Context(uri="viking://user/test/memories/test.md", user=user)
+
+ assert ctx.owner_space == user.user_space_name()
+
+ def test_owner_space_session(self):
+ """Test owner_space for session URI."""
+ user = UserIdentifier(account_id="account-123", user_id="user-123", agent_id="agent-456")
+ ctx = Context(uri="viking://session/test/msg/1.md", user=user)
+
+ assert ctx.owner_space == user.user_space_name()
+
+ def test_owner_space_resource_default(self):
+ """Test owner_space default for resource URI."""
+ user = UserIdentifier(account_id="account-123", user_id="user-123", agent_id="agent-456")
+ ctx = Context(uri="viking://resources/docs/test.md", user=user)
+
+ # Resource URIs don't match agent/user/session patterns
+ assert ctx.owner_space == ""
+
+
+class TestContextEdgeCases:
+ """Test edge cases for Context."""
+
+ def test_level_string_to_int(self):
+ """Test level conversion from string to int."""
+ # The code tries to convert level to int
+ ctx = Context(uri="viking://test/", level="1")
+
+ assert ctx.level == 1
+
+ def test_level_none(self):
+ """Test level None."""
+ ctx = Context(uri="viking://test/", level=None)
+
+ assert ctx.level is None
+
+ def test_level_invalid_string(self):
+ """Test invalid level string becomes None."""
+ ctx = Context(uri="viking://test/", level="invalid")
+
+ assert ctx.level is None
+
+ def test_empty_abstract(self):
+ """Test empty abstract."""
+ ctx = Context(uri="viking://test/", abstract="")
+
+ assert ctx.abstract == ""
+ assert ctx.get_vectorization_text() == ""
+
+ def test_long_abstract(self):
+ """Test long abstract."""
+ long_text = "x" * 10000
+ ctx = Context(uri="viking://test/", abstract=long_text)
+
+ assert ctx.abstract == long_text
+ assert ctx.get_vectorization_text() == long_text
+
+ def test_unicode_in_abstract(self):
+ """Test Unicode in abstract."""
+ ctx = Context(uri="viking://test/", abstract="你好世界 🌍")
+
+ assert ctx.abstract == "你好世界 🌍"
+
+ def test_special_chars_in_uri(self):
+ """Test special characters in URI."""
+ ctx = Context(uri="viking://test/path%20with%20spaces/")
+
+ assert ctx.uri == "viking://test/path%20with%20spaces/"
diff --git a/tests/unit/test_message.py b/tests/unit/test_message.py
new file mode 100644
index 000000000..483fb60f5
--- /dev/null
+++ b/tests/unit/test_message.py
@@ -0,0 +1,760 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Comprehensive tests for Message and Part classes."""
+
+import json
+from datetime import datetime, timezone
+
+from openviking.message import ContextPart, Message, TextPart, ToolPart
+from openviking.message.part import part_from_dict
+
+
+class TestTextPart:
+ """Test TextPart dataclass."""
+
+ def test_default_values(self):
+ """Test default values."""
+ part = TextPart()
+
+ assert part.text == ""
+ assert part.type == "text"
+
+ def test_custom_text(self):
+ """Test custom text."""
+ part = TextPart(text="Hello, world!")
+
+ assert part.text == "Hello, world!"
+ assert part.type == "text"
+
+ def test_empty_text(self):
+ """Test empty text."""
+ part = TextPart(text="")
+
+ assert part.text == ""
+ assert part.type == "text"
+
+ def test_long_text(self):
+ """Test long text."""
+ long_text = "x" * 10000
+ part = TextPart(text=long_text)
+
+ assert part.text == long_text
+
+ def test_unicode_text(self):
+ """Test Unicode text."""
+ part = TextPart(text="你好世界 🌍")
+
+ assert part.text == "你好世界 🌍"
+
+ def test_multiline_text(self):
+ """Test multiline text."""
+ part = TextPart(text="Line 1\nLine 2\nLine 3")
+
+ assert "\n" in part.text
+ assert part.text.count("\n") == 2
+
+
+class TestContextPart:
+ """Test ContextPart dataclass."""
+
+ def test_default_values(self):
+ """Test default values."""
+ part = ContextPart()
+
+ assert part.uri == ""
+ assert part.context_type == "memory"
+ assert part.abstract == ""
+ assert part.type == "context"
+
+ def test_custom_values(self):
+ """Test custom values."""
+ part = ContextPart(
+ uri="viking://resources/docs/test.md",
+ context_type="resource",
+ abstract="This is a test document",
+ )
+
+ assert part.uri == "viking://resources/docs/test.md"
+ assert part.context_type == "resource"
+ assert part.abstract == "This is a test document"
+ assert part.type == "context"
+
+ def test_memory_context_type(self):
+ """Test memory context type."""
+ part = ContextPart(
+ uri="viking://memories/profile/test.md",
+ context_type="memory",
+ )
+
+ assert part.context_type == "memory"
+
+ def test_skill_context_type(self):
+ """Test skill context type."""
+ part = ContextPart(
+ uri="viking://skills/my-skill/",
+ context_type="skill",
+ )
+
+ assert part.context_type == "skill"
+
+ def test_resource_context_type(self):
+ """Test resource context type."""
+ part = ContextPart(
+ uri="viking://resources/docs/readme.md",
+ context_type="resource",
+ )
+
+ assert part.context_type == "resource"
+
+
+class TestToolPart:
+ """Test ToolPart dataclass."""
+
+ def test_default_values(self):
+ """Test default values."""
+ part = ToolPart()
+
+ assert part.tool_id == ""
+ assert part.tool_name == ""
+ assert part.tool_uri == ""
+ assert part.skill_uri == ""
+ assert part.tool_input is None
+ assert part.tool_output == ""
+ assert part.tool_status == "pending"
+ assert part.duration_ms is None
+ assert part.prompt_tokens is None
+ assert part.completion_tokens is None
+ assert part.type == "tool"
+
+ def test_custom_values(self):
+ """Test custom values."""
+ part = ToolPart(
+ tool_id="call-123",
+ tool_name="search",
+ tool_uri="viking://session/test/tools/call-123",
+ skill_uri="viking://agent/test/skills/search",
+ tool_input={"query": "test"},
+ tool_output="Result",
+ tool_status="completed",
+ duration_ms=150.5,
+ prompt_tokens=100,
+ completion_tokens=50,
+ )
+
+ assert part.tool_id == "call-123"
+ assert part.tool_name == "search"
+ assert part.tool_uri == "viking://session/test/tools/call-123"
+ assert part.skill_uri == "viking://agent/test/skills/search"
+ assert part.tool_input == {"query": "test"}
+ assert part.tool_output == "Result"
+ assert part.tool_status == "completed"
+ assert part.duration_ms == 150.5
+ assert part.prompt_tokens == 100
+ assert part.completion_tokens == 50
+
+ def test_tool_statuses(self):
+ """Test various tool statuses."""
+ for status in ["pending", "running", "completed", "error"]:
+ part = ToolPart(tool_status=status)
+ assert part.tool_status == status
+
+ def test_tool_input_none(self):
+ """Test tool input can be None."""
+ part = ToolPart(tool_input=None)
+
+ assert part.tool_input is None
+
+ def test_tool_input_dict(self):
+ """Test tool input as dict."""
+ part = ToolPart(tool_input={"key": "value", "nested": {"a": 1}})
+
+ assert part.tool_input["key"] == "value"
+ assert part.tool_input["nested"]["a"] == 1
+
+ def test_tool_output_empty(self):
+ """Test tool output can be empty."""
+ part = ToolPart(tool_output="")
+
+ assert part.tool_output == ""
+
+
+class TestPartFromDict:
+ """Test part_from_dict function."""
+
+ def test_text_part_from_dict(self):
+ """Test creating TextPart from dict."""
+ data = {"type": "text", "text": "Hello"}
+
+ part = part_from_dict(data)
+
+ assert isinstance(part, TextPart)
+ assert part.text == "Hello"
+ assert part.type == "text"
+
+ def test_context_part_from_dict(self):
+ """Test creating ContextPart from dict."""
+ data = {
+ "type": "context",
+ "uri": "viking://test/",
+ "context_type": "resource",
+ "abstract": "Test abstract",
+ }
+
+ part = part_from_dict(data)
+
+ assert isinstance(part, ContextPart)
+ assert part.uri == "viking://test/"
+ assert part.context_type == "resource"
+ assert part.abstract == "Test abstract"
+
+ def test_tool_part_from_dict(self):
+ """Test creating ToolPart from dict."""
+ data = {
+ "type": "tool",
+ "tool_id": "call-123",
+ "tool_name": "search",
+ "tool_uri": "viking://session/test/tools/call-123",
+ "skill_uri": "viking://agent/test/skills/search",
+ "tool_input": {"query": "test"},
+ "tool_output": "Result",
+ "tool_status": "completed",
+ "duration_ms": 150.0,
+ "prompt_tokens": 100,
+ "completion_tokens": 50,
+ }
+
+ part = part_from_dict(data)
+
+ assert isinstance(part, ToolPart)
+ assert part.tool_id == "call-123"
+ assert part.tool_name == "search"
+ assert part.tool_status == "completed"
+
+ def test_unknown_type_defaults_to_text(self):
+ """Test unknown type defaults to TextPart."""
+ data = {"type": "unknown", "value": "something"}
+
+ part = part_from_dict(data)
+
+ assert isinstance(part, TextPart)
+ # The entire dict is converted to string
+ assert "unknown" in part.text
+
+ def test_missing_type_defaults_to_text(self):
+ """Test missing type defaults to TextPart."""
+ data = {"text": "Hello"}
+
+ part = part_from_dict(data)
+
+ assert isinstance(part, TextPart)
+ assert part.text == "Hello"
+
+ def test_empty_dict(self):
+ """Test empty dict creates empty TextPart."""
+ data = {}
+
+ part = part_from_dict(data)
+
+ assert isinstance(part, TextPart)
+ assert part.text == ""
+
+
+class TestMessageInit:
+ """Test Message initialization."""
+
+ def test_minimal_init(self):
+ """Test minimal initialization."""
+ msg = Message(
+ id="msg-123",
+ role="user",
+ parts=[TextPart(text="Hello")],
+ )
+
+ assert msg.id == "msg-123"
+ assert msg.role == "user"
+ assert len(msg.parts) == 1
+ # Note: created_at defaults to None; to_dict() generates timestamp if None
+ assert msg.created_at is None
+
+ def test_with_created_at(self):
+ """Test with explicit created_at."""
+ now = datetime.now(timezone.utc)
+ msg = Message(
+ id="msg-123",
+ role="assistant",
+ parts=[],
+ created_at=now,
+ )
+
+ assert msg.created_at == now
+
+ def test_user_role(self):
+ """Test user role."""
+ msg = Message(
+ id="msg-1",
+ role="user",
+ parts=[TextPart(text="Hello")],
+ )
+
+ assert msg.role == "user"
+
+ def test_assistant_role(self):
+ """Test assistant role."""
+ msg = Message(
+ id="msg-1",
+ role="assistant",
+ parts=[TextPart(text="Hi there")],
+ )
+
+ assert msg.role == "assistant"
+
+ def test_multiple_parts(self):
+ """Test message with multiple parts."""
+ msg = Message(
+ id="msg-1",
+ role="assistant",
+ parts=[
+ TextPart(text="Here's what I found:"),
+ ContextPart(uri="viking://resources/docs/test.md"),
+ ToolPart(tool_id="call-1", tool_name="search"),
+ ],
+ )
+
+ assert len(msg.parts) == 3
+
+
+class TestMessageContent:
+ """Test Message.content property."""
+
+ def test_content_returns_first_text_part(self):
+ """Test content returns first TextPart text."""
+ msg = Message(
+ id="msg-1",
+ role="user",
+ parts=[TextPart(text="Hello")],
+ )
+
+ assert msg.content == "Hello"
+
+ def test_content_returns_empty_if_no_text_part(self):
+ """Test content returns empty string if no TextPart."""
+ msg = Message(
+ id="msg-1",
+ role="assistant",
+ parts=[ContextPart(uri="viking://test/")],
+ )
+
+ assert msg.content == ""
+
+ def test_content_ignores_other_parts(self):
+ """Test content ignores non-TextPart parts."""
+ msg = Message(
+ id="msg-1",
+ role="assistant",
+ parts=[
+ ContextPart(uri="viking://test/"),
+ TextPart(text="Hello"),
+ ToolPart(tool_id="call-1"),
+ ],
+ )
+
+ assert msg.content == "Hello"
+
+ def test_content_returns_first_when_multiple_text_parts(self):
+ """Test content returns first TextPart when multiple exist."""
+ msg = Message(
+ id="msg-1",
+ role="assistant",
+ parts=[
+ TextPart(text="First"),
+ TextPart(text="Second"),
+ ],
+ )
+
+ assert msg.content == "First"
+
+
+class TestMessageToDict:
+ """Test Message.to_dict."""
+
+ def test_to_dict_basic(self):
+ """Test basic to_dict conversion."""
+ msg = Message(
+ id="msg-1",
+ role="user",
+ parts=[TextPart(text="Hello")],
+ )
+
+ d = msg.to_dict()
+
+ assert d["id"] == "msg-1"
+ assert d["role"] == "user"
+ assert len(d["parts"]) == 1
+ assert d["parts"][0]["type"] == "text"
+ assert d["parts"][0]["text"] == "Hello"
+ assert "created_at" in d
+
+ def test_to_dict_with_multiple_parts(self):
+ """Test to_dict with multiple parts."""
+ msg = Message(
+ id="msg-1",
+ role="assistant",
+ parts=[
+ TextPart(text="Hello"),
+ ContextPart(uri="viking://test/", context_type="memory"),
+ ],
+ )
+
+ d = msg.to_dict()
+
+ assert len(d["parts"]) == 2
+ assert d["parts"][0]["type"] == "text"
+ assert d["parts"][1]["type"] == "context"
+
+ def test_to_dict_with_tool_part(self):
+ """Test to_dict with ToolPart."""
+ msg = Message(
+ id="msg-1",
+ role="assistant",
+ parts=[
+ ToolPart(
+ tool_id="call-1",
+ tool_name="search",
+ tool_uri="viking://tools/1",
+ tool_status="completed",
+ duration_ms=100,
+ prompt_tokens=50,
+ completion_tokens=25,
+ )
+ ],
+ )
+
+ d = msg.to_dict()
+
+ assert d["parts"][0]["type"] == "tool"
+ assert d["parts"][0]["tool_id"] == "call-1"
+ assert d["parts"][0]["duration_ms"] == 100
+
+ def test_to_dict_timestamp_format(self):
+ """Test timestamp format in to_dict."""
+ now = datetime(2026, 3, 26, 10, 30, 0, tzinfo=timezone.utc)
+ msg = Message(
+ id="msg-1",
+ role="user",
+ parts=[],
+ created_at=now,
+ )
+
+ d = msg.to_dict()
+
+ assert d["created_at"] == "2026-03-26T10:30:00.000Z"
+
+
+class TestMessageFromDict:
+ """Test Message.from_dict."""
+
+ def test_from_dict_basic(self):
+ """Test basic from_dict conversion."""
+ d = {
+ "id": "msg-1",
+ "role": "user",
+ "parts": [{"type": "text", "text": "Hello"}],
+ "created_at": "2026-03-26T10:30:00Z",
+ }
+
+ msg = Message.from_dict(d)
+
+ assert msg.id == "msg-1"
+ assert msg.role == "user"
+ assert len(msg.parts) == 1
+ assert isinstance(msg.parts[0], TextPart)
+ assert msg.parts[0].text == "Hello"
+
+ def test_from_dict_with_context_part(self):
+ """Test from_dict with ContextPart."""
+ d = {
+ "id": "msg-1",
+ "role": "assistant",
+ "parts": [
+ {
+ "type": "context",
+ "uri": "viking://test/",
+ "context_type": "memory",
+ "abstract": "Test",
+ }
+ ],
+ "created_at": "2026-03-26T10:30:00Z",
+ }
+
+ msg = Message.from_dict(d)
+
+ assert isinstance(msg.parts[0], ContextPart)
+ assert msg.parts[0].uri == "viking://test/"
+
+ def test_from_dict_with_tool_part(self):
+ """Test from_dict with ToolPart."""
+ d = {
+ "id": "msg-1",
+ "role": "assistant",
+ "parts": [
+ {
+ "type": "tool",
+ "tool_id": "call-1",
+ "tool_name": "search",
+ "tool_uri": "viking://tools/1",
+ "tool_status": "completed",
+ }
+ ],
+ "created_at": "2026-03-26T10:30:00Z",
+ }
+
+ msg = Message.from_dict(d)
+
+ assert isinstance(msg.parts[0], ToolPart)
+ assert msg.parts[0].tool_id == "call-1"
+
+ def test_roundtrip(self):
+ """Test to_dict -> from_dict roundtrip."""
+ original = Message(
+ id="msg-1",
+ role="assistant",
+ parts=[
+ TextPart(text="Hello"),
+ ContextPart(uri="viking://test/", context_type="memory"),
+ ],
+ )
+
+ d = original.to_dict()
+ restored = Message.from_dict(d)
+
+ assert restored.id == original.id
+ assert restored.role == original.role
+ assert len(restored.parts) == len(original.parts)
+ assert isinstance(restored.parts[0], TextPart)
+ assert isinstance(restored.parts[1], ContextPart)
+
+
+class TestMessageFactoryMethods:
+ """Test Message factory methods."""
+
+ def test_create_user(self):
+ """Test create_user factory method."""
+ msg = Message.create_user("Hello, assistant!")
+
+ assert msg.role == "user"
+ assert msg.content == "Hello, assistant!"
+ assert len(msg.parts) == 1
+ assert msg.id.startswith("msg_")
+
+ def test_create_user_with_id(self):
+ """Test create_user with custom ID."""
+ msg = Message.create_user("Hello", msg_id="custom-id")
+
+ assert msg.id == "custom-id"
+
+ def test_create_assistant(self):
+ """Test create_assistant factory method."""
+ msg = Message.create_assistant("Hello, user!")
+
+ assert msg.role == "assistant"
+ assert msg.content == "Hello, user!"
+ assert len(msg.parts) == 1
+
+ def test_create_assistant_with_context_refs(self):
+ """Test create_assistant with context references."""
+ msg = Message.create_assistant(
+ content="Here's what I found:",
+ context_refs=[
+ {"uri": "viking://test/1.md", "context_type": "memory"},
+ {"uri": "viking://test/2.md", "context_type": "resource"},
+ ],
+ )
+
+ assert msg.role == "assistant"
+ assert len(msg.parts) == 3 # 1 text + 2 context
+
+ def test_create_assistant_with_tool_calls(self):
+ """Test create_assistant with tool calls."""
+ msg = Message.create_assistant(
+ content="Let me search for that.",
+ tool_calls=[
+ {"id": "call-1", "name": "search", "uri": "viking://tools/1"},
+ ],
+ )
+
+ assert msg.role == "assistant"
+ assert len(msg.parts) == 2 # 1 text + 1 tool
+
+ def test_create_assistant_empty(self):
+ """Test create_assistant with no content."""
+ msg = Message.create_assistant()
+
+ assert msg.role == "assistant"
+ assert msg.content == ""
+ assert len(msg.parts) == 0
+
+
+class TestMessageMethods:
+ """Test Message methods."""
+
+ def test_get_context_parts(self):
+ """Test get_context_parts method."""
+ msg = Message(
+ id="msg-1",
+ role="assistant",
+ parts=[
+ TextPart(text="Hello"),
+ ContextPart(uri="viking://test/1.md"),
+ TextPart(text="More text"),
+ ContextPart(uri="viking://test/2.md"),
+ ],
+ )
+
+ context_parts = msg.get_context_parts()
+
+ assert len(context_parts) == 2
+ assert all(isinstance(p, ContextPart) for p in context_parts)
+
+ def test_get_tool_parts(self):
+ """Test get_tool_parts method."""
+ msg = Message(
+ id="msg-1",
+ role="assistant",
+ parts=[
+ TextPart(text="Hello"),
+ ToolPart(tool_id="call-1"),
+ ToolPart(tool_id="call-2"),
+ ],
+ )
+
+ tool_parts = msg.get_tool_parts()
+
+ assert len(tool_parts) == 2
+ assert all(isinstance(p, ToolPart) for p in tool_parts)
+
+ def test_find_tool_part(self):
+ """Test find_tool_part method."""
+ msg = Message(
+ id="msg-1",
+ role="assistant",
+ parts=[
+ ToolPart(tool_id="call-1"),
+ ToolPart(tool_id="call-2"),
+ ],
+ )
+
+ part = msg.find_tool_part("call-1")
+
+ assert part is not None
+ assert part.tool_id == "call-1"
+
+ def test_find_tool_part_not_found(self):
+ """Test find_tool_part when not found."""
+ msg = Message(
+ id="msg-1",
+ role="assistant",
+ parts=[ToolPart(tool_id="call-1")],
+ )
+
+ part = msg.find_tool_part("nonexistent")
+
+ assert part is None
+
+ def test_to_jsonl(self):
+ """Test to_jsonl method."""
+ msg = Message(
+ id="msg-1",
+ role="user",
+ parts=[TextPart(text="Hello")],
+ )
+
+ jsonl = msg.to_jsonl()
+
+ # Should be valid JSON
+ parsed = json.loads(jsonl)
+ assert parsed["id"] == "msg-1"
+ assert parsed["role"] == "user"
+
+ def test_to_jsonl_unicode(self):
+ """Test to_jsonl with Unicode."""
+ msg = Message(
+ id="msg-1",
+ role="user",
+ parts=[TextPart(text="你好世界")],
+ )
+
+ jsonl = msg.to_jsonl()
+
+ assert "你好世界" in jsonl
+
+
+class TestMessageEdgeCases:
+ """Test edge cases for Message."""
+
+ def test_empty_parts(self):
+ """Test message with empty parts."""
+ msg = Message(
+ id="msg-1",
+ role="user",
+ parts=[],
+ )
+
+ assert len(msg.parts) == 0
+ assert msg.content == ""
+
+ def test_very_long_text(self):
+ """Test message with very long text."""
+ long_text = "x" * 100000
+ msg = Message(
+ id="msg-1",
+ role="user",
+ parts=[TextPart(text=long_text)],
+ )
+
+ assert len(msg.content) == 100000
+
+ def test_special_characters_in_text(self):
+ """Test message with special characters."""
+ msg = Message(
+ id="msg-1",
+ role="user",
+ parts=[TextPart(text='Special: "quotes", \n newlines, \t tabs')],
+ )
+
+ assert '"' in msg.content
+ assert "\n" in msg.content
+ assert "\t" in msg.content
+
+ def test_json_in_tool_input(self):
+ """Test tool input with nested JSON."""
+ msg = Message(
+ id="msg-1",
+ role="assistant",
+ parts=[
+ ToolPart(
+ tool_id="call-1",
+ tool_input={"nested": {"key": "value"}, "array": [1, 2, 3]},
+ )
+ ],
+ )
+
+ assert msg.parts[0].tool_input["nested"]["key"] == "value"
+ assert msg.parts[0].tool_input["array"] == [1, 2, 3]
+
+ def test_multiple_messages_independence(self):
+ """Test multiple messages are independent."""
+ msg1 = Message(
+ id="msg-1",
+ role="user",
+ parts=[TextPart(text="First")],
+ )
+ msg2 = Message(
+ id="msg-2",
+ role="user",
+ parts=[TextPart(text="Second")],
+ )
+
+ assert msg1.content == "First"
+ assert msg2.content == "Second"
+ assert msg1.id != msg2.id
diff --git a/tests/unit/test_process_lock.py b/tests/unit/test_process_lock.py
new file mode 100644
index 000000000..05b60882e
--- /dev/null
+++ b/tests/unit/test_process_lock.py
@@ -0,0 +1,253 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Tests for PID-based process lock utility."""
+
+import os
+from pathlib import Path
+
+import pytest
+
+from openviking.utils.process_lock import (
+ LOCK_FILENAME,
+ DataDirectoryLocked,
+ _is_pid_alive,
+ _read_pid_file,
+ acquire_data_dir_lock,
+)
+
+
+class TestReadPidFile:
+ """Test _read_pid_file function."""
+
+ def test_read_valid_pid(self, tmp_path: Path):
+ """Test reading a valid PID from file."""
+ lock_file = tmp_path / LOCK_FILENAME
+ lock_file.write_text("12345")
+
+ pid = _read_pid_file(str(lock_file))
+ assert pid == 12345
+
+ def test_read_nonexistent_file(self, tmp_path: Path):
+ """Test reading from nonexistent file returns 0."""
+ lock_file = tmp_path / "nonexistent.pid"
+
+ pid = _read_pid_file(str(lock_file))
+ assert pid == 0
+
+ def test_read_invalid_pid(self, tmp_path: Path):
+ """Test reading invalid PID returns 0."""
+ lock_file = tmp_path / LOCK_FILENAME
+ lock_file.write_text("not_a_number")
+
+ pid = _read_pid_file(str(lock_file))
+ assert pid == 0
+
+ def test_read_empty_file(self, tmp_path: Path):
+ """Test reading empty file returns 0."""
+ lock_file = tmp_path / LOCK_FILENAME
+ lock_file.write_text("")
+
+ pid = _read_pid_file(str(lock_file))
+ assert pid == 0
+
+ def test_read_pid_with_whitespace(self, tmp_path: Path):
+ """Test reading PID with leading/trailing whitespace."""
+ lock_file = tmp_path / LOCK_FILENAME
+ lock_file.write_text(" 12345 \n")
+
+ pid = _read_pid_file(str(lock_file))
+ assert pid == 12345
+
+ def test_read_pid_with_newline(self, tmp_path: Path):
+ """Test reading PID with newline."""
+ lock_file = tmp_path / LOCK_FILENAME
+ lock_file.write_text("12345\n")
+
+ pid = _read_pid_file(str(lock_file))
+ assert pid == 12345
+
+
+class TestIsPidAlive:
+ """Test _is_pid_alive function."""
+
+ def test_current_pid_is_alive(self):
+ """Test that current process PID is detected as alive."""
+ current_pid = os.getpid()
+ assert _is_pid_alive(current_pid) is True
+
+ def test_pid_1_is_alive(self):
+ """Test that PID 1 (init) is typically alive."""
+ # PID 1 is usually init process on Linux
+ assert _is_pid_alive(1) is True
+
+ def test_nonexistent_pid_not_alive(self):
+ """Test that nonexistent PID is not alive."""
+ # Use a very high PID that's unlikely to exist
+ assert _is_pid_alive(999999) is False
+
+ def test_pid_zero_not_alive(self):
+ """Test that PID 0 is not alive."""
+ assert _is_pid_alive(0) is False
+
+ def test_negative_pid_not_alive(self):
+ """Test that negative PID is not alive."""
+ assert _is_pid_alive(-1) is False
+
+
+class TestAcquireDataDirLock:
+ """Test acquire_data_dir_lock function."""
+
+ def test_acquire_creates_lock_file(self, tmp_path: Path):
+ """Test acquiring lock creates lock file."""
+ lock_path = acquire_data_dir_lock(str(tmp_path))
+
+ assert lock_path == str(tmp_path / LOCK_FILENAME)
+ assert (tmp_path / LOCK_FILENAME).exists()
+
+ def test_acquire_writes_current_pid(self, tmp_path: Path):
+ """Test lock file contains current PID."""
+ acquire_data_dir_lock(str(tmp_path))
+ my_pid = os.getpid()
+
+ stored_pid = int((tmp_path / LOCK_FILENAME).read_text().strip())
+ assert stored_pid == my_pid
+
+ def test_acquire_same_pid_succeeds(self, tmp_path: Path):
+ """Test acquiring lock with same PID succeeds."""
+ my_pid = os.getpid()
+ (tmp_path / LOCK_FILENAME).write_text(str(my_pid))
+
+ # Should succeed since it's our own PID
+ lock_path = acquire_data_dir_lock(str(tmp_path))
+ assert lock_path == str(tmp_path / LOCK_FILENAME)
+
+ def test_acquire_with_stale_lock_succeeds(self, tmp_path: Path):
+ """Test acquiring lock with stale (dead process) lock succeeds."""
+ # Write a PID that doesn't exist
+ (tmp_path / LOCK_FILENAME).write_text("999999")
+
+ lock_path = acquire_data_dir_lock(str(tmp_path))
+ assert lock_path == str(tmp_path / LOCK_FILENAME)
+
+ def test_acquire_with_live_process_raises(self, tmp_path: Path):
+ """Test acquiring lock with live process raises DataDirectoryLocked."""
+ # Use PID 1 (init) which is typically alive
+ (tmp_path / LOCK_FILENAME).write_text("1")
+
+ with pytest.raises(DataDirectoryLocked) as exc_info:
+ acquire_data_dir_lock(str(tmp_path))
+
+ assert "Another OpenViking process" in str(exc_info.value)
+ assert "PID 1" in str(exc_info.value)
+
+ def test_acquire_creates_directory(self, tmp_path: Path):
+ """Test acquiring lock creates directory if it doesn't exist."""
+ new_dir = tmp_path / "new_subdir"
+
+ acquire_data_dir_lock(str(new_dir))
+ assert new_dir.exists()
+ assert (new_dir / LOCK_FILENAME).exists()
+
+ def test_error_message_suggests_http_mode(self, tmp_path: Path):
+ """Test error message suggests HTTP mode."""
+ (tmp_path / LOCK_FILENAME).write_text("1")
+
+ with pytest.raises(DataDirectoryLocked) as exc_info:
+ acquire_data_dir_lock(str(tmp_path))
+
+ error_msg = str(exc_info.value)
+ assert "HTTP mode" in error_msg
+ assert "openviking-server" in error_msg
+
+ def test_error_message_shows_pid(self, tmp_path: Path):
+ """Test error message shows conflicting PID."""
+ (tmp_path / LOCK_FILENAME).write_text("1")
+
+ with pytest.raises(DataDirectoryLocked) as exc_info:
+ acquire_data_dir_lock(str(tmp_path))
+
+ error_msg = str(exc_info.value)
+ assert "PID 1" in error_msg
+
+ def test_error_message_shows_directory(self, tmp_path: Path):
+ """Test error message shows directory path."""
+ (tmp_path / LOCK_FILENAME).write_text("1")
+
+ with pytest.raises(DataDirectoryLocked) as exc_info:
+ acquire_data_dir_lock(str(tmp_path))
+
+ error_msg = str(exc_info.value)
+ assert str(tmp_path) in error_msg
+
+
+class TestAcquireDataDirLockEdgeCases:
+ """Test edge cases for acquire_data_dir_lock."""
+
+ def test_acquire_nested_directory(self, tmp_path: Path):
+ """Test acquiring lock in nested directory."""
+ nested = tmp_path / "a" / "b" / "c"
+
+ acquire_data_dir_lock(str(nested))
+ assert nested.exists()
+ assert (nested / LOCK_FILENAME).exists()
+
+ def test_acquire_overwrites_stale_lock(self, tmp_path: Path):
+ """Test that acquiring overwrites stale lock with current PID."""
+ my_pid = os.getpid()
+ (tmp_path / LOCK_FILENAME).write_text("999999")
+
+ acquire_data_dir_lock(str(tmp_path))
+
+ stored_pid = int((tmp_path / LOCK_FILENAME).read_text().strip())
+ assert stored_pid == my_pid
+
+ def test_lock_filename_constant(self):
+ """Test LOCK_FILENAME constant is correct."""
+ assert LOCK_FILENAME == ".openviking.pid"
+
+ def test_acquire_with_pathlib_path(self, tmp_path: Path):
+ """Test acquiring with pathlib.Path instead of string."""
+ lock_path = acquire_data_dir_lock(str(tmp_path))
+ assert lock_path == str(tmp_path / LOCK_FILENAME)
+
+ def test_acquire_permissions_on_readonly_parent(self, tmp_path: Path):
+ """Test handling when parent directory is read-only."""
+ # This test may not work on all systems
+ # Just verify it doesn't crash
+ lock_path = acquire_data_dir_lock(str(tmp_path))
+ assert lock_path.endswith(LOCK_FILENAME)
+
+
+class TestProcessLockIntegration:
+ """Integration tests for process lock."""
+
+ def test_multiple_acquires_same_process(self, tmp_path: Path):
+ """Test multiple acquires from same process."""
+ lock_path1 = acquire_data_dir_lock(str(tmp_path))
+ lock_path2 = acquire_data_dir_lock(str(tmp_path))
+
+ assert lock_path1 == lock_path2
+
+ def test_lock_file_cleanup_on_exit_simulation(self, tmp_path: Path):
+ """Test that lock file would be cleaned up on exit."""
+ acquire_data_dir_lock(str(tmp_path))
+ assert (tmp_path / LOCK_FILENAME).exists()
+
+ # Note: Actual cleanup happens via atexit, which we can't easily test
+ # in unit tests without process termination
+
+ def test_reentrant_lock_same_pid(self, tmp_path: Path):
+ """Test that same PID can re-acquire lock."""
+ my_pid = os.getpid()
+
+ # First acquire
+ lock_path1 = acquire_data_dir_lock(str(tmp_path))
+
+ # Write PID again
+ (tmp_path / LOCK_FILENAME).write_text(str(my_pid))
+
+ # Second acquire should succeed
+ lock_path2 = acquire_data_dir_lock(str(tmp_path))
+
+ assert lock_path1 == lock_path2
diff --git a/tests/unit/test_time_utils_comprehensive.py b/tests/unit/test_time_utils_comprehensive.py
new file mode 100644
index 000000000..e84432e33
--- /dev/null
+++ b/tests/unit/test_time_utils_comprehensive.py
@@ -0,0 +1,325 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Comprehensive tests for time utility functions."""
+
+from datetime import datetime, timedelta, timezone
+
+from openviking.utils.time_utils import (
+ format_iso8601,
+ format_simplified,
+ get_current_timestamp,
+ parse_iso_datetime,
+)
+
+
+class TestParseIsoDatetime:
+ """Test parse_iso_datetime function."""
+
+ def test_parse_standard_iso_format(self):
+ """Test parsing standard ISO 8601 format."""
+ dt = parse_iso_datetime("2026-03-26T10:30:00+00:00")
+
+ assert dt.year == 2026
+ assert dt.month == 3
+ assert dt.day == 26
+ assert dt.hour == 10
+ assert dt.minute == 30
+ assert dt.second == 0
+ assert dt.tzinfo is not None
+
+ def test_parse_z_suffix(self):
+ """Test parsing ISO 8601 with Z suffix."""
+ dt = parse_iso_datetime("2026-03-26T10:30:00Z")
+
+ assert dt.year == 2026
+ assert dt.month == 3
+ assert dt.day == 26
+ assert dt.tzinfo is not None
+ assert dt.utcoffset() == timezone.utc.utcoffset(dt)
+
+ def test_parse_with_microseconds(self):
+ """Test parsing with microseconds."""
+ dt = parse_iso_datetime("2026-03-26T10:30:00.123456+00:00")
+
+ assert dt.microsecond == 123456
+
+ def test_parse_with_excess_fractional_seconds(self):
+ """Test parsing with >6 digit fractional seconds (Windows compatibility)."""
+ # Windows may produce timestamps with >6 digit fractional seconds
+ dt = parse_iso_datetime("2026-03-26T10:30:00.1470042+08:00")
+
+ assert dt.year == 2026
+ assert dt.month == 3
+ assert dt.day == 26
+ # Should truncate to 6 digits
+ assert dt.microsecond == 147004
+
+ def test_parse_z_with_excess_fractional_seconds(self):
+ """Test parsing Z suffix with excess fractional seconds."""
+ dt = parse_iso_datetime("2026-03-26T01:26:14.481Z")
+
+ assert dt.tzinfo is not None
+ assert dt.utcoffset() == timezone.utc.utcoffset(dt)
+
+ def test_parse_with_timezone_offset(self):
+ """Test parsing with non-UTC timezone offset."""
+ dt = parse_iso_datetime("2026-03-26T18:30:00+08:00")
+
+ # 18:30+08:00 = 10:30 UTC
+ dt_utc = dt.astimezone(timezone.utc)
+ assert dt_utc.hour == 10
+ assert dt_utc.minute == 30
+
+ def test_parse_negative_timezone_offset(self):
+ """Test parsing with negative timezone offset."""
+ dt = parse_iso_datetime("2026-03-26T05:30:00-05:00")
+
+ # 05:30-05:00 = 10:30 UTC
+ dt_utc = dt.astimezone(timezone.utc)
+ assert dt_utc.hour == 10
+ assert dt_utc.minute == 30
+
+ def test_parse_milliseconds_only(self):
+ """Test parsing with milliseconds only."""
+ dt = parse_iso_datetime("2026-03-26T10:30:00.123+00:00")
+
+ assert dt.microsecond == 123000
+
+ def test_parse_no_fractional_seconds(self):
+ """Test parsing without fractional seconds."""
+ dt = parse_iso_datetime("2026-03-26T10:30:00+00:00")
+
+ assert dt.microsecond == 0
+
+
+class TestFormatIso8601:
+ """Test format_iso8601 function."""
+
+ def test_format_utc_datetime(self):
+ """Test formatting UTC datetime."""
+ dt = datetime(2026, 3, 26, 10, 30, 0, tzinfo=timezone.utc)
+ formatted = format_iso8601(dt)
+
+ assert formatted == "2026-03-26T10:30:00.000Z"
+
+ def test_format_naive_datetime_assumes_utc(self):
+ """Test formatting naive datetime assumes UTC."""
+ dt = datetime(2026, 3, 26, 10, 30, 0)
+ formatted = format_iso8601(dt)
+
+ assert formatted == "2026-03-26T10:30:00.000Z"
+
+ def test_format_converts_to_utc(self):
+ """Test formatting converts non-UTC to UTC."""
+ dt = datetime(2026, 3, 26, 18, 30, 0, tzinfo=timezone(timedelta(hours=8)))
+ formatted = format_iso8601(dt)
+
+ # 18:30+08:00 = 10:30 UTC
+ assert formatted == "2026-03-26T10:30:00.000Z"
+
+ def test_format_with_milliseconds(self):
+ """Test formatting preserves milliseconds."""
+ dt = datetime(2026, 3, 26, 10, 30, 0, 123456, tzinfo=timezone.utc)
+ formatted = format_iso8601(dt)
+
+ assert formatted == "2026-03-26T10:30:00.123Z"
+
+ def test_format_with_negative_timezone(self):
+ """Test formatting converts negative timezone to UTC."""
+ dt = datetime(2026, 3, 26, 5, 30, 0, tzinfo=timezone(timedelta(hours=-5)))
+ formatted = format_iso8601(dt)
+
+ # 05:30-05:00 = 10:30 UTC
+ assert formatted == "2026-03-26T10:30:00.000Z"
+
+ def test_format_ends_with_z(self):
+ """Test formatted string ends with Z."""
+ dt = datetime(2026, 3, 26, 10, 30, 0, tzinfo=timezone.utc)
+ formatted = format_iso8601(dt)
+
+ assert formatted.endswith("Z")
+
+
+class TestFormatSimplified:
+ """Test format_simplified function."""
+
+ def test_format_same_day_shows_time(self):
+ """Test formatting shows time for same day."""
+ now = datetime(2026, 3, 26, 15, 0, 0)
+ dt = datetime(2026, 3, 26, 10, 30, 0)
+
+ formatted = format_simplified(dt, now)
+
+ assert formatted == "10:30:00"
+
+ def test_format_different_day_shows_date(self):
+ """Test formatting shows date for different day."""
+ now = datetime(2026, 3, 26, 15, 0, 0)
+ dt = datetime(2026, 3, 25, 10, 30, 0)
+
+ formatted = format_simplified(dt, now)
+
+ assert formatted == "2026-03-25"
+
+ def test_format_older_date_shows_date(self):
+ """Test formatting shows date for older dates."""
+ now = datetime(2026, 3, 26, 15, 0, 0)
+ dt = datetime(2025, 12, 1, 10, 30, 0)
+
+ formatted = format_simplified(dt, now)
+
+ assert formatted == "2025-12-01"
+
+ def test_format_just_under_24h_shows_time(self):
+ """Test formatting shows time for just under 24 hours."""
+ now = datetime(2026, 3, 26, 15, 0, 0)
+ dt = datetime(2026, 3, 25, 16, 0, 0)
+
+ formatted = format_simplified(dt, now)
+
+ # 16:00 is less than 24 hours ago
+ assert formatted == "16:00:00"
+
+ def test_format_just_over_24h_shows_date(self):
+ """Test formatting shows date for just over 24 hours."""
+ now = datetime(2026, 3, 26, 15, 0, 0)
+ dt = datetime(2026, 3, 25, 14, 0, 0)
+
+ formatted = format_simplified(dt, now)
+
+ # 14:00 is more than 24 hours ago
+ assert formatted == "2026-03-25"
+
+
+class TestGetCurrentTimestamp:
+ """Test get_current_timestamp function."""
+
+ def test_returns_string(self):
+ """Test function returns string."""
+ ts = get_current_timestamp()
+
+ assert isinstance(ts, str)
+
+ def test_ends_with_z(self):
+ """Test timestamp ends with Z."""
+ ts = get_current_timestamp()
+
+ assert ts.endswith("Z")
+
+ def test_format_is_correct(self):
+ """Test timestamp format is correct."""
+ ts = get_current_timestamp()
+
+ # Should match pattern: YYYY-MM-DDTHH:MM:SS.sssZ
+ assert len(ts) == 24
+ assert ts[4] == "-"
+ assert ts[7] == "-"
+ assert ts[10] == "T"
+ assert ts[13] == ":"
+ assert ts[16] == ":"
+ assert ts[19] == "."
+
+ def test_is_utc(self):
+ """Test timestamp is in UTC."""
+ ts = get_current_timestamp()
+
+ # Parse it back and verify it's a valid timestamp
+ dt = parse_iso_datetime(ts)
+ assert dt.tzinfo is not None
+
+
+class TestTimeUtilsRoundTrip:
+ """Test round-trip conversions."""
+
+ def test_format_parse_roundtrip(self):
+ """Test format -> parse roundtrip preserves values."""
+ original = datetime(2026, 3, 26, 10, 30, 15, 123456, tzinfo=timezone.utc)
+
+ formatted = format_iso8601(original)
+ parsed = parse_iso_datetime(formatted)
+
+ # Note: milliseconds precision, so microseconds may differ
+ assert parsed.year == original.year
+ assert parsed.month == original.month
+ assert parsed.day == original.day
+ assert parsed.hour == original.hour
+ assert parsed.minute == original.minute
+ assert parsed.second == original.second
+
+ def test_current_timestamp_roundtrip(self):
+ """Test get_current_timestamp can be parsed."""
+ ts = get_current_timestamp()
+ parsed = parse_iso_datetime(ts)
+
+ assert parsed.tzinfo is not None
+ assert parsed.year >= 2025 # Sanity check
+
+
+class TestTimeUtilsEdgeCases:
+ """Test edge cases for time utilities."""
+
+ def test_parse_min_datetime(self):
+ """Test parsing minimum datetime."""
+ dt = parse_iso_datetime("0001-01-01T00:00:00Z")
+
+ assert dt.year == 1
+ assert dt.month == 1
+ assert dt.day == 1
+
+ def test_parse_max_datetime(self):
+ """Test parsing maximum datetime."""
+ dt = parse_iso_datetime("9999-12-31T23:59:59.999999Z")
+
+ assert dt.year == 9999
+ assert dt.month == 12
+ assert dt.day == 31
+
+ def test_parse_leap_second(self):
+ """Test parsing with leap second (60 seconds)."""
+ # Note: Python's datetime doesn't actually support leap seconds
+ # but we test that the parsing logic doesn't crash
+ try:
+ dt = parse_iso_datetime("2026-03-26T10:30:60Z")
+ # If it succeeds, verify it's a valid datetime
+ assert dt.minute == 30
+ except ValueError:
+ # Python may reject leap seconds, which is fine
+ pass
+
+ def test_parse_midnight(self):
+ """Test parsing midnight."""
+ dt = parse_iso_datetime("2026-03-26T00:00:00Z")
+
+ assert dt.hour == 0
+ assert dt.minute == 0
+ assert dt.second == 0
+
+ def test_format_midnight(self):
+ """Test formatting midnight."""
+ dt = datetime(2026, 3, 26, 0, 0, 0, tzinfo=timezone.utc)
+ formatted = format_iso8601(dt)
+
+ assert formatted == "2026-03-26T00:00:00.000Z"
+
+ def test_parse_different_timezone_formats(self):
+ """Test parsing various timezone formats."""
+ formats = [
+ "2026-03-26T10:30:00Z",
+ "2026-03-26T10:30:00+00:00",
+ "2026-03-26T10:30:00-00:00",
+ ]
+
+ for fmt in formats:
+ dt = parse_iso_datetime(fmt)
+ dt_utc = dt.astimezone(timezone.utc)
+ assert dt_utc.hour == 10
+ assert dt_utc.minute == 30
+
+ def test_format_daylight_saving_transition(self):
+ """Test formatting during DST transition."""
+ # This is mainly to ensure no crashes during DST transitions
+ dt = datetime(2026, 3, 8, 2, 30, 0, tzinfo=timezone.utc)
+ formatted = format_iso8601(dt)
+
+ assert formatted == "2026-03-08T02:30:00.000Z"