Skip to content

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

feat: 添加完整的 API 测试套件 (#950)

kaisonglif32af085d72b
diff --git a/.github/workflows/api_test.yml b/.github/workflows/api_test.yml
new file mode 100644
index 000000000..c15102097
--- /dev/null
+++ b/.github/workflows/api_test.yml
@@ -0,0 +1,283 @@
+name: 03. API Integration Tests
+
+on:
+ workflow_dispatch:
+ push:
+ branches:
+ - 'api_test'
+ paths-ignore:
+ - 'docs/**'
+ - '**.md'
+ - 'LICENSE'
+ - 'CONTRIBUTING.md'
+ - '**.png'
+ - '**.jpg'
+ - '**.jpeg'
+ - '**.gif'
+ - '**.svg'
+ - '.gitignore'
+ - '.editorconfig'
+ pull_request:
+ branches:
+ - 'main'
+ - 'develop'
+ paths-ignore:
+ - 'docs/**'
+ - '**.md'
+ - 'LICENSE'
+ - 'CONTRIBUTING.md'
+ - '**.png'
+ - '**.jpg'
+ - '**.jpeg'
+ - '**.gif'
+ - '**.svg'
+ - '.gitignore'
+ - '.editorconfig'
+
+# 同一 PR 只运行最新的一次,取消之前的运行
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ api-tests:
+ name: API Integration Tests
+ runs-on: ubuntu-24.04
+
+ steps:
+ - uses: actions/checkout@v6
+ with:
+ submodules: recursive
+
+ - name: Set up Python 3.10
+ uses: actions/setup-python@v6
+ with:
+ python-version: '3.10'
+
+ - name: Cache Go modules
+ uses: actions/cache@v4
+ with:
+ path: ~/go/pkg/mod
+ key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
+ restore-keys: |
+ ${{ runner.os }}-go-
+
+ - name: Cache C++ extensions
+ uses: actions/cache@v4
+ with:
+ path: openviking/pyagfs
+ key: ${{ runner.os }}-cpp-${{ hashFiles('**/CMakeLists.txt', '**/*.cpp', '**/*.h') }}
+ restore-keys: |
+ ${{ runner.os }}-cpp-
+
+ - name: Cache Python dependencies
+ uses: actions/cache@v4
+ with:
+ path: ~/.cache/pip
+ key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt', '**/pyproject.toml') }}
+ restore-keys: |
+ ${{ runner.os }}-pip-
+
+ - name: Set up Go
+ uses: actions/setup-go@v6
+ with:
+ go-version: '1.25.1'
+
+ - name: Install system dependencies (Ubuntu)
+ run: |
+ sudo apt-get update -y && sudo apt-get install -y cmake build-essential --no-install-recommends
+
+ - name: Install uv
+ uses: astral-sh/setup-uv@v7
+ with:
+ enable-cache: true
+
+ - name: Install build dependencies (system pip)
+ run: |
+ python -m pip install --upgrade pip
+ pip install "setuptools>=70.1" setuptools_scm cmake wheel
+ echo "---"
+ python -c "import setuptools; print(f'setuptools version: {setuptools.__version__}')"
+
+ - name: Install dependencies using uv sync
+ run: |
+ echo "Installing dependencies using uv sync..."
+ uv sync --frozen
+
+ - name: Install build dependencies (uv pip)
+ run: |
+ echo "Installing build dependencies to uv environment..."
+ uv pip install setuptools setuptools_scm cmake wheel
+
+ - name: Build C++ extensions
+ run: |
+ uv run python setup.py build_ext --inplace
+
+ - name: Install API test dependencies
+ run: |
+ cd tests/api_test
+ uv pip install -r requirements.txt
+
+ - name: Create OpenViking config file
+ id: create-config
+ env:
+ VLM_API_KEY: ${{ secrets.VLM_API_KEY }}
+ EMBEDDING_API_KEY: ${{ secrets.EMBEDDING_API_KEY }}
+ run: |
+ # 创建配置目录
+ mkdir -p /home/runner/.openviking
+
+ # 检查是否有有效的 API keys
+ HAS_SECRETS=false
+ if [ -n "$VLM_API_KEY" ] && [ -n "$EMBEDDING_API_KEY" ]; then
+ HAS_SECRETS=true
+ echo "Using full configuration with VLM and Embedding"
+ else
+ echo "Using minimal configuration (no VLM/Embedding)"
+ fi
+
+ echo "HAS_SECRETS=$HAS_SECRETS" >> $GITHUB_ENV
+
+ if [ "$HAS_SECRETS" = "true" ]; then
+ # 完整配置(含 VLM 和 Embedding
+ cat > /home/runner/.openviking/ov.conf << EOF
+ {
+ "server": {
+ "root_api_key": "test-root-api-key"
+ },
+ "vlm": {
+ "provider": "volcengine",
+ "api_key": "$VLM_API_KEY",
+ "model": "doubao-seed-2-0-mini-260215",
+ "api_base": "https://ark.cn-beijing.volces.com/api/v3",
+ "temperature": 0.1,
+ "max_retries": 3
+ },
+ "embedding": {
+ "dense": {
+ "provider": "volcengine",
+ "api_key": "$EMBEDDING_API_KEY",
+ "model": "doubao-embedding-vision-251215",
+ "api_base": "https://ark.cn-beijing.volces.com/api/v3",
+ "dimension": 1024,
+ "input": "multimodal"
+ }
+ }
+ }
+ EOF
+ else
+ # 最小配置(使用 dummy API keys,不会实际调用)
+ cat > /home/runner/.openviking/ov.conf << EOF
+ {
+ "server": {
+ "root_api_key": "test-root-api-key"
+ },
+ "vlm": {
+ "provider": "volcengine",
+ "api_key": "dummy-vlm-api-key",
+ "model": "doubao-seed-2-0-mini-260215",
+ "api_base": "https://ark.cn-beijing.volces.com/api/v3",
+ "temperature": 0.1,
+ "max_retries": 3
+ },
+ "embedding": {
+ "dense": {
+ "provider": "volcengine",
+ "api_key": "dummy-embedding-api-key",
+ "model": "doubao-embedding-vision-251215",
+ "api_base": "https://ark.cn-beijing.volces.com/api/v3",
+ "dimension": 1024,
+ "input": "multimodal"
+ }
+ }
+ }
+ EOF
+ fi
+
+ echo "Config file created at /home/runner/.openviking/ov.conf"
+
+ - name: Find available port and start OpenViking Server
+ id: start-server
+ run: |
+ # 找到可用的随机端口
+ find_available_port() {
+ local port=1933
+ while true; do
+ if ! lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
+ echo $port
+ return
+ fi
+ port=$((port + 1))
+ done
+ }
+
+ SERVER_PORT=$(find_available_port)
+ echo "Using port: $SERVER_PORT"
+ echo "SERVER_PORT=$SERVER_PORT" >> $GITHUB_ENV
+
+ echo "Starting OpenViking Server on port $SERVER_PORT..."
+ export ROOT_API_KEY=test-root-api-key
+ export SERVER_PORT=$SERVER_PORT
+ nohup uv run python -m openviking.server.bootstrap > openviking-server.log 2>&1 &
+ echo $! > openviking-server.pid
+ echo "SERVER_PID=$(cat openviking-server.pid)" >> $GITHUB_ENV
+
+ echo "Waiting for server to start..."
+ for i in {1..30}; do
+ if curl -s http://127.0.0.1:$SERVER_PORT/health | grep -q '"healthy":true'; then
+ echo "Server is ready!"
+ break
+ fi
+ echo "Waiting... ($i/30)"
+ sleep 2
+ done
+
+ # Check if server started successfully
+ if ! curl -s http://127.0.0.1:$SERVER_PORT/health | grep -q '"healthy":true'; then
+ echo "Server failed to start!"
+ echo "Server logs:"
+ cat openviking-server.log
+ exit 1
+ fi
+
+ - name: Run API Tests
+ id: run-tests
+ run: |
+ cd tests/api_test
+ export OPENVIKING_API_KEY=test-root-api-key
+ export SERVER_URL=http://127.0.0.1:${{ env.SERVER_PORT }}
+
+ if [ "${{ env.HAS_SECRETS }}" = "true" ]; then
+ echo "Running full test suite with VLM/Embedding"
+ uv run python -m pytest . -v --html=api-test-report.html --self-contained-html
+ else
+ echo "Running basic tests only (no VLM/Embedding)"
+ uv run python -m pytest . -v --html=api-test-report.html --self-contained-html \
+ --ignore=retrieval/ --ignore=resources/test_pack.py --ignore=resources/test_wait_processed.py \
+ --ignore=admin/ --ignore=skills/ --ignore=system/test_system_status.py --ignore=system/test_is_healthy.py --ignore=system/test_system_wait.py -k "not test_observer"
+ fi
+ continue-on-error: true
+
+ - name: Upload test reports
+ uses: actions/upload-artifact@v7
+ if: always()
+ with:
+ name: api-test-reports-${{ github.run_id }}
+ path: |
+ tests/api_test/api-test-report.html
+ openviking-server.log
+
+ - name: Stop OpenViking Server
+ if: always()
+ run: |
+ if [ -f openviking-server.pid ]; then
+ kill $(cat openviking-server.pid) 2>/dev/null || true
+ # 确保完全清理
+ pkill -f "openviking.server.bootstrap" 2>/dev/null || true
+ fi
+
+ - name: Check test results
+ if: steps.run-tests.outcome != 'success'
+ run: |
+ echo "API tests failed!"
+ exit 1
diff --git a/.gitignore b/.gitignore
index a3f187325..f149cd90d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -54,6 +54,10 @@ coverage.xml
cover/
test_data/
test_data_sync/
+reports/
+test-results.xml
+test-reports/
+report.html
# Virtual environments
.env
@@ -77,6 +81,9 @@ venv.bak/
.AppleDouble
.LSOverride
+# Windows
+Thumbs.db
+
# Thumbnails
._*
@@ -96,6 +103,12 @@ Network Trash Folder
Temporary Items
.apdisk
+# Config files - contains sensitive information
+config/settings.py
+
+# Docker
+docker-compose.override.yml
+
# OpenViking specific
/data/*
/demo_data/*
@@ -103,6 +116,13 @@ Temporary Items
.claude
.openviking
*.code-workspace
+.openviking.pid
+exports/
+
+# API Test temporary files
+tests/api_test/api-test-report.html
+tests/api_test/openviking-server.log
+tests/api_test/openviking-server.pid
# AI Coding
CLAUDE.md
diff --git a/tests/api_test/README.md b/tests/api_test/README.md
new file mode 100644
index 000000000..04117a8e4
--- /dev/null
+++ b/tests/api_test/README.md
@@ -0,0 +1,146 @@
+# OpenViking API 自动化测试
+
+本目录包含 OpenViking 的 API 集成测试套件。
+
+## 目录结构
+
+```
+tests/api_test/
+├── admin/ # 管理 API 测试
+├── api/ # API 客户端实现
+├── conftest.py # pytest fixtures 和配置
+├── filesystem/ # 文件系统 API 测试
+├── health_check/ # 健康检查测试
+├── pytest.ini # pytest 配置
+├── requirements.txt # 测试依赖
+├── resources/ # 资源管理 API 测试
+├── retrieval/ # 检索 API 测试
+├── scenarios/ # 场景级集成测试
+├── services/ # 服务管理模块
+├── sessions/ # 会话 API 测试
+├── system/ # 系统 API 测试
+└── tools/ # 工具模块
+```
+
+## 本地运行测试
+
+### 前置条件
+
+1. Python 3.10+
+2. OpenViking Server 已启动(默认端口 1933)
+
+### 安装依赖
+
+```bash
+cd tests/api_test
+pip install -r requirements.txt
+```
+
+### 运行测试
+
+#### 一键本地测试(推荐)
+
+使用提供的脚本模拟完整的 CI 流水线流程:
+
+```bash
+cd tests/api_test
+./local-test.sh
+```
+
+这个脚本会自动:
+1. 检查 Python 版本
+2. 安装 OpenViking
+3. 安装测试依赖
+4. 启动 OpenViking Server(自动找可用端口)
+5. 运行所有 API 测试
+6. 停止服务并清理
+
+#### 手动运行测试
+
+```bash
+# 运行所有测试
+python -m pytest . -v
+
+# 运行特定模块测试
+python -m pytest admin/ -v
+python -m pytest filesystem/ -v
+python -m pytest sessions/ -v
+
+# 运行特定测试文件
+python -m pytest health_check/test_server_health_check.py -v
+
+# 生成 HTML 报告
+python -m pytest . -v --html=api-test-report.html --self-contained-html
+```
+
+### 环境变量配置
+
+测试通过环境变量配置,无需修改代码:
+
+| 环境变量 | 说明 | 默认值 |
+|---------|------|--------|
+| `SERVER_HOST` | OpenViking Server 主机 | 127.0.0.1 |
+| `SERVER_PORT` | OpenViking Server 端口 | 1933 |
+| `OPENVIKING_API_KEY` | API 密钥 | test-root-api-key |
+| `VLM_API_KEY` | VLM 模型密钥(可选) | - |
+| `EMBEDDING_API_KEY` | Embedding 模型密钥(可选) | - |
+
+示例:
+
+```bash
+export SERVER_PORT=1934
+export VLM_API_KEY=your-vlm-key
+export EMBEDDING_API_KEY=your-embedding-key
+python -m pytest retrieval/ -v
+```
+
+## CI/CD 流水线
+
+### 工作流文件
+
+`.github/workflows/api_test.yml` - API 集成测试流水线
+
+### 流水线特性
+
+- ✅ 智能构建复用:只在依赖变更时重新构建
+- ✅ 并发安全:同一 PR 自动取消旧的运行
+- ✅ 动态端口:自动查找可用端口避免冲突
+- ✅ Secrets 支持:安全传递 API 密钥
+
+### 配置 GitHub Secrets
+
+为了运行完整的检索测试,需要在仓库中配置以下 Secrets:
+
+1. 进入仓库 **Settings** → **Secrets and variables** → **Actions**
+2. 点击 **New repository secret**
+3. 添加以下 Secrets:
+
+| Secret 名称 | 说明 |
+|------------|------|
+| `VLM_API_KEY` | VLM 模型 API 密钥 |
+| `EMBEDDING_API_KEY` | Embedding 模型 API 密钥 |
+
+## 测试覆盖范围
+
+### 接口测试
+
+| 模块 | 测试用例数 | 说明 |
+|------|----------|------|
+| admin | 6 | 账户、用户、角色、密钥管理 |
+| filesystem | 10 | 文件系统操作 |
+| health_check | 1 | 服务健康检查 |
+| resources | 3 | 资源管理 |
+| retrieval | 4 | 搜索和检索 |
+| sessions | 6 | 会话管理 |
+| system | 4 | 系统管理 |
+
+## 注意事项
+
+1. **不要提交敏感信息**:`.env` 和 `ov.conf` 已在 `.gitignore` 中
+2. **检索测试需要密钥**:`retrieval/` 和部分 `scenarios/` 测试需要 VLM 和 Embedding API 密钥
+3. **CI 与本地一致**:CI 流水线使用与本地相同的测试框架和配置
+
+## 相关文档
+
+- OpenViking API 文档:`docs/zh/api/`
+- CI/CD 配置:`.github/workflows/api_test.yml`
diff --git a/tests/api_test/__init__.py b/tests/api_test/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/api_test/admin/test_admin_accounts.py b/tests/api_test/admin/test_admin_accounts.py
new file mode 100644
index 000000000..c66edb27f
--- /dev/null
+++ b/tests/api_test/admin/test_admin_accounts.py
@@ -0,0 +1,64 @@
+import json
+import uuid
+
+
+class TestAdminAccounts:
+ def test_admin_list_accounts(self, api_client):
+ try:
+ response = api_client.admin_list_accounts()
+ print(f"\nAdmin list accounts API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Admin List Accounts API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert isinstance(data["result"], list), "'result' should be a list"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
+
+ def test_admin_create_delete_account(self, api_client):
+ random_id = str(uuid.uuid4())[:8]
+ test_account_id = f"test-account-{random_id}"
+ test_admin_user_id = f"test-admin-{random_id}"
+
+ try:
+ response = api_client.admin_create_account(test_account_id, test_admin_user_id)
+ print(f"\nAdmin create account API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Admin Create Account API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert data["result"]["account_id"] == test_account_id, "Account ID mismatch"
+ assert data["result"]["admin_user_id"] == test_admin_user_id, "Admin user ID mismatch"
+
+ response = api_client.admin_delete_account(test_account_id)
+ print(f"\nAdmin delete account API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Admin Delete Account API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/admin/test_admin_regenerate_key.py b/tests/api_test/admin/test_admin_regenerate_key.py
new file mode 100644
index 000000000..f868dbf3c
--- /dev/null
+++ b/tests/api_test/admin/test_admin_regenerate_key.py
@@ -0,0 +1,37 @@
+import json
+import uuid
+
+
+class TestAdminRegenerateKey:
+ def test_admin_regenerate_key(self, api_client):
+ random_id = str(uuid.uuid4())[:8]
+ test_user_id = f"test-user-{random_id}"
+
+ try:
+ response = api_client.admin_register_user("default", test_user_id, "user")
+ print(f"\nAdmin register user API status code: {response.status_code}")
+
+ data = response.json()
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ response = api_client.admin_regenerate_key("default", test_user_id)
+ print(f"\nAdmin regenerate key API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Admin Regenerate Key API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert "user_key" in data["result"], "'user_key' field should exist"
+
+ response = api_client.admin_remove_user("default", test_user_id)
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/admin/test_admin_role.py b/tests/api_test/admin/test_admin_role.py
new file mode 100644
index 000000000..40d5f1a84
--- /dev/null
+++ b/tests/api_test/admin/test_admin_role.py
@@ -0,0 +1,36 @@
+import json
+import uuid
+
+
+class TestAdminRole:
+ def test_admin_set_role(self, api_client):
+ random_id = str(uuid.uuid4())[:8]
+ test_user_id = f"test-user-{random_id}"
+
+ try:
+ response = api_client.admin_register_user("default", test_user_id, "user")
+ print(f"\nAdmin register user API status code: {response.status_code}")
+
+ data = response.json()
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ response = api_client.admin_set_role("default", test_user_id, "admin")
+ print(f"\nAdmin set role API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Admin Set Role API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+
+ response = api_client.admin_remove_user("default", test_user_id)
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/admin/test_admin_users.py b/tests/api_test/admin/test_admin_users.py
new file mode 100644
index 000000000..f65ac340e
--- /dev/null
+++ b/tests/api_test/admin/test_admin_users.py
@@ -0,0 +1,62 @@
+import json
+import uuid
+
+
+class TestAdminUsers:
+ def test_admin_list_users(self, api_client):
+ try:
+ response = api_client.admin_list_users("default")
+ print(f"\nAdmin list users API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Admin List Users API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert isinstance(data["result"], list), "'result' should be a list"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
+
+ def test_admin_register_remove_user(self, api_client):
+ random_id = str(uuid.uuid4())[:8]
+ test_user_id = f"test-user-{random_id}"
+
+ try:
+ response = api_client.admin_register_user("default", test_user_id, "user")
+ print(f"\nAdmin register user API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Admin Register User API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert data["result"]["user_id"] == test_user_id, "User ID mismatch"
+
+ response = api_client.admin_remove_user("default", test_user_id)
+ print(f"\nAdmin remove user API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Admin Remove User API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/api/__init__.py b/tests/api_test/api/__init__.py
new file mode 100644
index 000000000..70f486e4c
--- /dev/null
+++ b/tests/api_test/api/__init__.py
@@ -0,0 +1,3 @@
+from .client import OpenVikingAPIClient
+
+__all__ = ["OpenVikingAPIClient"]
diff --git a/tests/api_test/api/client.py b/tests/api_test/api/client.py
new file mode 100644
index 000000000..2562cd2bd
--- /dev/null
+++ b/tests/api_test/api/client.py
@@ -0,0 +1,463 @@
+import json
+import time
+from typing import Any, Dict, Optional
+from urllib.parse import urlencode
+
+import requests
+from config import Config
+
+
+class OpenVikingAPIClient:
+ def __init__(
+ self,
+ base_url: Optional[str] = None,
+ server_url: Optional[str] = None,
+ api_key: Optional[str] = None,
+ account: Optional[str] = None,
+ user: Optional[str] = None,
+ ):
+ self.base_url = base_url or Config.CONSOLE_URL
+ self.server_url = server_url or Config.SERVER_URL
+ self.api_key = api_key or Config.OPENVIKING_API_KEY
+ self.account = account or Config.OPENVIKING_ACCOUNT
+ self.user = user or Config.OPENVIKING_USER
+ self.session = requests.Session()
+ self._setup_default_headers()
+ self.max_retries = 3
+ self.retry_delay = 0.5
+ self.last_request_info = None
+
+ def _filter_sensitive_headers(self, headers: Dict[str, str]) -> Dict[str, str]:
+ """过滤敏感头信息"""
+ filtered = {}
+ sensitive_headers_lower = {"authorization"}
+ for key, value in headers.items():
+ if key.lower() in sensitive_headers_lower:
+ filtered[key] = "[REDACTED]"
+ else:
+ filtered[key] = value
+ return filtered
+
+ def _filter_sensitive_data(self, data: Any) -> Any:
+ """过滤敏感数据"""
+ if isinstance(data, dict):
+ filtered = {}
+ for key, value in data.items():
+ if key.lower() in ["api_key", "apikey", "password", "secret", "token"]:
+ filtered[key] = "[REDACTED]"
+ else:
+ filtered[key] = self._filter_sensitive_data(value)
+ return filtered
+ elif isinstance(data, list):
+ return [self._filter_sensitive_data(item) for item in data]
+ else:
+ return data
+
+ def _request_with_retry(self, method: str, url: str, **kwargs) -> requests.Response:
+ filtered_headers = self._filter_sensitive_headers(dict(self.session.headers))
+ filtered_kwargs = self._filter_sensitive_data(kwargs)
+
+ self.last_request_info = {
+ "method": method,
+ "url": url,
+ "headers": filtered_headers,
+ **filtered_kwargs,
+ }
+ for attempt in range(self.max_retries):
+ try:
+ response = self.session.request(method, url, **kwargs)
+ return response
+ except (
+ requests.exceptions.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ ):
+ if attempt == self.max_retries - 1:
+ raise
+ time.sleep(self.retry_delay * (attempt + 1))
+
+ def to_curl(self) -> Optional[str]:
+ if not self.last_request_info:
+ return None
+
+ info = self.last_request_info
+ parts = ["curl -X", info["method"].upper()]
+
+ if "headers" in info:
+ for key, value in info["headers"].items():
+ parts.append(f'-H "{key}: {value}"')
+
+ if "json" in info and info["json"]:
+ parts.append(f"-d '{json.dumps(info['json'], ensure_ascii=False)}'")
+ parts.append('-H "Content-Type: application/json"')
+
+ parts.append(f'"{info["url"]}"')
+ return " ".join(parts)
+
+ def _setup_default_headers(self):
+ headers = {
+ "Accept": "*/*",
+ "Accept-Language": "zh-CN,zh;q=0.9",
+ "Connection": "keep-alive",
+ "Content-Type": "application/json",
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
+ "X-OpenViking-Account": self.account,
+ "X-OpenViking-User": self.user,
+ }
+ if self.api_key:
+ headers["Authorization"] = f"Bearer {self.api_key}"
+ self.session.headers.update(headers)
+
+ def _build_url(self, base: str, endpoint: str, params: Optional[Dict[str, Any]] = None) -> str:
+ url = f"{base}{endpoint}"
+ if params:
+ url = f"{url}?{urlencode(params)}"
+ return url
+
+ def find(
+ self,
+ query: str,
+ target_uri: Optional[str] = None,
+ limit: int = 10,
+ score_threshold: Optional[float] = None,
+ filter: Optional[Dict[str, Any]] = None,
+ ) -> requests.Response:
+ endpoint = "/api/v1/search/find"
+ url = self._build_url(self.server_url, endpoint)
+ payload = {"query": query, "limit": limit}
+ if target_uri:
+ payload["target_uri"] = target_uri
+ if score_threshold is not None:
+ payload["score_threshold"] = score_threshold
+ if filter:
+ payload["filter"] = filter
+ return self._request_with_retry("POST", url, json=payload)
+
+ def search(
+ self,
+ query: str,
+ target_uri: Optional[str] = None,
+ session_id: Optional[str] = None,
+ limit: int = 10,
+ score_threshold: Optional[float] = None,
+ filter: Optional[Dict[str, Any]] = None,
+ ) -> requests.Response:
+ endpoint = "/api/v1/search/search"
+ url = self._build_url(self.server_url, endpoint)
+ payload = {"query": query, "limit": limit}
+ if target_uri:
+ payload["target_uri"] = target_uri
+ if session_id:
+ payload["session_id"] = session_id
+ if score_threshold is not None:
+ payload["score_threshold"] = score_threshold
+ if filter:
+ payload["filter"] = filter
+ return self._request_with_retry("POST", url, json=payload)
+
+ def grep(self, uri: str, pattern: str, case_insensitive: bool = False) -> requests.Response:
+ endpoint = "/api/v1/search/grep"
+ url = self._build_url(self.server_url, endpoint)
+ payload = {"uri": uri, "pattern": pattern, "case_insensitive": case_insensitive}
+ return self._request_with_retry("POST", url, json=payload)
+
+ def glob(self, pattern: str, uri: Optional[str] = None) -> requests.Response:
+ endpoint = "/api/v1/search/glob"
+ url = self._build_url(self.server_url, endpoint)
+ payload = {"pattern": pattern}
+ if uri:
+ payload["uri"] = uri
+ return self._request_with_retry("POST", url, json=payload)
+
+ def read_content(self, uri: str, offset: int = 0, limit: int = -1) -> requests.Response:
+ endpoint = "/console/api/v1/ov/content/read"
+ params = {"uri": uri, "offset": offset, "limit": limit}
+ url = self._build_url(self.base_url, endpoint, params)
+ return self.session.get(url)
+
+ def list_contents(self, path: str, offset: int = 0, limit: int = 100) -> requests.Response:
+ endpoint = "/console/api/v1/ov/content/list"
+ params = {"path": path, "offset": offset, "limit": limit}
+ url = self._build_url(self.base_url, endpoint, params)
+ return self.session.get(url)
+
+ def write_content(self, uri: str, content: str) -> requests.Response:
+ endpoint = "/console/api/v1/ov/content/write"
+ params = {"uri": uri}
+ url = self._build_url(self.base_url, endpoint, params)
+ return self.session.post(url, json={"content": content})
+
+ def delete_content(self, uri: str) -> requests.Response:
+ endpoint = "/console/api/v1/ov/content/delete"
+ params = {"uri": uri}
+ url = self._build_url(self.base_url, endpoint, params)
+ return self.session.delete(url)
+
+ def health_check(self) -> requests.Response:
+ return self.session.get(f"{self.base_url}/")
+
+ def server_health_check(self) -> requests.Response:
+ return self.session.get(f"{self.server_url}/health")
+
+ def add_resource(
+ self,
+ path: str,
+ to: Optional[str] = None,
+ reason: Optional[str] = None,
+ wait: bool = False,
+ ) -> requests.Response:
+ endpoint = "/api/v1/resources"
+ url = self._build_url(self.server_url, endpoint)
+ payload = {"path": path}
+ if to:
+ payload["to"] = to
+ if reason:
+ payload["reason"] = reason
+ if wait:
+ payload["wait"] = wait
+ return self._request_with_retry("POST", url, json=payload)
+
+ def wait_processed(self) -> requests.Response:
+ endpoint = "/api/v1/system/wait"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("POST", url, json={})
+
+ def create_session(self, session_id: Optional[str] = None) -> requests.Response:
+ endpoint = "/api/v1/sessions"
+ url = self._build_url(self.server_url, endpoint)
+ payload = {}
+ if session_id:
+ payload["session_id"] = session_id
+ return self._request_with_retry("POST", url, json=payload)
+
+ def list_sessions(self) -> requests.Response:
+ endpoint = "/api/v1/sessions"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("GET", url)
+
+ def get_session(self, session_id: str) -> requests.Response:
+ endpoint = f"/api/v1/sessions/{session_id}"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("GET", url)
+
+ def delete_session(self, session_id: str) -> requests.Response:
+ endpoint = f"/api/v1/sessions/{session_id}"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("DELETE", url)
+
+ def add_message(self, session_id: str, role: str, content: str) -> requests.Response:
+ endpoint = f"/api/v1/sessions/{session_id}/messages"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("POST", url, json={"role": role, "content": content})
+
+ def fs_ls(self, uri: str, simple: bool = False, recursive: bool = False) -> requests.Response:
+ endpoint = "/api/v1/fs/ls"
+ params = {"uri": uri, "simple": simple, "recursive": recursive}
+ url = self._build_url(self.server_url, endpoint, params)
+ return self._request_with_retry("GET", url)
+
+ def fs_tree(self, uri: str) -> requests.Response:
+ endpoint = "/api/v1/fs/tree"
+ params = {"uri": uri}
+ url = self._build_url(self.server_url, endpoint, params)
+ return self._request_with_retry("GET", url)
+
+ def fs_stat(self, uri: str) -> requests.Response:
+ endpoint = "/api/v1/fs/stat"
+ params = {"uri": uri}
+ url = self._build_url(self.server_url, endpoint, params)
+ return self._request_with_retry("GET", url)
+
+ def fs_mkdir(self, uri: str) -> requests.Response:
+ endpoint = "/api/v1/fs/mkdir"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("POST", url, json={"uri": uri})
+
+ def fs_read(self, uri: str) -> requests.Response:
+ endpoint = "/api/v1/content/read"
+ params = {"uri": uri}
+ url = self._build_url(self.server_url, endpoint, params)
+ return self._request_with_retry("GET", url)
+
+ def fs_write(self, uri: str, content: str) -> requests.Response:
+ endpoint = "/api/v1/content/write"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("POST", url, json={"uri": uri, "content": content})
+
+ def fs_rm(self, uri: str, recursive: bool = False) -> requests.Response:
+ endpoint = "/api/v1/fs"
+ params = {"uri": uri, "recursive": recursive}
+ url = self._build_url(self.server_url, endpoint, params)
+ return self._request_with_retry("DELETE", url)
+
+ def get_abstract(self, uri: str) -> requests.Response:
+ endpoint = "/api/v1/content/abstract"
+ params = {"uri": uri}
+ url = self._build_url(self.server_url, endpoint, params)
+ return self.session.get(url)
+
+ def get_overview(self, uri: str) -> requests.Response:
+ endpoint = "/api/v1/content/overview"
+ params = {"uri": uri}
+ url = self._build_url(self.server_url, endpoint, params)
+ return self.session.get(url)
+
+ def export_ovpack(self, uri: str, to: str) -> requests.Response:
+ endpoint = "/api/v1/pack/export"
+ url = self._build_url(self.server_url, endpoint)
+ return self.session.post(url, json={"uri": uri, "to": to})
+
+ def import_ovpack(
+ self, file_path: str, parent: str, force: bool = False, vectorize: bool = True
+ ) -> requests.Response:
+ endpoint = "/api/v1/pack/import"
+ url = self._build_url(self.server_url, endpoint)
+ return self.session.post(
+ url,
+ json={"file_path": file_path, "parent": parent, "force": force, "vectorize": vectorize},
+ )
+
+ def fs_mv(self, from_uri: str, to_uri: str) -> requests.Response:
+ endpoint = "/api/v1/fs/mv"
+ url = self._build_url(self.server_url, endpoint)
+ return self.session.post(url, json={"from_uri": from_uri, "to_uri": to_uri})
+
+ def link(self, from_uri: str, to_uris: Any, reason: str = "") -> requests.Response:
+ endpoint = "/api/v1/relations/link"
+ url = self._build_url(self.server_url, endpoint)
+ return self.session.post(
+ url, json={"from_uri": from_uri, "to_uris": to_uris, "reason": reason}
+ )
+
+ def relations(self, uri: str) -> requests.Response:
+ endpoint = "/api/v1/relations"
+ params = {"uri": uri}
+ url = self._build_url(self.server_url, endpoint, params)
+ return self.session.get(url)
+
+ def unlink(self, from_uri: str, to_uri: str) -> requests.Response:
+ endpoint = "/api/v1/relations/link"
+ url = self._build_url(self.server_url, endpoint)
+ return self.session.delete(url, json={"from_uri": from_uri, "to_uri": to_uri})
+
+ def session_used(
+ self,
+ session_id: str,
+ contexts: Optional[list] = None,
+ skill: Optional[Dict[str, Any]] = None,
+ ) -> requests.Response:
+ endpoint = f"/api/v1/sessions/{session_id}/used"
+ url = self._build_url(self.server_url, endpoint)
+ payload = {}
+ if contexts:
+ payload["contexts"] = contexts
+ if skill:
+ payload["skill"] = skill
+ return self.session.post(url, json=payload)
+
+ def session_commit(self, session_id: str) -> requests.Response:
+ endpoint = f"/api/v1/sessions/{session_id}/commit"
+ url = self._build_url(self.server_url, endpoint)
+ return self.session.post(url, json={})
+
+ def system_status(self) -> requests.Response:
+ endpoint = "/api/v1/system/status"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("GET", url)
+
+ def system_wait(self, timeout: Optional[float] = None) -> requests.Response:
+ endpoint = "/api/v1/system/wait"
+ url = self._build_url(self.server_url, endpoint)
+ payload = {}
+ if timeout is not None:
+ payload["timeout"] = timeout
+ return self._request_with_retry("POST", url, json=payload)
+
+ def observer_queue(self) -> requests.Response:
+ endpoint = "/api/v1/observer/queue"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("GET", url)
+
+ def observer_vikingdb(self) -> requests.Response:
+ endpoint = "/api/v1/observer/vikingdb"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("GET", url)
+
+ def observer_vlm(self) -> requests.Response:
+ endpoint = "/api/v1/observer/vlm"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("GET", url)
+
+ def observer_system(self) -> requests.Response:
+ endpoint = "/api/v1/observer/system"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("GET", url)
+
+ def is_healthy(self) -> requests.Response:
+ endpoint = "/api/v1/debug/health"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("GET", url)
+
+ def admin_create_account(self, account_id: str, admin_user_id: str) -> requests.Response:
+ endpoint = "/api/v1/admin/accounts"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry(
+ "POST", url, json={"account_id": account_id, "admin_user_id": admin_user_id}
+ )
+
+ def admin_list_accounts(self) -> requests.Response:
+ endpoint = "/api/v1/admin/accounts"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("GET", url)
+
+ def admin_delete_account(self, account_id: str) -> requests.Response:
+ endpoint = f"/api/v1/admin/accounts/{account_id}"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("DELETE", url)
+
+ def admin_register_user(
+ self, account_id: str, user_id: str, role: str = "user"
+ ) -> requests.Response:
+ endpoint = f"/api/v1/admin/accounts/{account_id}/users"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("POST", url, json={"user_id": user_id, "role": role})
+
+ def admin_list_users(self, account_id: str) -> requests.Response:
+ endpoint = f"/api/v1/admin/accounts/{account_id}/users"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("GET", url)
+
+ def admin_remove_user(self, account_id: str, user_id: str) -> requests.Response:
+ endpoint = f"/api/v1/admin/accounts/{account_id}/users/{user_id}"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("DELETE", url)
+
+ def admin_set_role(self, account_id: str, user_id: str, role: str) -> requests.Response:
+ endpoint = f"/api/v1/admin/accounts/{account_id}/users/{user_id}/role"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("PUT", url, json={"role": role})
+
+ def admin_regenerate_key(self, account_id: str, user_id: str) -> requests.Response:
+ endpoint = f"/api/v1/admin/accounts/{account_id}/users/{user_id}/key"
+ url = self._build_url(self.server_url, endpoint)
+ return self._request_with_retry("POST", url, json={})
+
+ def add_skill(
+ self, data: Any, wait: bool = False, timeout: Optional[float] = None
+ ) -> requests.Response:
+ endpoint = "/api/v1/skills"
+ url = self._build_url(self.server_url, endpoint)
+ payload = {"data": data}
+ if wait:
+ payload["wait"] = wait
+ if timeout is not None:
+ payload["timeout"] = timeout
+ return self._request_with_retry("POST", url, json=payload)
+
+ def close(self):
+ self.session.close()
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ self.close()
diff --git a/tests/api_test/config.py b/tests/api_test/config.py
new file mode 100644
index 000000000..d726a32d8
--- /dev/null
+++ b/tests/api_test/config.py
@@ -0,0 +1,6 @@
+#!/usr/bin/env python3
+"""Config module alias for compatibility"""
+
+from tools.config.config import Config
+
+__all__ = ["Config"]
diff --git a/tests/api_test/conftest.py b/tests/api_test/conftest.py
new file mode 100644
index 000000000..80a67be00
--- /dev/null
+++ b/tests/api_test/conftest.py
@@ -0,0 +1,447 @@
+import os
+
+import psutil
+import pytest
+from api.client import OpenVikingAPIClient
+from config import Config
+
+TEST_CASE_DESCRIPTIONS = {
+ "test_add_resource.py::TestAddResource::test_add_resource_simple": "向知识库添加资源",
+ "test_pack.py::TestPack::test_export_ovpack": "导出资源包",
+ "test_wait_processed.py::TestWaitProcessed::test_wait_processed": "等待资源处理完成",
+ "test_fs_ls.py::TestFsLs::test_fs_ls_root": "列出文件系统根目录",
+ "test_fs_mkdir.py::TestFsMkdir::test_fs_mkdir": "创建目录",
+ "test_fs_mv.py::TestFsMv::test_fs_mv": "移动文件/目录",
+ "test_fs_read_write.py::TestFsReadWrite::test_fs_read": "读取文件内容",
+ "test_fs_rm.py::TestFsRm::test_fs_rm": "删除文件/目录",
+ "test_fs_stat.py::TestFsStat::test_fs_stat": "获取文件状态",
+ "test_fs_tree.py::TestFsTree::test_fs_tree": "获取目录树结构",
+ "test_get_abstract.py::TestGetAbstract::test_get_abstract": "获取内容摘要",
+ "test_get_overview.py::TestGetOverview::test_get_overview": "获取内容概览",
+ "test_link_relations.py::TestLinkRelations::test_link_relations_unlink": "管理内容关联关系",
+ "test_add_message.py::TestAddMessage::test_add_message": "向会话添加消息",
+ "test_create_session.py::TestCreateSession::test_create_session": "创建会话",
+ "test_delete_session.py::TestDeleteSession::test_delete_session": "删除会话",
+ "test_get_session.py::TestGetSession::test_get_session": "获取会话信息",
+ "test_list_sessions.py::TestListSessions::test_list_sessions": "列出所有会话",
+ "test_session_used_commit.py::TestSessionUsedCommit::test_session_used_commit": "会话使用和提交",
+ "test_find.py::TestFind::test_find_basic": "基础查找搜索",
+ "test_find.py::TestFind::test_find_with_different_query": "不同查询的查找搜索",
+ "test_search.py::TestSearch::test_basic_search": "基础语义搜索",
+ "test_search.py::TestSearch::test_search_with_different_query": "不同查询的语义搜索",
+ "test_grep.py::TestGrep::test_grep_basic": "基础文本搜索",
+ "test_glob.py::TestGlob::test_glob_basic": "基础模式匹配",
+ "test_is_healthy.py::TestIsHealthy::test_is_healthy": "检查系统健康状态",
+ "test_observer.py::TestObserver::test_observer_queue": "观察任务队列状态",
+ "test_observer.py::TestObserver::test_observer_vikingdb": "观察向量数据库状态",
+ "test_observer.py::TestObserver::test_observer_system": "观察系统整体状态",
+ "test_system_status.py::TestSystemStatus::test_system_status": "获取系统状态",
+ "test_system_wait.py::TestSystemWait::test_system_wait": "等待系统处理完成",
+ "test_admin_accounts.py::TestAdminAccounts::test_admin_list_accounts": "列出所有账户",
+ "test_admin_accounts.py::TestAdminAccounts::test_admin_create_delete_account": "创建和删除账户",
+ "test_admin_regenerate_key.py::TestAdminRegenerateKey::test_admin_regenerate_key": "重新生成API密钥",
+ "test_admin_role.py::TestAdminRole::test_admin_set_role": "设置用户角色",
+ "test_admin_users.py::TestAdminUsers::test_admin_list_users": "列出账户下的用户",
+ "test_admin_users.py::TestAdminUsers::test_admin_register_remove_user": "注册和删除用户",
+ "test_server_health_check.py::TestServerHealthCheck::test_server_health_check": "服务器健康检查",
+ "test_tc_r01_semantic_retrieval.py::TestTCR01SemanticRetrieval::test_semantic_retrieval_end_to_end": "TC-R01 语义检索全链路验证",
+ "test_tc_r02_resource_swap.py::TestTCR02ResourceSwap::test_resource_incremental_update": "TC-R02 资源增量更新",
+ "test_tc_r03_grep_validation.py::TestTCR03GrepValidation::test_grep_pattern_match": "TC-R03 正则检索验证",
+ "test_tc_r04_delete_sync.py::TestTCR04DeleteSync::test_resource_deletion_index_sync": "TC-R04 资源删除索引同步",
+ "test_tc_r05_pack_consistency.py::TestTCR05PackConsistency::test_pack_export_import_consistency": "TC-R05 批量导入导出一致性",
+ "test_tc_r06_intent_extended_search.py::TestTCR06IntentExtendedSearch::test_intent_extended_search": "TC-R06 意图扩展搜索",
+ "test_tc_r07_relation_link.py::TestTCR07RelationLink::test_relation_link": "TC-R07 关系链接验证",
+ "test_tc_r08_watch_update.py::TestTCR08WatchUpdate::test_watch_update": "TC-R08 定时监听更新",
+ "test_tc_s01_session_commit.py::TestTCS01SessionCommit::test_session_persistence_and_commit": "TC-S01 对话持久化与Commit",
+ "test_tc_s02_reference_count.py::TestTCS02ReferenceCount::test_reference_count_used": "TC-S02 引用计数Used()",
+ "test_tc_s03_multimodal_parts.py::TestTCS03MultimodalParts::test_multimodal_parts_write": "TC-S03 多模态Parts写入",
+ "test_tc_s04_long_context_recall.py::TestTCS04LongContextRecall::test_long_context_recall": "TC-S04 长程上下文召回",
+ "test_tc_s05_session_delete_cleanup.py::TestTCS05SessionDeleteCleanup::test_session_delete_cleanup": "TC-S05 会话删除与清理",
+ "test_tc_f01_read_write_consistency.py::TestTCF01ReadWriteConsistency::test_read_write_consistency": "TC-F01 写读一致性",
+ "test_tc_f02_recursive_traversal.py::TestTCF02RecursiveTraversal::test_recursive_traversal": "TC-F02 目录层级遍历",
+ "test_tc_f03_tree_rendering.py::TestTCF03TreeRendering::test_tree_rendering": "TC-F03 复杂Tree渲染",
+ "test_tc_f04_content_abstract.py::TestTCF04ContentAbstract::test_content_abstract": "TC-F04 目录/文件摘要",
+ "test_tc_f05_vfs_stat.py::TestTCF05VFSStat::test_vfs_stat": "TC-F05 VFS空间状态检查",
+ "test_tc_sy01_system_health.py::TestTCSY01SystemHealth::test_system_health_check": "TC-SY01 系统健康检查",
+ "test_tc_sy02_system_stats.py::TestTCSY02SystemStats::test_system_stats_baseline": "TC-SY02 系统指标基线监控",
+ "test_tc_ad01_token_isolation.py::TestTCAD01TokenIsolation::test_token_isolation": "TC-AD01 Token权限隔离",
+ "test_tc_ad02_backup_restore.py::TestTCAD02BackupRestore::test_backup_restore": "TC-AD02 系统冷备份与校验",
+ "test_tc_er01_invalid_uri.py::TestTCER01InvalidURI::test_invalid_uri_exception": "TC-ER01 无效URI异常拦截",
+ "test_tc_er02_concurrent_write.py::TestTCER02ConcurrentWrite::test_concurrent_write_conflict": "TC-ER02 并发写入冲突验证",
+}
+
+
+TEST_CASE_APIS = {
+ "test_add_resource.py::TestAddResource::test_add_resource_simple": "/api/v1/resources",
+ "test_pack.py::TestPack::test_export_ovpack": "/api/v1/resources/pack",
+ "test_wait_processed.py::TestWaitProcessed::test_wait_processed": "/api/v1/resources/wait",
+ "test_fs_ls.py::TestFsLs::test_fs_ls_root": "/api/v1/fs/ls",
+ "test_fs_mkdir.py::TestFsMkdir::test_fs_mkdir": "/api/v1/fs/mkdir",
+ "test_fs_mv.py::TestFsMv::test_fs_mv": "/api/v1/fs/mv",
+ "test_fs_read_write.py::TestFsReadWrite::test_fs_read": "/api/v1/fs/read",
+ "test_fs_rm.py::TestFsRm::test_fs_rm": "/api/v1/fs/rm",
+ "test_fs_stat.py::TestFsStat::test_fs_stat": "/api/v1/fs/stat",
+ "test_fs_tree.py::TestFsTree::test_fs_tree": "/api/v1/fs/tree",
+ "test_get_abstract.py::TestGetAbstract::test_get_abstract": "/api/v1/fs/abstract",
+ "test_get_overview.py::TestGetOverview::test_get_overview": "/api/v1/fs/overview",
+ "test_link_relations.py::TestLinkRelations::test_link_relations_unlink": "/api/v1/fs/relations",
+ "test_add_message.py::TestAddMessage::test_add_message": "/api/v1/sessions/messages",
+ "test_create_session.py::TestCreateSession::test_create_session": "/api/v1/sessions",
+ "test_delete_session.py::TestDeleteSession::test_delete_session": "/api/v1/sessions",
+ "test_get_session.py::TestGetSession::test_get_session": "/api/v1/sessions",
+ "test_list_sessions.py::TestListSessions::test_list_sessions": "/api/v1/sessions",
+ "test_session_used_commit.py::TestSessionUsedCommit::test_session_used_commit": "/api/v1/sessions/commit",
+ "test_find.py::TestFind::test_find_basic": "/api/v1/search/find",
+ "test_find.py::TestFind::test_find_with_different_query": "/api/v1/search/find",
+ "test_search.py::TestSearch::test_basic_search": "/api/v1/search",
+ "test_search.py::TestSearch::test_search_with_different_query": "/api/v1/search",
+ "test_grep.py::TestGrep::test_grep_basic": "/api/v1/search/grep",
+ "test_glob.py::TestGlob::test_glob_basic": "/api/v1/search/glob",
+ "test_is_healthy.py::TestIsHealthy::test_is_healthy": "/api/v1/system/healthy",
+ "test_observer.py::TestObserver::test_observer_queue": "/api/v1/system/observer",
+ "test_observer.py::TestObserver::test_observer_vikingdb": "/api/v1/system/observer",
+ "test_observer.py::TestObserver::test_observer_system": "/api/v1/system/observer",
+ "test_system_status.py::TestSystemStatus::test_system_status": "/api/v1/system/status",
+ "test_system_wait.py::TestSystemWait::test_system_wait": "/api/v1/system/wait",
+ "test_admin_accounts.py::TestAdminAccounts::test_admin_list_accounts": "/api/v1/admin/accounts",
+ "test_admin_accounts.py::TestAdminAccounts::test_admin_create_delete_account": "/api/v1/admin/accounts",
+ "test_admin_regenerate_key.py::TestAdminRegenerateKey::test_admin_regenerate_key": "/api/v1/admin/keys",
+ "test_admin_role.py::TestAdminRole::test_admin_set_role": "/api/v1/admin/roles",
+ "test_admin_users.py::TestAdminUsers::test_admin_list_users": "/api/v1/admin/users",
+ "test_admin_users.py::TestAdminUsers::test_admin_register_remove_user": "/api/v1/admin/users",
+ "test_server_health_check.py::TestServerHealthCheck::test_server_health_check": "/health",
+ "test_tc_r01_semantic_retrieval.py::TestTCR01SemanticRetrieval::test_semantic_retrieval_end_to_end": "/api/v1/resources,/api/v1/search/find",
+ "test_tc_r02_resource_swap.py::TestTCR02ResourceSwap::test_resource_incremental_update": "/api/v1/resources,/api/v1/search/find",
+ "test_tc_r03_grep_validation.py::TestTCR03GrepValidation::test_grep_pattern_match": "/api/v1/resources,/api/v1/search/grep",
+ "test_tc_r04_delete_sync.py::TestTCR04DeleteSync::test_resource_deletion_index_sync": "/api/v1/resources,/api/v1/fs/rm,/api/v1/search/find",
+ "test_tc_r05_pack_consistency.py::TestTCR05PackConsistency::test_pack_export_import_consistency": "/api/v1/resources/pack/export,/api/v1/resources/pack/import",
+ "test_tc_r06_intent_extended_search.py::TestTCR06IntentExtendedSearch::test_intent_extended_search": "/api/v1/sessions,/api/v1/search",
+ "test_tc_r07_relation_link.py::TestTCR07RelationLink::test_relation_link": "/api/v1/fs/relations/link,/api/v1/search/find",
+ "test_tc_r08_watch_update.py::TestTCR08WatchUpdate::test_watch_update": "/api/v1/resources",
+ "test_tc_s01_session_commit.py::TestTCS01SessionCommit::test_session_persistence_and_commit": "/api/v1/sessions,/api/v1/sessions/messages,/api/v1/sessions/commit",
+ "test_tc_s02_reference_count.py::TestTCS02ReferenceCount::test_reference_count_used": "/api/v1/sessions/used,/api/v1/system/status",
+ "test_tc_s03_multimodal_parts.py::TestTCS03MultimodalParts::test_multimodal_parts_write": "/api/v1/sessions/messages,/api/v1/sessions",
+ "test_tc_s04_long_context_recall.py::TestTCS04LongContextRecall::test_long_context_recall": "/api/v1/sessions/messages,/api/v1/sessions/commit,/api/v1/search",
+ "test_tc_s05_session_delete_cleanup.py::TestTCS05SessionDeleteCleanup::test_session_delete_cleanup": "/api/v1/sessions",
+ "test_tc_f01_read_write_consistency.py::TestTCF01ReadWriteConsistency::test_read_write_consistency": "/api/v1/fs/write,/api/v1/fs/read",
+ "test_tc_f02_recursive_traversal.py::TestTCF02RecursiveTraversal::test_recursive_traversal": "/api/v1/fs/ls",
+ "test_tc_f03_tree_rendering.py::TestTCF03TreeRendering::test_tree_rendering": "/api/v1/fs/tree",
+ "test_tc_f04_content_abstract.py::TestTCF04ContentAbstract::test_content_abstract": "/api/v1/fs/abstract",
+ "test_tc_f05_vfs_stat.py::TestTCF05VFSStat::test_vfs_stat": "/api/v1/fs/stat",
+ "test_tc_sy01_system_health.py::TestTCSY01SystemHealth::test_system_health_check": "/api/v1/system/healthy",
+ "test_tc_sy02_system_stats.py::TestTCSY02SystemStats::test_system_stats_baseline": "/api/v1/system/status",
+ "test_tc_ad01_token_isolation.py::TestTCAD01TokenIsolation::test_token_isolation": "/api/v1/admin/token/generate,/api/v1/search/find",
+ "test_tc_ad02_backup_restore.py::TestTCAD02BackupRestore::test_backup_restore": "/api/v1/admin/backup",
+ "test_tc_er01_invalid_uri.py::TestTCER01InvalidURI::test_invalid_uri_exception": "/api/v1/fs/read",
+ "test_tc_er02_concurrent_write.py::TestTCER02ConcurrentWrite::test_concurrent_write_conflict": "/api/v1/resources",
+}
+
+
+CATEGORY_NAMES = {
+ "admin": "管理API",
+ "filesystem": "文件系统API",
+ "health_check": "健康检查",
+ "resources": "资源管理API",
+ "retrieval": "检索API",
+ "sessions": "会话管理API",
+ "system": "系统管理API",
+ "resources_retrieval": "P1 知识中枢场景",
+ "scenarios": "场景级测试",
+ "stability_error": "P3 运维与异常边界",
+}
+
+
+def get_test_description(nodeid):
+ for key, desc in TEST_CASE_DESCRIPTIONS.items():
+ if key in nodeid:
+ return desc
+ return nodeid.split("::")[-1]
+
+
+def get_test_api(nodeid):
+ for key, api in TEST_CASE_APIS.items():
+ if key in nodeid:
+ return api
+ return ""
+
+
+def format_memory(bytes_value):
+ if bytes_value is None:
+ return ""
+
+ if bytes_value < 1024:
+ value = bytes_value
+ unit = "B"
+ elif bytes_value < 1024 * 1024:
+ value = bytes_value / 1024
+ unit = "KB"
+ elif bytes_value < 1024 * 1024 * 1024:
+ value = bytes_value / (1024 * 1024)
+ unit = "MB"
+ else:
+ value = bytes_value / (1024 * 1024 * 1024)
+ unit = "GB"
+
+ return f"{value:.1f} {unit}"
+
+
+def format_memory_delta(delta_bytes):
+ if delta_bytes is None:
+ return ""
+
+ abs_bytes = abs(delta_bytes)
+ if abs_bytes < 1024:
+ value = abs_bytes
+ unit = "B"
+ elif abs_bytes < 1024 * 1024:
+ value = abs_bytes / 1024
+ unit = "KB"
+ elif abs_bytes < 1024 * 1024 * 1024:
+ value = abs_bytes / (1024 * 1024)
+ unit = "MB"
+ else:
+ value = abs_bytes / (1024 * 1024 * 1024)
+ unit = "GB"
+
+ sign = "+" if delta_bytes > 0 else "" if delta_bytes == 0 else "-"
+ return f"{sign}{value:.1f} {unit}"
+
+
+def get_test_category(nodeid):
+ parts = nodeid.split(os.sep)
+ for part in parts:
+ if part in CATEGORY_NAMES:
+ return CATEGORY_NAMES[part]
+ return "其他"
+
+
[email protected](scope="session")
+def api_client():
+ client = OpenVikingAPIClient(server_url=Config.SERVER_URL, api_key=Config.OPENVIKING_API_KEY)
+ return client
+
+
+def pytest_collection_modifyitems(config, items):
+ cache = config.cache
+ lastfailed = cache.get("cache/lastfailed", {})
+
+ def item_sort_key(item):
+ is_failed = item.nodeid in lastfailed
+ category = get_test_category(item.nodeid)
+ return (0 if is_failed else 1, category, item.name)
+
+ items.sort(key=item_sort_key)
+
+
+def pytest_runtest_setup(item):
+ process = psutil.Process()
+ mem_info = process.memory_info()
+ item._start_memory = mem_info.rss
+
+
[email protected](tryfirst=True, hookwrapper=True)
+def pytest_runtest_makereport(item, call):
+ outcome = yield
+ report = outcome.get_result()
+
+ if report.when == "call":
+ category = get_test_category(item.nodeid)
+ description = get_test_description(item.nodeid)
+ report.category = category
+ report.description = description
+ report.nodeid = item.nodeid
+ report.is_failed = report.failed
+
+ if hasattr(item, "_start_memory"):
+ process = psutil.Process()
+ mem_info = process.memory_info()
+ delta = mem_info.rss - item._start_memory
+ report.memory_current = mem_info.rss
+ report.memory_delta = delta
+
+ if report.failed:
+ for _fixture_name, fixture_value in item.funcargs.items():
+ if hasattr(fixture_value, "to_curl"):
+ curl = fixture_value.to_curl()
+ if curl:
+ report.sections.append(("cURL Command", curl))
+
+
+def pytest_report_teststatus(report, config):
+ if report.when == "call":
+ category = getattr(report, "category", "其他")
+ description = getattr(report, "description", "")
+
+ return (report.outcome, f"{category} - {description}", "")
+
+
+def pytest_html_results_table_header(cells):
+ cells.insert(2, "<th>分类</th>")
+ cells.insert(3, "<th>描述</th>")
+ cells.insert(4, "<th>API</th>")
+ cells.insert(6, "<th>内存用量</th>")
+
+ result = cells[0]
+ test = cells[1]
+ category = cells[2]
+ description = cells[3]
+ api = cells[4]
+ duration = cells[5]
+ memory = cells[6]
+
+ cells.clear()
+ cells.append(result)
+ cells.append(category)
+ cells.append(description)
+ cells.append(api)
+ cells.append(duration)
+ cells.append(memory)
+ cells.append(test)
+
+
+def pytest_html_results_table_row(report, cells):
+ if hasattr(report, "nodeid"):
+ category = get_test_category(report.nodeid)
+ description = get_test_description(report.nodeid)
+ api = get_test_api(report.nodeid)
+ memory_current = getattr(report, "memory_current", None)
+ memory_delta = getattr(report, "memory_delta", None)
+
+ memory_current_str = format_memory(memory_current)
+ memory_delta_str = format_memory_delta(memory_delta)
+
+ if memory_current_str and memory_delta_str:
+ memory_str = f"{memory_current_str} ({memory_delta_str})"
+ elif memory_current_str:
+ memory_str = memory_current_str
+ else:
+ memory_str = ""
+
+ cells.insert(2, f"<td>{category}</td>")
+ cells.insert(3, f"<td>{description}</td>")
+ cells.insert(4, f"<td>{api}</td>")
+ cells.insert(6, f"<td>{memory_str}</td>")
+
+ result = cells[0]
+ test = cells[1]
+ category = cells[2]
+ description = cells[3]
+ api = cells[4]
+ duration = cells[5]
+ memory = cells[6]
+
+ cells.clear()
+ cells.append(result)
+ cells.append(category)
+ cells.append(description)
+ cells.append(api)
+ cells.append(duration)
+ cells.append(memory)
+ cells.append(test)
+
+
+def pytest_html_report_title(report):
+ report.title = "OpenViking API测试报告"
+
+
+def pytest_html_results_summary(prefix, summary, postfix):
+ prefix.extend(
+ [
+ """
+ <p><strong>OpenViking Version:</strong> 0.2.9</p>
+ """
+ ]
+ )
+ prefix.extend(
+ [
+ """
+ <style>
+ /* 隐藏时长描述 */
+ .run-count {
+ display: none !important;
+ }
+
+ /* 设置列宽度 */
+ #results-table th:nth-child(1),
+ #results-table td:nth-child(1) {
+ width: 60px !important;
+ }
+
+ #results-table th:nth-child(2),
+ #results-table td:nth-child(2) {
+ width: 120px !important;
+ }
+
+ #results-table th:nth-child(3),
+ #results-table td:nth-child(3) {
+ width: 250px !important;
+ }
+
+ #results-table th:nth-child(4),
+ #results-table td:nth-child(4) {
+ width: 200px !important;
+ font-family: monospace !important;
+ font-size: 12px !important;
+ }
+
+ #results-table th:nth-child(5),
+ #results-table td:nth-child(5) {
+ width: 80px !important;
+ }
+
+ #results-table th:nth-child(6),
+ #results-table td:nth-child(6) {
+ width: 100px !important;
+ text-align: right !important;
+ }
+
+ #results-table th:nth-child(7),
+ #results-table td:nth-child(7) {
+ width: 180px !important;
+ max-width: 180px !important;
+ overflow: hidden !important;
+ text-overflow: ellipsis !important;
+ white-space: nowrap !important;
+ }
+ </style>
+ <script>
+ function sortFailedFirst() {
+ var table = document.getElementById('results-table');
+ if (table) {
+ var tbodies = table.querySelectorAll('tbody');
+ tbodies.forEach(function(tbody) {
+ var rows = Array.from(tbody.querySelectorAll('tr.collapsible'));
+ if (rows.length > 0) {
+ var sortedRows = rows.sort(function(a, b) {
+ var aFailed = a.querySelector('.failed, .error') !== null ||
+ (a.querySelector('.col-result') &&
+ (a.querySelector('.col-result').textContent.includes('Failed') ||
+ a.querySelector('.col-result').textContent.includes('Error')));
+ var bFailed = b.querySelector('.failed, .error') !== null ||
+ (b.querySelector('.col-result') &&
+ (b.querySelector('.col-result').textContent.includes('Failed') ||
+ b.querySelector('.col-result').textContent.includes('Error')));
+ if (aFailed && !bFailed) return -1;
+ if (!aFailed && bFailed) return 1;
+ return 0;
+ });
+ sortedRows.forEach(function(row) {
+ tbody.insertBefore(row, tbody.firstChild);
+ if (row.nextElementSibling && row.nextElementSibling.classList.contains('extras-row')) {
+ tbody.insertBefore(row.nextElementSibling, tbody.firstChild.nextSibling);
+ }
+ });
+ }
+ });
+ }
+ }
+
+ document.addEventListener('DOMContentLoaded', function() {
+ setTimeout(sortFailedFirst, 100);
+ setTimeout(sortFailedFirst, 500);
+ setTimeout(sortFailedFirst, 1000);
+ });
+ </script>
+ """
+ ]
+ )
diff --git a/tests/api_test/filesystem/test_fs_ls.py b/tests/api_test/filesystem/test_fs_ls.py
new file mode 100644
index 000000000..bcb7c2ef6
--- /dev/null
+++ b/tests/api_test/filesystem/test_fs_ls.py
@@ -0,0 +1,28 @@
+import json
+
+import pytest
+import requests
+
+
+class TestFsLs:
+ def test_fs_ls_root(self, api_client):
+ try:
+ response = api_client.fs_ls("viking://")
+ except requests.exceptions.ConnectionError:
+ pytest.fail("Could not connect to server service - service is not running")
+
+ assert response.status_code < 500, f"FS ls failed with status {response.status_code}"
+
+ if response.status_code == 200:
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("FS ls (root) API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert isinstance(data["result"], list), "'result' should be a list"
+ assert len(data["result"]) > 0, "'result' list should not be empty"
diff --git a/tests/api_test/filesystem/test_fs_mkdir.py b/tests/api_test/filesystem/test_fs_mkdir.py
new file mode 100644
index 000000000..1a373df12
--- /dev/null
+++ b/tests/api_test/filesystem/test_fs_mkdir.py
@@ -0,0 +1,34 @@
+import json
+import uuid
+
+import pytest
+import requests
+
+
+class TestFsMkdir:
+ def test_fs_mkdir(self, api_client):
+ random_id = str(uuid.uuid4())[:8]
+ test_dir_path = f"viking://user/test-dir-{random_id}/"
+
+ try:
+ response = api_client.fs_mkdir(test_dir_path)
+ print(f"\nFS mkdir API status code: {response.status_code}")
+
+ if response.status_code == 200:
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("FS mkdir API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, (
+ f"Expected error to be null, got {data.get('error')}"
+ )
+ assert "result" in data, "'result' field should exist"
+
+ response = api_client.fs_rm(test_dir_path, recursive=True)
+
+ except requests.exceptions.ConnectionError:
+ pytest.fail("Could not connect to server service - service is not running")
diff --git a/tests/api_test/filesystem/test_fs_mv.py b/tests/api_test/filesystem/test_fs_mv.py
new file mode 100644
index 000000000..9b5f68a3a
--- /dev/null
+++ b/tests/api_test/filesystem/test_fs_mv.py
@@ -0,0 +1,33 @@
+import json
+import uuid
+
+
+class TestFsMv:
+ def test_fs_mv(self, api_client):
+ random_id = str(uuid.uuid4())[:8]
+ src_dir = f"/tmp/test-mv-src-{random_id}"
+ dst_dir = f"/tmp/test-mv-dst-{random_id}"
+
+ try:
+ response = api_client.fs_mkdir(src_dir)
+ print(f"\nCreate source directory API status code: {response.status_code}")
+ assert response.status_code == 200, (
+ f"Failed to create source directory: {response.status_code}"
+ )
+
+ response = api_client.fs_mv(src_dir, dst_dir)
+ print(f"\nFS mv API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("FS Mv API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/filesystem/test_fs_read_write.py b/tests/api_test/filesystem/test_fs_read_write.py
new file mode 100644
index 000000000..53cca7c23
--- /dev/null
+++ b/tests/api_test/filesystem/test_fs_read_write.py
@@ -0,0 +1,39 @@
+import json
+
+
+class TestFsReadWrite:
+ def test_fs_read(self, api_client):
+ try:
+ response = api_client.fs_ls("viking://")
+ print(f"\nList root directory API status code: {response.status_code}")
+ assert response.status_code == 200, (
+ f"Failed to list root directory: {response.status_code}"
+ )
+
+ data = response.json()
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ result = data.get("result", [])
+ assert len(result) > 0, "No files found in root"
+
+ test_file_path = result[0].get("uri")
+ assert test_file_path is not None, "No suitable file found"
+
+ response = api_client.fs_read(test_file_path)
+ print(f"\nFS read API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("FS read API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/filesystem/test_fs_rm.py b/tests/api_test/filesystem/test_fs_rm.py
new file mode 100644
index 000000000..327aede75
--- /dev/null
+++ b/tests/api_test/filesystem/test_fs_rm.py
@@ -0,0 +1,32 @@
+import json
+import uuid
+
+
+class TestFsRm:
+ def test_fs_rm(self, api_client):
+ random_id = str(uuid.uuid4())[:8]
+ test_dir = f"/tmp/test-rm-{random_id}"
+
+ try:
+ response = api_client.fs_mkdir(test_dir)
+ print(f"\nCreate test directory API status code: {response.status_code}")
+ assert response.status_code == 200, (
+ f"Failed to create test directory: {response.status_code}"
+ )
+
+ response = api_client.fs_rm(test_dir, recursive=True)
+ print(f"\nFS rm API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("FS Rm API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/filesystem/test_fs_stat.py b/tests/api_test/filesystem/test_fs_stat.py
new file mode 100644
index 000000000..c7a99ea5f
--- /dev/null
+++ b/tests/api_test/filesystem/test_fs_stat.py
@@ -0,0 +1,27 @@
+import json
+
+import pytest
+import requests
+
+
+class TestFsStat:
+ def test_fs_stat(self, api_client):
+ try:
+ response = api_client.fs_stat("viking://")
+ except requests.exceptions.ConnectionError:
+ pytest.fail("Could not connect to server service - service is not running")
+
+ assert response.status_code < 500, f"FS stat failed with status {response.status_code}"
+
+ if response.status_code == 200:
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("FS stat (root) API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert data["result"] is not None, "'result' should not be null"
diff --git a/tests/api_test/filesystem/test_fs_tree.py b/tests/api_test/filesystem/test_fs_tree.py
new file mode 100644
index 000000000..b1f06962e
--- /dev/null
+++ b/tests/api_test/filesystem/test_fs_tree.py
@@ -0,0 +1,27 @@
+import json
+
+import pytest
+import requests
+
+
+class TestFsTree:
+ def test_fs_tree(self, api_client):
+ try:
+ response = api_client.fs_tree("viking://")
+ except requests.exceptions.ConnectionError:
+ pytest.fail("Could not connect to server service - service is not running")
+
+ assert response.status_code < 500, f"FS tree failed with status {response.status_code}"
+
+ if response.status_code == 200:
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("FS tree (root) API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert data["result"] is not None, "'result' should not be null"
diff --git a/tests/api_test/filesystem/test_get_abstract.py b/tests/api_test/filesystem/test_get_abstract.py
new file mode 100644
index 000000000..50d1e8825
--- /dev/null
+++ b/tests/api_test/filesystem/test_get_abstract.py
@@ -0,0 +1,39 @@
+import json
+
+
+class TestGetAbstract:
+ def test_get_abstract(self, api_client):
+ try:
+ response = api_client.fs_ls("viking://")
+ print(f"\nList root directory API status code: {response.status_code}")
+ assert response.status_code == 200, (
+ f"Failed to list root directory: {response.status_code}"
+ )
+
+ data = response.json()
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ result = data.get("result", [])
+ assert len(result) > 0, "No files found in root"
+
+ test_file_path = result[0].get("uri")
+ assert test_file_path is not None, "No suitable file found"
+
+ response = api_client.get_abstract(test_file_path)
+ print(f"\nGet abstract API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Get Abstract API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/filesystem/test_get_overview.py b/tests/api_test/filesystem/test_get_overview.py
new file mode 100644
index 000000000..b3d87c870
--- /dev/null
+++ b/tests/api_test/filesystem/test_get_overview.py
@@ -0,0 +1,27 @@
+import json
+
+import pytest
+import requests
+
+
+class TestGetOverview:
+ def test_get_overview(self, api_client):
+ try:
+ response = api_client.get_overview("viking://")
+ except requests.exceptions.ConnectionError:
+ pytest.fail("Could not connect to server service - service is not running")
+
+ assert response.status_code < 500, f"Get overview failed with status {response.status_code}"
+
+ if response.status_code == 200:
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Get Overview API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert data["result"] is not None, "'result' should not be null"
diff --git a/tests/api_test/filesystem/test_link_relations.py b/tests/api_test/filesystem/test_link_relations.py
new file mode 100644
index 000000000..b7e3bd92a
--- /dev/null
+++ b/tests/api_test/filesystem/test_link_relations.py
@@ -0,0 +1,63 @@
+import json
+
+
+class TestLinkRelations:
+ def test_link_relations_unlink(self, api_client):
+ try:
+ response = api_client.fs_ls("viking://")
+ print(f"\nList root directory API status code: {response.status_code}")
+ assert response.status_code == 200, (
+ f"Failed to list root directory: {response.status_code}"
+ )
+
+ data = response.json()
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ result = data.get("result", [])
+ assert len(result) >= 2, (
+ f"Not enough files in root directory to test link/relations/unlink, found {len(result)} files"
+ )
+
+ file1 = result[0].get("uri")
+ file2 = result[1].get("uri")
+
+ assert file1 is not None, "First file URI should not be None"
+ assert file2 is not None, "Second file URI should not be None"
+
+ response = api_client.link(file1, [file2], "Test link")
+ print(f"\nLink API status code: {response.status_code}")
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Link API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ response = api_client.relations(file1)
+ print(f"\nRelations API status code: {response.status_code}")
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Relations API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ response = api_client.unlink(file1, file2)
+ print(f"\nUnlink API status code: {response.status_code}")
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Unlink API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/health_check/test_server_health_check.py b/tests/api_test/health_check/test_server_health_check.py
new file mode 100644
index 000000000..04daa2e68
--- /dev/null
+++ b/tests/api_test/health_check/test_server_health_check.py
@@ -0,0 +1,32 @@
+import json
+
+import pytest
+import requests
+
+
+class TestServerHealthCheck:
+ def test_server_health_check(self, api_client):
+ try:
+ response = api_client.server_health_check()
+ print("\n" + "=" * 80)
+ print("Health Check API Response:")
+ print("=" * 80)
+ print(json.dumps(response.json(), indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert response.status_code < 500, (
+ f"Server health check failed with status {response.status_code}"
+ )
+
+ if response.status_code == 200:
+ data = response.json()
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, (
+ f"Expected error to be null, got {data.get('error')}"
+ )
+ assert data.get("healthy") is not None, "'healthy' field should not be null"
+ assert "version" in data, "'version' field should exist"
+ assert "user_id" in data, "'user_id' field should exist"
+
+ except requests.exceptions.ConnectionError:
+ pytest.fail("Could not connect to server service - service is not running")
diff --git a/tests/api_test/local-test.sh b/tests/api_test/local-test.sh
new file mode 100755
index 000000000..1461c8234
--- /dev/null
+++ b/tests/api_test/local-test.sh
@@ -0,0 +1,147 @@
+#!/bin/bash
+# OpenViking API 测试 - 本地测试脚本
+# 模拟 GitHub Actions 流水线的执行流程
+
+set -e
+
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+NC='\033[0m' # No Color
+
+echo -e "${GREEN}========================================${NC}"
+echo -e "${GREEN} OpenViking API 测试 - 本地执行${NC}"
+echo -e "${GREEN}========================================${NC}"
+echo ""
+
+# 1. 检查 Python 版本
+echo -e "${YELLOW}[1/7] 检查 Python 版本...${NC}"
+PYTHON_VERSION=$(python3 --version | awk '{print $2}')
+echo "Python 版本: $PYTHON_VERSION"
+python3 -c "import sys; assert sys.version_info >= (3, 10), 'Python 3.10+ required'"
+echo -e "${GREEN}✓ Python 版本检查通过${NC}"
+echo ""
+
+# 2. 安装 OpenViking
+echo -e "${YELLOW}[2/7] 安装 OpenViking...${NC}"
+cd "$(dirname "$0")/../.."
+pip install -e .
+echo -e "${GREEN}✓ OpenViking 安装成功${NC}"
+echo ""
+
+# 3. 安装测试依赖
+echo -e "${YELLOW}[3/7] 安装测试依赖...${NC}"
+cd tests/api_test
+pip install -r requirements.txt
+echo -e "${GREEN}✓ 测试依赖安装成功${NC}"
+echo ""
+
+# 4. 创建 OpenViking 配置文件
+echo -e "${YELLOW}[4/8] 创建 OpenViking 配置文件...${NC}"
+mkdir -p ~/.openviking
+cat > ~/.openviking/ov.conf << EOF
+{
+ "server": {
+ "root_api_key": "test-root-api-key"
+ },
+ "vlm": {
+ "provider": "volcengine",
+ "api_key": "dummy-vlm-api-key",
+ "model": "doubao-seed-2-0-mini-260215",
+ "api_base": "https://ark.cn-beijing.volces.com/api/v3",
+ "temperature": 0.1,
+ "max_retries": 3
+ },
+ "embedding": {
+ "dense": {
+ "provider": "volcengine",
+ "api_key": "dummy-embedding-api-key",
+ "model": "doubao-embedding-vision-251215",
+ "api_base": "https://ark.cn-beijing.volces.com/api/v3",
+ "dimension": 1024,
+ "input": "multimodal"
+ }
+ }
+}
+EOF
+echo -e "${GREEN}✓ 配置文件创建成功${NC}"
+echo ""
+
+# 5. 找到可用端口
+echo -e "${YELLOW}[5/8] 查找可用端口...${NC}"
+find_available_port() {
+ local port=1933
+ while true; do
+ if ! lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
+ echo $port
+ return
+ fi
+ port=$((port + 1))
+ done
+}
+SERVER_PORT=$(find_available_port)
+echo "使用端口: $SERVER_PORT"
+echo -e "${GREEN}✓ 找到可用端口${NC}"
+echo ""
+
+# 6. 启动 OpenViking Server
+echo -e "${YELLOW}[6/8] 启动 OpenViking Server...${NC}"
+export ROOT_API_KEY=test-root-api-key
+export SERVER_PORT=$SERVER_PORT
+nohup python -m openviking.server.bootstrap > openviking-server.log 2>&1 &
+SERVER_PID=$!
+echo $SERVER_PID > openviking-server.pid
+echo "Server PID: $SERVER_PID"
+
+# 等待服务启动
+echo "等待服务启动..."
+for i in {1..30}; do
+ if curl -s http://127.0.0.1:$SERVER_PORT/health | grep -q '"healthy":true'; then
+ echo -e "${GREEN}✓ 服务已就绪!${NC}"
+ break
+ fi
+ echo "等待... ($i/30)"
+ sleep 2
+done
+
+# 检查服务是否启动成功
+if ! curl -s http://127.0.0.1:$SERVER_PORT/health | grep -q '"healthy":true'; then
+ echo -e "${RED}✗ 服务启动失败!${NC}"
+ echo "服务日志:"
+ cat openviking-server.log
+ exit 1
+fi
+echo ""
+
+# 7. 运行 API 测试
+echo -e "${YELLOW}[7/8] 运行 API 测试...${NC}"
+export OPENVIKING_API_KEY=test-root-api-key
+export SERVER_URL=http://127.0.0.1:$SERVER_PORT
+python -m pytest . -v --html=api-test-report.html --self-contained-html --ignore=retrieval/ --ignore=resources/test_pack.py --ignore=resources/test_wait_processed.py
+TEST_RESULT=$?
+echo ""
+
+# 8. 停止服务
+echo -e "${YELLOW}[8/8] 停止 OpenViking Server...${NC}"
+if [ -f openviking-server.pid ]; then
+ kill $SERVER_PID 2>/dev/null || true
+ pkill -f "openviking.server.bootstrap" 2>/dev/null || true
+ rm -f openviking-server.pid
+fi
+echo -e "${GREEN}✓ 服务已停止${NC}"
+echo ""
+
+# 总结
+echo -e "${GREEN}========================================${NC}"
+if [ $TEST_RESULT -eq 0 ]; then
+ echo -e "${GREEN} ✓ 所有测试通过!${NC}"
+else
+ echo -e "${RED} ✗ 部分测试失败${NC}"
+fi
+echo -e "${GREEN}========================================${NC}"
+echo ""
+echo "测试报告: tests/api_test/api-test-report.html"
+echo "服务日志: tests/api_test/openviking-server.log"
+echo ""
+
+exit $TEST_RESULT
diff --git a/tests/api_test/ov.conf.template b/tests/api_test/ov.conf.template
new file mode 100644
index 000000000..775a2d932
--- /dev/null
+++ b/tests/api_test/ov.conf.template
@@ -0,0 +1,28 @@
+{
+ "server": {
+ "host": "0.0.0.0",
+ "port": 1933,
+ "root_api_key": "test-root-api-key"
+ },
+ "log": {
+ "level": "INFO"
+ },
+ "vlm": {
+ "provider": "volcengine",
+ "api_key": "YOUR_VLM_API_KEY",
+ "model": "doubao-seed-2-0-mini-260215",
+ "api_base": "https://ark.cn-beijing.volces.com/api/v3",
+ "temperature": 0.1,
+ "max_retries": 3
+ },
+ "embedding": {
+ "dense": {
+ "provider": "volcengine",
+ "api_key": "YOUR_EMBEDDING_API_KEY",
+ "model": "doubao-embedding-vision-251215",
+ "api_base": "https://ark.cn-beijing.volces.com/api/v3",
+ "dimension": 1024,
+ "input": "multimodal"
+ }
+ }
+}
diff --git a/tests/api_test/pytest.ini b/tests/api_test/pytest.ini
new file mode 100644
index 000000000..577ba2190
--- /dev/null
+++ b/tests/api_test/pytest.ini
@@ -0,0 +1,11 @@
+[pytest]
+testpaths = .
+python_files = test_*.py
+python_classes = Test*
+python_functions = test_*
+asyncio_mode = auto
+log_cli = true
+log_cli_level = INFO
+addopts = -rA --tb=short -v --ff --ignore=tools/tests/
+pythonpath = .
+
diff --git a/tests/api_test/requirements.txt b/tests/api_test/requirements.txt
new file mode 100644
index 000000000..e03da1947
--- /dev/null
+++ b/tests/api_test/requirements.txt
@@ -0,0 +1,6 @@
+pytest>=7.0.0
+pytest-asyncio>=0.21.0
+pytest-html>=4.0.0
+requests>=2.28.0
+psutil>=5.9.0
+aiohttp>=3.8.0
diff --git a/tests/api_test/resources/test_add_resource.py b/tests/api_test/resources/test_add_resource.py
new file mode 100644
index 000000000..e25ce25f8
--- /dev/null
+++ b/tests/api_test/resources/test_add_resource.py
@@ -0,0 +1,74 @@
+import json
+import os
+import tempfile
+
+
+class TestAddResource:
+ def test_add_resource_simple(self, api_client):
+ try:
+ print("\n" + "=" * 80)
+ print("测试步骤 1: 创建临时测试文件")
+ print("=" * 80)
+
+ with tempfile.TemporaryDirectory() as temp_dir:
+ test_file_path = os.path.join(temp_dir, "test_file.txt")
+ test_content = "这是一个测试文件的内容,用于验证 add_resource API。\n"
+ test_content += "包含一些中文内容,测试场景化验证。"
+
+ with open(test_file_path, "w", encoding="utf-8") as f:
+ f.write(test_content)
+
+ print(f"✓ 临时文件创建成功: {test_file_path}")
+ print(f"✓ 文件内容: {test_content}")
+
+ print("\n" + "=" * 80)
+ print("测试步骤 2: 调用 add_resource API 导入本地文件")
+ print("=" * 80)
+
+ response = api_client.add_resource(
+ path=test_file_path, reason="测试 add_resource API 功能", wait=True
+ )
+ print(f"\nAdd resource API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Add Resource API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, (
+ f"Expected error to be null, got {data.get('error')}"
+ )
+ assert "result" in data, "'result' field should exist"
+
+ result = data.get("result", {})
+ assert "root_uri" in result, "Result should contain 'root_uri' field"
+
+ imported_uri = result.get("root_uri")
+ assert imported_uri is not None, "Imported URI should not be None"
+ assert imported_uri.startswith("viking://"), (
+ f"URI should start with 'viking://', got {imported_uri}"
+ )
+
+ print(f"✓ 文件成功导入,URI: {imported_uri}")
+
+ print("\n" + "=" * 80)
+ print("测试步骤 3: 验证导入的文件")
+ print("=" * 80)
+
+ response = api_client.fs_ls(imported_uri)
+ print(f"\nList imported file API status code: {response.status_code}")
+
+ data = response.json()
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+
+ print("✓ 导入的文件验证成功!")
+ print("\n" + "=" * 80)
+ print("所有测试步骤完成 ✓")
+ print("=" * 80)
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/resources/test_pack.py b/tests/api_test/resources/test_pack.py
new file mode 100644
index 000000000..74a6de7dd
--- /dev/null
+++ b/tests/api_test/resources/test_pack.py
@@ -0,0 +1,43 @@
+import json
+import uuid
+
+
+class TestPack:
+ def test_export_ovpack(self, api_client):
+ random_id = str(uuid.uuid4())[:8]
+ test_export_path = f"./exports/export-{random_id}.ovpack"
+
+ try:
+ response = api_client.fs_ls("viking://")
+ print(f"\nList root directory API status code: {response.status_code}")
+ assert response.status_code == 200, (
+ f"Failed to list root directory: {response.status_code}"
+ )
+
+ data = response.json()
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ result = data.get("result", [])
+ assert len(result) > 0, "No files found in root"
+
+ test_uri = result[0].get("uri")
+ assert test_uri is not None, "No suitable file found"
+
+ response = api_client.export_ovpack(uri=test_uri, to=test_export_path)
+ print(f"\nExport ovpack API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Export OVPack API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/resources/test_wait_processed.py b/tests/api_test/resources/test_wait_processed.py
new file mode 100644
index 000000000..bb8cac3ce
--- /dev/null
+++ b/tests/api_test/resources/test_wait_processed.py
@@ -0,0 +1,37 @@
+import json
+import time
+
+import pytest
+import requests
+
+
+class TestWaitProcessed:
+ def test_wait_processed(self, api_client):
+ max_retries = 3
+ retry_delay = 2
+
+ for attempt in range(max_retries):
+ try:
+ response = api_client.wait_processed()
+ break
+ except requests.exceptions.ConnectionError:
+ if attempt < max_retries - 1:
+ print(f"Connection error, retrying in {retry_delay}s...")
+ time.sleep(retry_delay)
+ else:
+ pytest.fail("Could not connect to server service - service is not running")
+
+ assert response.status_code < 500, (
+ f"Wait processed failed with status {response.status_code}"
+ )
+
+ if response.status_code == 200:
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Wait Processed API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
diff --git a/tests/api_test/retrieval/test_find.py b/tests/api_test/retrieval/test_find.py
new file mode 100644
index 000000000..2ae45d10e
--- /dev/null
+++ b/tests/api_test/retrieval/test_find.py
@@ -0,0 +1,55 @@
+import json
+
+
+class TestFind:
+ def test_find_basic(self, api_client):
+ try:
+ response = api_client.find("how to authenticate", limit=10)
+ print(f"\nFind API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Find API Response (basic find):")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert data["result"] is not None, "'result' should not be null"
+
+ result = data["result"]
+ assert "memories" in result, "'memories' field should exist"
+ assert isinstance(result["memories"], list), "'memories' should be a list"
+ assert "resources" in result, "'resources' field should exist"
+ assert isinstance(result["resources"], list), "'resources' should be a list"
+ assert "skills" in result, "'skills' field should exist"
+ assert isinstance(result["skills"], list), "'skills' should be a list"
+ assert "total" in result, "'total' field should exist"
+ assert isinstance(result["total"], int), "'total' should be an integer"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
+
+ def test_find_with_different_query(self, api_client):
+ try:
+ response = api_client.find("what is OpenViking", limit=5)
+ print(f"\nFind API (different query) status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Find API Response (different query):")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert data["result"] is not None, "'result' should not be null"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/retrieval/test_glob.py b/tests/api_test/retrieval/test_glob.py
new file mode 100644
index 000000000..8b8f2495a
--- /dev/null
+++ b/tests/api_test/retrieval/test_glob.py
@@ -0,0 +1,26 @@
+import json
+
+
+class TestGlob:
+ def test_glob_basic(self, api_client):
+ try:
+ response = api_client.glob("**/*", "viking://user/")
+ print(f"\nGlob API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Glob API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert data["result"] is not None, "'result' should not be null"
+ assert "matches" in data["result"], "'matches' field should exist"
+ assert isinstance(data["result"]["matches"], list), "'matches' should be a list"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/retrieval/test_grep.py b/tests/api_test/retrieval/test_grep.py
new file mode 100644
index 000000000..39fbc92c5
--- /dev/null
+++ b/tests/api_test/retrieval/test_grep.py
@@ -0,0 +1,35 @@
+import json
+
+import pytest
+import requests
+
+
+class TestGrep:
+ def test_grep_basic(self, api_client):
+ try:
+ response = api_client.grep("viking://user/", "viking")
+ print(f"\nGrep API status code: {response.status_code}")
+
+ if response.status_code == 200:
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Grep API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, (
+ f"Expected error to be null, got {data.get('error')}"
+ )
+ assert "result" in data, "'result' field should exist"
+ assert data["result"] is not None, "'result' should not be null"
+ assert "matches" in data["result"], "'matches' field should exist"
+ assert isinstance(data["result"]["matches"], list), "'matches' should be a list"
+ else:
+ print(f"Grep returned non-200 status: {response.status_code}")
+ print(f"Response: {response.text}")
+
+ except requests.exceptions.ConnectionError as e:
+ print(f"Connection error: {e}")
+ pytest.fail("Could not connect to server service - service is not running")
diff --git a/tests/api_test/retrieval/test_search.py b/tests/api_test/retrieval/test_search.py
new file mode 100644
index 000000000..8223f2d16
--- /dev/null
+++ b/tests/api_test/retrieval/test_search.py
@@ -0,0 +1,55 @@
+import json
+
+
+class TestSearch:
+ def test_basic_search(self, api_client):
+ try:
+ response = api_client.search("how to authenticate users", limit=10)
+ print(f"\nSearch API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Search API Response (basic search):")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert data["result"] is not None, "'result' should not be null"
+
+ result = data["result"]
+ assert "memories" in result, "'memories' field should exist"
+ assert isinstance(result["memories"], list), "'memories' should be a list"
+ assert "resources" in result, "'resources' field should exist"
+ assert isinstance(result["resources"], list), "'resources' should be a list"
+ assert "skills" in result, "'skills' field should exist"
+ assert isinstance(result["skills"], list), "'skills' should be a list"
+ assert "total" in result, "'total' field should exist"
+ assert isinstance(result["total"], int), "'total' should be an integer"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
+
+ def test_search_with_different_query(self, api_client):
+ try:
+ response = api_client.search("what is OpenViking", limit=5)
+ print(f"\nSearch API (different query) status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Search API Response (different query):")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert data["result"] is not None, "'result' should not be null"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/services/__init__.py b/tests/api_test/services/__init__.py
new file mode 100644
index 000000000..b3440f257
--- /dev/null
+++ b/tests/api_test/services/__init__.py
@@ -0,0 +1,3 @@
+from .service_manager import OpenVikingServiceManager
+
+__all__ = ["OpenVikingServiceManager"]
diff --git a/tests/api_test/services/service_manager.py b/tests/api_test/services/service_manager.py
new file mode 100644
index 000000000..1f2ad9d80
--- /dev/null
+++ b/tests/api_test/services/service_manager.py
@@ -0,0 +1,177 @@
+import subprocess
+import threading
+import time
+from typing import Optional
+
+import psutil
+import requests
+from config import Config
+
+
+class OpenVikingServiceManager:
+ def __init__(self):
+ self.server_process: Optional[subprocess.Popen] = None
+ self.server_output: list = []
+ self._server_was_started_by_us: bool = False
+
+ def _log_output(self, process, output_list, prefix):
+ for line in iter(process.stdout.readline, ""):
+ if line:
+ line = line.rstrip()
+ output_list.append(line)
+ print(f"[{prefix}] {line}")
+ for line in iter(process.stderr.readline, ""):
+ if line:
+ line = line.rstrip()
+ output_list.append(line)
+ print(f"[{prefix} ERROR] {line}")
+
+ def _is_port_in_use(self, port: int, host: str = "127.0.0.1") -> bool:
+ try:
+ import socket
+
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.settimeout(1)
+ result = sock.connect_ex((host, port))
+ sock.close()
+ return result == 0
+ except Exception:
+ return False
+
+ def _wait_for_service(self, url: str, timeout: int) -> bool:
+ start_time = time.time()
+ while time.time() - start_time < timeout:
+ try:
+ response = requests.get(url, timeout=2)
+ if response.status_code < 500:
+ return True
+ except Exception:
+ pass
+ time.sleep(Config.SERVICE_CHECK_INTERVAL)
+ return False
+
+ def start_server(self) -> bool:
+ if self._is_port_in_use(Config.SERVER_PORT):
+ print(f"⚠️ Server port {Config.SERVER_PORT} already in use, verifying service...")
+ if self._wait_for_service(Config.SERVER_URL, 5):
+ print(f"✅ Server is already running on {Config.SERVER_URL}")
+ self._server_was_started_by_us = False
+ return True
+ else:
+ print(f"❌ Port {Config.SERVER_PORT} is in use but service is not responding")
+ return False
+
+ print(f"🚀 Starting OpenViking server on {Config.SERVER_URL}...")
+ cmd = ["python", "-m", "openviking.server.bootstrap"]
+
+ try:
+ self.server_process = subprocess.Popen(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ bufsize=1,
+ universal_newlines=True,
+ )
+
+ threading.Thread(
+ target=self._log_output,
+ args=(self.server_process, self.server_output, "SERVER"),
+ daemon=True,
+ ).start()
+
+ if self._wait_for_service(Config.SERVER_URL, Config.SERVER_STARTUP_TIMEOUT):
+ print(f"✅ Server started successfully on {Config.SERVER_URL}")
+ self._server_was_started_by_us = True
+ return True
+ else:
+ print(f"❌ Failed to start server after {Config.SERVER_STARTUP_TIMEOUT} seconds")
+ self._print_process_output("SERVER", self.server_output)
+ self.stop_server()
+ return False
+ except Exception as e:
+ print(f"❌ Error starting server: {e}")
+ self.stop_server()
+ return False
+
+ def _print_process_output(self, name: str, output: list):
+ if output:
+ print(f"\n{'=' * 60}")
+ print(f"{name} Output:")
+ print("=" * 60)
+ for line in output[-50:]:
+ print(line)
+ print("=" * 60 + "\n")
+
+ def _find_process_by_port(self, port: int) -> Optional[psutil.Process]:
+ try:
+ for proc in psutil.process_iter(["pid", "name"]):
+ try:
+ connections = proc.connections()
+ for conn in connections:
+ if conn.laddr.port == port:
+ return proc
+ except (psutil.AccessDenied, psutil.NoSuchProcess):
+ continue
+ except Exception:
+ pass
+ return None
+
+ def stop_server(self):
+ if self.server_process:
+ print("🛑 Stopping server (started by us)...")
+ self._terminate_process_tree(self.server_process.pid)
+ self.server_process = None
+ elif self._is_port_in_use(Config.SERVER_PORT):
+ print("🛑 Server was not started by us, but port is in use - trying to stop...")
+ proc = self._find_process_by_port(Config.SERVER_PORT)
+ if proc:
+ print(
+ f" Found process {proc.pid} ({proc.name()}) using port {Config.SERVER_PORT}"
+ )
+ self._terminate_process_tree(proc.pid)
+ self._server_was_started_by_us = False
+
+ def _terminate_process_tree(self, pid: int):
+ try:
+ parent = psutil.Process(pid)
+ children = parent.children(recursive=True)
+ for child in children:
+ child.terminate()
+ parent.terminate()
+ gone, alive = psutil.wait_procs(children + [parent], timeout=5)
+ for p in alive:
+ p.kill()
+ except psutil.NoSuchProcess:
+ pass
+ except Exception as e:
+ print(f"⚠️ Error terminating process {pid}: {e}")
+
+ def start_all(self) -> bool:
+ print("\n" + "=" * 60)
+ print("Starting OpenViking Services")
+ print("=" * 60 + "\n")
+
+ if not self.start_server():
+ print("\n❌ Failed to start all services")
+ return False
+
+ print("\n✅ All services started successfully!")
+ print("=" * 60 + "\n")
+ return True
+
+ def stop_all(self):
+ print("\n" + "=" * 60)
+ print("Stopping OpenViking Services")
+ print("=" * 60 + "\n")
+ self.stop_server()
+ print("\n✅ All services stopped")
+ print("=" * 60 + "\n")
+
+ def __enter__(self):
+ if not self.start_all():
+ raise RuntimeError("Failed to start OpenViking services")
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ self.stop_all()
diff --git a/tests/api_test/sessions/test_add_message.py b/tests/api_test/sessions/test_add_message.py
new file mode 100644
index 000000000..60206301f
--- /dev/null
+++ b/tests/api_test/sessions/test_add_message.py
@@ -0,0 +1,31 @@
+import json
+
+
+class TestAddMessage:
+ def test_add_message(self, api_client):
+ session_id = None
+
+ try:
+ response = api_client.create_session()
+ assert response.status_code == 200, "Create session failed"
+ data = response.json()
+ session_id = data["result"]["session_id"]
+ assert session_id is not None, "session_id should not be null"
+
+ response = api_client.add_message(session_id, "user", "Hello, how can I help?")
+ assert response.status_code == 200, "Add message failed"
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Add Message API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ response = api_client.delete_session(session_id)
+ assert response.status_code == 200, "Delete session failed"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/sessions/test_create_session.py b/tests/api_test/sessions/test_create_session.py
new file mode 100644
index 000000000..2aee03070
--- /dev/null
+++ b/tests/api_test/sessions/test_create_session.py
@@ -0,0 +1,31 @@
+import json
+
+import pytest
+import requests
+
+
+class TestCreateSession:
+ def test_create_session(self, api_client):
+ try:
+ response = api_client.create_session()
+ except requests.exceptions.ConnectionError:
+ pytest.fail("Could not connect to server service - service is not running")
+
+ assert response.status_code < 500, (
+ f"Create session failed with status {response.status_code}"
+ )
+
+ if response.status_code == 200:
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Create Session API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert data["result"] is not None, "'result' should not be null"
+ assert "session_id" in data["result"], "'session_id' field should exist"
+ assert "user" in data["result"], "'user' field should exist"
diff --git a/tests/api_test/sessions/test_delete_session.py b/tests/api_test/sessions/test_delete_session.py
new file mode 100644
index 000000000..76796b868
--- /dev/null
+++ b/tests/api_test/sessions/test_delete_session.py
@@ -0,0 +1,30 @@
+import json
+
+import pytest
+import requests
+
+
+class TestDeleteSession:
+ def test_delete_session(self, api_client):
+ session_id = None
+
+ try:
+ response = api_client.create_session()
+ assert response.status_code == 200, "Create session failed"
+ data = response.json()
+ session_id = data["result"]["session_id"]
+ assert session_id is not None, "session_id should not be null"
+
+ response = api_client.delete_session(session_id)
+ assert response.status_code == 200, "Delete session failed"
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Delete Session API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ except requests.exceptions.ConnectionError:
+ pytest.fail("Could not connect to server service - service is not running")
diff --git a/tests/api_test/sessions/test_get_session.py b/tests/api_test/sessions/test_get_session.py
new file mode 100644
index 000000000..a9c7b6984
--- /dev/null
+++ b/tests/api_test/sessions/test_get_session.py
@@ -0,0 +1,35 @@
+import json
+
+import pytest
+import requests
+
+
+class TestGetSession:
+ def test_get_session(self, api_client):
+ session_id = None
+
+ try:
+ response = api_client.create_session()
+ assert response.status_code == 200, "Create session failed"
+ data = response.json()
+ session_id = data["result"]["session_id"]
+ assert session_id is not None, "session_id should not be null"
+
+ response = api_client.get_session(session_id)
+ assert response.status_code == 200, "Get session failed"
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Get Session API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert data["result"]["session_id"] == session_id, "session_id mismatch"
+
+ response = api_client.delete_session(session_id)
+ assert response.status_code == 200, "Delete session failed"
+
+ except requests.exceptions.ConnectionError:
+ pytest.fail("Could not connect to server service - service is not running")
diff --git a/tests/api_test/sessions/test_list_sessions.py b/tests/api_test/sessions/test_list_sessions.py
new file mode 100644
index 000000000..b9924d612
--- /dev/null
+++ b/tests/api_test/sessions/test_list_sessions.py
@@ -0,0 +1,29 @@
+import json
+
+import pytest
+import requests
+
+
+class TestListSessions:
+ def test_list_sessions(self, api_client):
+ try:
+ response = api_client.list_sessions()
+ except requests.exceptions.ConnectionError:
+ pytest.fail("Could not connect to server service - service is not running")
+
+ assert response.status_code < 500, (
+ f"List sessions failed with status {response.status_code}"
+ )
+
+ if response.status_code == 200:
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("List Sessions API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert isinstance(data["result"], list), "'result' should be a list"
diff --git a/tests/api_test/sessions/test_session_used_commit.py b/tests/api_test/sessions/test_session_used_commit.py
new file mode 100644
index 000000000..1da08b74f
--- /dev/null
+++ b/tests/api_test/sessions/test_session_used_commit.py
@@ -0,0 +1,52 @@
+import json
+
+import pytest
+import requests
+
+
+class TestSessionUsedCommit:
+ def test_session_used_commit(self, api_client):
+ session_id = None
+
+ try:
+ response = api_client.create_session()
+ assert response.status_code == 200, "Create session failed"
+ data = response.json()
+ session_id = data["result"]["session_id"]
+ assert session_id is not None, "session_id should not be null"
+
+ response = api_client.add_message(session_id, "user", "Hello, test message!")
+ assert response.status_code == 200, "Add message failed"
+ data = response.json()
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ response = api_client.session_used(session_id)
+ assert response.status_code == 200, "Session used failed"
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Session Used API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+
+ response = api_client.session_commit(session_id)
+ assert response.status_code == 200, "Session commit failed"
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Session Commit API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+
+ response = api_client.delete_session(session_id)
+ assert response.status_code == 200, "Delete session failed"
+
+ except requests.exceptions.ConnectionError:
+ pytest.fail("Could not connect to server service - service is not running")
diff --git a/tests/api_test/skills/__init__.py b/tests/api_test/skills/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/api_test/skills/test_add_skill.py b/tests/api_test/skills/test_add_skill.py
new file mode 100644
index 000000000..f87b7088b
--- /dev/null
+++ b/tests/api_test/skills/test_add_skill.py
@@ -0,0 +1,85 @@
+import json
+import uuid
+
+
+class TestAddSkill:
+ def test_add_skill_with_dict(self, api_client):
+ try:
+ skill_name = f"test-skill-{uuid.uuid4().hex[:8]}"
+ skill = {
+ "name": skill_name,
+ "description": "A test skill for API testing",
+ "content": f"""# {skill_name}
+
+A test skill for API testing.
+
+## Parameters
+- **query** (string, required): Search query
+- **limit** (integer, optional): Max results, default 10
+""",
+ }
+
+ response = api_client.add_skill(skill, wait=True)
+ print(f"\nAdd skill API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Add Skill API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert data["result"].get("status") == "success", (
+ f"Expected result status 'success', got {data['result'].get('status')}"
+ )
+ assert "uri" in data["result"], "'uri' field should exist in result"
+ assert "name" in data["result"], "'name' field should exist in result"
+ assert data["result"]["name"] == skill_name, (
+ f"Expected skill name '{skill_name}', got {data['result']['name']}"
+ )
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
+
+ def test_add_skill_with_mcp_format(self, api_client):
+ try:
+ skill_name = f"test-calculator-{uuid.uuid4().hex[:8]}"
+ mcp_tool = {
+ "name": skill_name.replace("-", "_"),
+ "description": "Perform mathematical calculations",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "expression": {
+ "type": "string",
+ "description": "Mathematical expression to evaluate",
+ }
+ },
+ "required": ["expression"],
+ },
+ }
+
+ response = api_client.add_skill(mcp_tool, wait=True)
+ print(f"\nAdd MCP skill API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Add MCP Skill API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+ assert data["result"].get("status") == "success", (
+ f"Expected result status 'success', got {data['result'].get('status')}"
+ )
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/system/test_is_healthy.py b/tests/api_test/system/test_is_healthy.py
new file mode 100644
index 000000000..befb2c261
--- /dev/null
+++ b/tests/api_test/system/test_is_healthy.py
@@ -0,0 +1,22 @@
+import json
+
+
+class TestIsHealthy:
+ def test_is_healthy(self, api_client):
+ try:
+ response = api_client.is_healthy()
+ print(f"\nIs healthy API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Is Healthy API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/system/test_observer.py b/tests/api_test/system/test_observer.py
new file mode 100644
index 000000000..2f858f842
--- /dev/null
+++ b/tests/api_test/system/test_observer.py
@@ -0,0 +1,83 @@
+import json
+
+
+class TestObserver:
+ def test_observer_queue(self, api_client):
+ try:
+ response = api_client.observer_queue()
+ print(f"\nObserver queue API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Observer Queue API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
+
+ def test_observer_vikingdb(self, api_client):
+ try:
+ response = api_client.observer_vikingdb()
+ print(f"\nObserver vikingdb API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Observer VikingDB API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
+
+ def test_observer_system(self, api_client):
+ try:
+ response = api_client.observer_system()
+ print(f"\nObserver system API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Observer System API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
+
+ def test_observer_vlm(self, api_client):
+ try:
+ response = api_client.observer_vlm()
+ print(f"\nObserver VLM API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("Observer VLM API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/system/test_system_status.py b/tests/api_test/system/test_system_status.py
new file mode 100644
index 000000000..4f9b0c262
--- /dev/null
+++ b/tests/api_test/system/test_system_status.py
@@ -0,0 +1,23 @@
+import json
+
+
+class TestSystemStatus:
+ def test_system_status(self, api_client):
+ try:
+ response = api_client.system_status()
+ print(f"\nSystem status API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("System Status API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/system/test_system_wait.py b/tests/api_test/system/test_system_wait.py
new file mode 100644
index 000000000..18cc475a2
--- /dev/null
+++ b/tests/api_test/system/test_system_wait.py
@@ -0,0 +1,23 @@
+import json
+
+
+class TestSystemWait:
+ def test_system_wait(self, api_client):
+ try:
+ response = api_client.system_wait()
+ print(f"\nSystem wait API status code: {response.status_code}")
+
+ data = response.json()
+ print("\n" + "=" * 80)
+ print("System Wait API Response:")
+ print("=" * 80)
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+ print("=" * 80 + "\n")
+
+ assert data.get("status") == "ok", f"Expected status 'ok', got {data.get('status')}"
+ assert data.get("error") is None, f"Expected error to be null, got {data.get('error')}"
+ assert "result" in data, "'result' field should exist"
+
+ except Exception as e:
+ print(f"Error: {e}")
+ raise
diff --git a/tests/api_test/tools/checkers/check_admin.py b/tests/api_test/tools/checkers/check_admin.py
new file mode 100644
index 000000000..e4449cbfe
--- /dev/null
+++ b/tests/api_test/tools/checkers/check_admin.py
@@ -0,0 +1,7 @@
+# Let's look at the admin router
+admin_path = "/usr/local/lib/python3.11/site-packages/openviking/server/routers/admin.py"
+print(f"Reading {admin_path}...")
+print("=" * 80)
+
+with open(admin_path, "r") as f:
+ print(f.read())
diff --git a/tests/api_test/tools/checkers/check_api_keys.py b/tests/api_test/tools/checkers/check_api_keys.py
new file mode 100644
index 000000000..96074b030
--- /dev/null
+++ b/tests/api_test/tools/checkers/check_api_keys.py
@@ -0,0 +1,6 @@
+api_keys_path = "/usr/local/lib/python3.11/site-packages/openviking/server/api_keys.py"
+print(f"Reading {api_keys_path}...")
+print("=" * 80)
+
+with open(api_keys_path, "r") as f:
+ print(f.read())
diff --git a/tests/api_test/tools/checkers/check_app.py b/tests/api_test/tools/checkers/check_app.py
new file mode 100644
index 000000000..fc935de0e
--- /dev/null
+++ b/tests/api_test/tools/checkers/check_app.py
@@ -0,0 +1,6 @@
+app_path = "/usr/local/lib/python3.11/site-packages/openviking/server/app.py"
+print(f"Reading {app_path}...")
+print("=" * 80)
+
+with open(app_path, "r") as f:
+ print(f.read())
diff --git a/tests/api_test/tools/checkers/check_auth.py b/tests/api_test/tools/checkers/check_auth.py
new file mode 100644
index 000000000..428d7d0d4
--- /dev/null
+++ b/tests/api_test/tools/checkers/check_auth.py
@@ -0,0 +1,6 @@
+auth_path = "/usr/local/lib/python3.11/site-packages/openviking/server/auth.py"
+print(f"Reading {auth_path}...")
+print("=" * 80)
+
+with open(auth_path, "r") as f:
+ print(f.read())
diff --git a/tests/api_test/tools/checkers/check_bootstrap.py b/tests/api_test/tools/checkers/check_bootstrap.py
new file mode 100644
index 000000000..b273f6957
--- /dev/null
+++ b/tests/api_test/tools/checkers/check_bootstrap.py
@@ -0,0 +1,6 @@
+bootstrap_path = "/usr/local/lib/python3.11/site-packages/openviking/server/bootstrap.py"
+print(f"Reading {bootstrap_path}...")
+print("=" * 80)
+
+with open(bootstrap_path, "r") as f:
+ print(f.read())
diff --git a/tests/api_test/tools/checkers/check_config.py b/tests/api_test/tools/checkers/check_config.py
new file mode 100644
index 000000000..e8301e642
--- /dev/null
+++ b/tests/api_test/tools/checkers/check_config.py
@@ -0,0 +1,6 @@
+config_path = "/usr/local/lib/python3.11/site-packages/openviking/server/config.py"
+print(f"Reading {config_path}...")
+print("=" * 80)
+
+with open(config_path, "r") as f:
+ print(f.read())
diff --git a/tests/api_test/tools/checkers/check_endpoints.py b/tests/api_test/tools/checkers/check_endpoints.py
new file mode 100644
index 000000000..ca297c240
--- /dev/null
+++ b/tests/api_test/tools/checkers/check_endpoints.py
@@ -0,0 +1,92 @@
+#!/usr/bin/env python3
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+from api.client import OpenVikingAPIClient
+
+
+def check_endpoints():
+ client = OpenVikingAPIClient()
+
+ print("=" * 80)
+ print("Checking OpenViking API Endpoints")
+ print("=" * 80)
+
+ # Check health first
+ try:
+ response = client.server_health_check()
+ print(f"\n1. /health: {response.status_code}")
+ if response.status_code == 200:
+ print(f" Response: {response.json()}")
+ except Exception as e:
+ print(f"1. /health: ERROR - {e}")
+
+ # Check fs_ls
+ try:
+ response = client.fs_ls("viking://")
+ print(f"\n2. /api/v1/fs/ls: {response.status_code}")
+ if response.status_code == 200:
+ print(f" Response: {response.json()}")
+ files = response.json().get("result", [])
+ if files:
+ test_uri = files[0].get("uri")
+ if test_uri:
+ # Check fs_stat
+ try:
+ response = client.fs_stat(test_uri)
+ print(f"\n3. /api/v1/fs/stat: {response.status_code}")
+ if response.status_code == 200:
+ print(f" Response: {response.json()}")
+ except Exception as e:
+ print(f"3. /api/v1/fs/stat: ERROR - {e}")
+
+ # Check get_overview
+ try:
+ response = client.get_overview(test_uri)
+ print(f"\n4. /api/v1/content/overview: {response.status_code}")
+ if response.status_code == 200:
+ print(f" Response: {response.json()}")
+ except Exception as e:
+ print(f"4. /api/v1/content/overview: ERROR - {e}")
+
+ # Check fs_read
+ try:
+ response = client.fs_read(test_uri)
+ print(f"\n5. /api/v1/content/read: {response.status_code}")
+ if response.status_code == 200:
+ print(f" Response: {response.json()}")
+ except Exception as e:
+ print(f"5. /api/v1/content/read: ERROR - {e}")
+
+ # Check get_abstract
+ try:
+ response = client.get_abstract(test_uri)
+ print(f"\n6. /api/v1/content/abstract: {response.status_code}")
+ if response.status_code == 200:
+ print(f" Response: {response.json()}")
+ except Exception as e:
+ print(f"6. /api/v1/content/abstract: ERROR - {e}")
+ except Exception as e:
+ print(f"2. /api/v1/fs/ls: ERROR - {e}")
+
+ # Check fs_write (will likely fail but let's try)
+ try:
+ import uuid
+
+ test_uri = f"viking://user/test-{uuid.uuid4()[:8]}.md"
+ response = client.fs_write(test_uri, "test content")
+ print(f"\n7. /api/v1/content/write: {response.status_code}")
+ if response.status_code == 200:
+ print(f" Response: {response.json()}")
+ else:
+ print(f" Response text: {response.text}")
+ except Exception as e:
+ print(f"7. /api/v1/content/write: ERROR - {e}")
+
+ print("\n" + "=" * 80)
+
+
+if __name__ == "__main__":
+ check_endpoints()
diff --git a/tests/api_test/tools/checkers/check_logger.py b/tests/api_test/tools/checkers/check_logger.py
new file mode 100644
index 000000000..b203e2a50
--- /dev/null
+++ b/tests/api_test/tools/checkers/check_logger.py
@@ -0,0 +1,6 @@
+logger_path = "/usr/local/lib/python3.11/site-packages/openviking_cli/utils/logger.py"
+print(f"Reading {logger_path}...")
+print("=" * 80)
+
+with open(logger_path, "r") as f:
+ print(f.read())
diff --git a/tests/api_test/tools/checkers/check_logger_config.py b/tests/api_test/tools/checkers/check_logger_config.py
new file mode 100644
index 000000000..4eb986461
--- /dev/null
+++ b/tests/api_test/tools/checkers/check_logger_config.py
@@ -0,0 +1,31 @@
+import inspect
+import os
+
+import openviking_cli.utils
+
+print("Searching for configure_uvicorn_logging...")
+print("=" * 80)
+
+print(f"openviking_cli.utils path: {os.path.dirname(openviking_cli.utils.__file__)}")
+
+# List all modules in openviking_cli.utils
+utils_path = os.path.dirname(openviking_cli.utils.__file__)
+print("\nListing all .py files in utils directory:")
+for filename in os.listdir(utils_path):
+ if filename.endswith(".py") and not filename.startswith("_"):
+ print(f" {filename}")
+
+# Try to find configure_uvicorn_logging
+print("\nSearching for configure_uvicorn_logging in utils modules...")
+for filename in os.listdir(utils_path):
+ if filename.endswith(".py") and filename != "__init__.py":
+ module_name = f"openviking_cli.utils.{filename[:-3]}"
+ try:
+ module = __import__(module_name, fromlist=[""])
+ for name, obj in inspect.getmembers(module):
+ if name == "configure_uvicorn_logging":
+ print(f" Found configure_uvicorn_logging in {module_name}!")
+ print("\nCode for configure_uvicorn_logging:")
+ print(inspect.getsource(obj))
+ except Exception:
+ pass
diff --git a/tests/api_test/tools/checkers/check_server_config.py b/tests/api_test/tools/checkers/check_server_config.py
new file mode 100644
index 000000000..469171cc1
--- /dev/null
+++ b/tests/api_test/tools/checkers/check_server_config.py
@@ -0,0 +1,7 @@
+# Let's look at the server config module
+server_config_path = "/usr/local/lib/python3.11/site-packages/openviking/server/config.py"
+print(f"Reading {server_config_path}...")
+print("=" * 80)
+
+with open(server_config_path, "r") as f:
+ print(f.read())
diff --git a/tests/api_test/tools/config/config.py b/tests/api_test/tools/config/config.py
new file mode 100644
index 000000000..86ba8d317
--- /dev/null
+++ b/tests/api_test/tools/config/config.py
@@ -0,0 +1,21 @@
+import os
+
+
+class Config:
+ SERVER_HOST = os.getenv("SERVER_HOST", "127.0.0.1")
+ SERVER_PORT = int(os.getenv("SERVER_PORT", 1933))
+ CONSOLE_HOST = os.getenv("CONSOLE_HOST", "127.0.0.1")
+ CONSOLE_PORT = int(os.getenv("CONSOLE_PORT", 8020))
+
+ SERVER_URL = f"http://{SERVER_HOST}:{SERVER_PORT}"
+ CONSOLE_URL = f"http://{CONSOLE_HOST}:{CONSOLE_PORT}"
+
+ OPENVIKING_API_KEY = os.getenv("OPENVIKING_API_KEY", "test-root-api-key")
+ OPENVIKING_ACCOUNT = os.getenv("OPENVIKING_ACCOUNT", "default")
+ OPENVIKING_USER = os.getenv("OPENVIKING_USER", "default")
+
+ SERVER_STARTUP_TIMEOUT = 30
+ CONSOLE_STARTUP_TIMEOUT = 30
+ SERVICE_CHECK_INTERVAL = 1
+
+ USE_PYENV = os.getenv("OV_USE_PYENV", "true").lower() == "true"
diff --git a/tests/api_test/tools/config/find_root_key.py b/tests/api_test/tools/config/find_root_key.py
new file mode 100644
index 000000000..18b82836f
--- /dev/null
+++ b/tests/api_test/tools/config/find_root_key.py
@@ -0,0 +1,55 @@
+import os
+import subprocess
+
+import openviking
+
+print("Searching for root_api_key in OpenViking code...")
+
+# Find where openviking is installed
+
+openviking_path = os.path.dirname(openviking.__file__)
+print(f"OpenViking path: {openviking_path}")
+
+# Search for root_api_key in the code
+print("\nSearching in openviking package...")
+try:
+ result = subprocess.run(
+ ["grep", "-r", "root_api_key", openviking_path], capture_output=True, text=True
+ )
+ if result.stdout:
+ print(result.stdout)
+ else:
+ print("No matches in openviking package")
+except Exception as e:
+ print(f"Error searching: {e}")
+
+# Also check openviking_cli
+try:
+ import openviking_cli
+
+ cli_path = os.path.dirname(openviking_cli.__file__)
+ print(f"\nOpenViking CLI path: {cli_path}")
+ print("\nSearching in openviking_cli package...")
+ result = subprocess.run(
+ ["grep", "-r", "root_api_key", cli_path], capture_output=True, text=True
+ )
+ if result.stdout:
+ print(result.stdout)
+ else:
+ print("No matches in openviking_cli package")
+except Exception as e:
+ print(f"Error searching CLI: {e}")
+
+# Also search for "Admin API requires" to find where that error is coming from
+print("\n" + "=" * 80)
+print("Searching for error message...")
+try:
+ result = subprocess.run(
+ ["grep", "-r", "Admin API requires", openviking_path], capture_output=True, text=True
+ )
+ if result.stdout:
+ print(result.stdout)
+ else:
+ print("No matches for error message")
+except Exception as e:
+ print(f"Error searching error message: {e}")
diff --git a/tests/api_test/tools/config/generate_config.py b/tests/api_test/tools/config/generate_config.py
new file mode 100644
index 000000000..13678a00d
--- /dev/null
+++ b/tests/api_test/tools/config/generate_config.py
@@ -0,0 +1,21 @@
+#!/usr/bin/env python3
+import json
+import os
+
+config = {
+ "server": {
+ "host": "0.0.0.0",
+ "port": int(os.environ.get("SERVER_PORT", 1933)),
+ "root_api_key": os.environ.get("ROOT_API_KEY", "test-root-api-key"),
+ },
+ "log": {"level": os.environ.get("LOG_LEVEL", "INFO")},
+}
+
+config_path = "/etc/openviking/ov.conf"
+os.makedirs(os.path.dirname(config_path), exist_ok=True)
+
+with open(config_path, "w") as f:
+ json.dump(config, f, indent=2)
+
+print(f"Generated config at {config_path}")
+print(json.dumps(config, indent=2))
diff --git a/tests/api_test/tools/config/search_api_key_manager.py b/tests/api_test/tools/config/search_api_key_manager.py
new file mode 100644
index 000000000..8316470db
--- /dev/null
+++ b/tests/api_test/tools/config/search_api_key_manager.py
@@ -0,0 +1,29 @@
+import inspect
+import os
+
+import openviking.server
+
+print("Searching for APIKeyManager...")
+print("=" * 80)
+
+# List all modules in openviking.server
+server_path = os.path.dirname(openviking.server.__file__)
+print(f"Server module path: {server_path}")
+
+print("\nListing all .py files in server directory:")
+for filename in os.listdir(server_path):
+ if filename.endswith(".py") and not filename.startswith("_"):
+ print(f" {filename}")
+
+# Try to find APIKeyManager in all server modules
+print("\nSearching for APIKeyManager in server modules...")
+for filename in os.listdir(server_path):
+ if filename.endswith(".py") and filename != "__init__.py":
+ module_name = f"openviking.server.{filename[:-3]}"
+ try:
+ module = __import__(module_name, fromlist=[""])
+ for name, _obj in inspect.getmembers(module):
+ if name == "APIKeyManager":
+ print(f" Found APIKeyManager in {module_name}!")
+ except Exception:
+ pass
diff --git a/tests/api_test/tools/fixers/fix_escape_chars.py b/tests/api_test/tools/fixers/fix_escape_chars.py
new file mode 100644
index 000000000..57e737ff9
--- /dev/null
+++ b/tests/api_test/tools/fixers/fix_escape_chars.py
@@ -0,0 +1,36 @@
+import os
+
+
+def fix_escape_chars(file_path):
+ with open(file_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Replace all occurrences of \' with '
+ fixed_content = content.replace(r"\'", "'")
+
+ if fixed_content != content:
+ with open(file_path, "w", encoding="utf-8") as f:
+ f.write(fixed_content)
+ print(f"Fixed {file_path}")
+ return True
+ else:
+ print(f"No changes needed for {file_path}")
+ return False
+
+
+def main():
+ test_dir = "tests"
+ fixed_count = 0
+
+ for root, _dirs, files in os.walk(test_dir):
+ for file in files:
+ if file.endswith(".py") and file != "__init__.py" and file != "conftest.py":
+ file_path = os.path.join(root, file)
+ if fix_escape_chars(file_path):
+ fixed_count += 1
+
+ print(f"\nTotal files fixed: {fixed_count}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/api_test/tools/scripts/init-ollama.sh b/tests/api_test/tools/scripts/init-ollama.sh
new file mode 100755
index 000000000..dc5d3359e
--- /dev/null
+++ b/tests/api_test/tools/scripts/init-ollama.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+set -e
+
+echo "Waiting for Ollama service to be ready..."
+until ollama list > /dev/null 2>&1; do
+ echo "Ollama service not ready yet, waiting..."
+ sleep 2
+done
+
+echo "Ollama service is ready!"
+echo "Pulling nomic-embed-text model..."
+ollama pull nomic-embed-text
+
+echo "Model pull complete!"
+ollama list
diff --git a/tests/api_test/tools/scripts/start-server.sh b/tests/api_test/tools/scripts/start-server.sh
new file mode 100644
index 000000000..3c5f9532c
--- /dev/null
+++ b/tests/api_test/tools/scripts/start-server.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+set -e
+
+# 使用环境变量替换配置模板
+envsubst < /etc/openviking/ov.conf.template > /etc/openviking/ov.conf
+
+echo "Generated configuration:"
+cat /etc/openviking/ov.conf
+
+# 启动OpenViking服务
+exec openviking server start
diff --git a/tests/api_test/tools/scripts/start_services.py b/tests/api_test/tools/scripts/start_services.py
new file mode 100644
index 000000000..d464e4547
--- /dev/null
+++ b/tests/api_test/tools/scripts/start_services.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python3
+import sys
+import time
+
+from config import Config
+from services import OpenVikingServiceManager
+
+
+def main():
+ manager = OpenVikingServiceManager()
+
+ try:
+ if not manager.start_all():
+ print("❌ Failed to start services")
+ return 1
+
+ print("\n" + "=" * 60)
+ print("OpenViking services are running!")
+ print("=" * 60)
+ print(f"Server: {Config.SERVER_URL}")
+ print(f"Console: {Config.CONSOLE_URL}")
+ print("=" * 60)
+ print("\nPress Ctrl+C to stop services\n")
+
+ while True:
+ time.sleep(1)
+
+ except KeyboardInterrupt:
+ print("\n\nStopping services...")
+ finally:
+ # Stop services after test session
+ manager.stop_all()
+
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/api_test/tools/tests/test_admin_api.py b/tests/api_test/tools/tests/test_admin_api.py
new file mode 100644
index 000000000..19e31e9e1
--- /dev/null
+++ b/tests/api_test/tools/tests/test_admin_api.py
@@ -0,0 +1,22 @@
+import json
+
+from api.client import OpenVikingAPIClient
+
+
+def main():
+ client = OpenVikingAPIClient()
+
+ print("Current API Key:", client.api_key)
+ print("Current Headers:", client.session.headers)
+ print("\n" + "=" * 80 + "\n")
+
+ print("Testing admin_list_accounts...")
+ response = client.admin_list_accounts()
+ print(f"Status code: {response.status_code}")
+ print("Response:")
+ print(json.dumps(response.json(), indent=2, ensure_ascii=False))
+ print("\n" + "=" * 80 + "\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/api_test/tools/tests/test_api_key_manager.py b/tests/api_test/tools/tests/test_api_key_manager.py
new file mode 100644
index 000000000..508a1bd24
--- /dev/null
+++ b/tests/api_test/tools/tests/test_api_key_manager.py
@@ -0,0 +1,53 @@
+import asyncio
+
+from openviking.server.app import create_app
+from openviking.server.config import load_server_config
+
+
+async def test_api_key_manager():
+ try:
+ config = load_server_config()
+ app = create_app(config)
+ lifespan = app.router.lifespan_context
+
+ async with lifespan(app):
+ print(
+ "✅ api_key_manager exists!"
+ if hasattr(app.state, "api_key_manager")
+ else "❌ api_key_manager does NOT exist!"
+ )
+
+ print("\n" + "=" * 80)
+ print("Testing _get_api_key_manager function!")
+ print("=" * 80)
+
+ # Let's simulate a request
+ class MockRequest:
+ def __init__(self, app):
+ self.app = app
+
+ mock_request = MockRequest(app)
+
+ from openviking.server.routers.admin import _get_api_key_manager
+
+ try:
+ manager = _get_api_key_manager(mock_request)
+ print(f"✅ _get_api_key_manager returned: {manager}")
+
+ print("\nTesting manager.get_accounts()...")
+ accounts = manager.get_accounts()
+ print(f" accounts: {accounts}")
+ except Exception as e:
+ print(f"❌ _get_api_key_manager error: {e}")
+ import traceback
+
+ traceback.print_exc()
+
+ except Exception as e:
+ print(f"\n❌ Error: {e}")
+ import traceback
+
+ traceback.print_exc()
+
+
+asyncio.run(test_api_key_manager())
diff --git a/tests/api_test/tools/tests/test_app_state.py b/tests/api_test/tools/tests/test_app_state.py
new file mode 100644
index 000000000..5c650d161
--- /dev/null
+++ b/tests/api_test/tools/tests/test_app_state.py
@@ -0,0 +1,75 @@
+import os
+
+print("Testing app state in container...")
+print("=" * 80)
+
+print("\nFirst, let's check what's in /app directory:")
+print(os.listdir("/app"))
+
+print("\nNow let's create a simple test script:")
+test_script_content = """
+import asyncio
+from openviking.server.app import create_app
+from openviking.server.config import load_server_config
+
+async def test_app_state():
+ try:
+ config = load_server_config()
+ print(f"Config loaded:")
+ print(f" host: {config.host}")
+ print(f" port: {config.port}")
+ print(f" root_api_key: {config.root_api_key}")
+
+ print("\nCreating app...")
+ app = create_app(config)
+
+ print("\nApp created! Now entering lifespan...")
+ lifespan = app.router.lifespan_context
+
+ print("\n" + "="*80)
+ print("Entering lifespan context...")
+
+ async with lifespan(app):
+ print("\nInside lifespan context!")
+ print(f"app.state attributes: {dir(app.state)}")
+
+ if hasattr(app.state, 'api_key_manager'):
+ print(f"\n✅ api_key_manager exists!")
+ print(f" api_key_manager: {app.state.api_key_manager}")
+ else:
+ print(f"\n❌ api_key_manager does NOT exist!")
+
+ print("\n" + "="*80)
+ print("Now let's test _get_api_key_manager function!")
+ print("="*80)
+
+ # Let's simulate a request
+ class MockRequest:
+ def __init__(self, app):
+ self.app = app
+
+ mock_request = MockRequest(app)
+
+ from openviking.server.routers.admin import _get_api_key_manager
+
+ try:
+ manager = _get_api_key_manager(mock_request)
+ print(f"✅ _get_api_key_manager returned: {manager}")
+ except Exception as e:
+ print(f"❌ _get_api_key_manager error: {e}")
+ import traceback
+ traceback.print_exc()
+
+ except Exception as e:
+ print(f"\n❌ Error: {e}")
+ import traceback
+ traceback.print_exc()
+
+asyncio.run(test_app_state())
+"""
+
+with open("/app/test_app_state_in_container.py", "w") as f:
+ f.write(test_script_content)
+
+print("\nTest script created at /app/test_app_state_in_container.py")
+print("\nNow let's run it!")
diff --git a/tests/api_test/tools/tests/test_config_value.py b/tests/api_test/tools/tests/test_config_value.py
new file mode 100644
index 000000000..344b82bd1
--- /dev/null
+++ b/tests/api_test/tools/tests/test_config_value.py
@@ -0,0 +1,23 @@
+from openviking.server.config import load_server_config
+
+print("Testing config value...")
+print("=" * 80)
+
+try:
+ config = load_server_config()
+ print("Config loaded:")
+ print(f" host: {config.host}")
+ print(f" port: {config.port}")
+ print(f" root_api_key: {config.root_api_key}")
+ print(f" type(root_api_key): {type(config.root_api_key)}")
+
+ if config.root_api_key:
+ print("\n✅ root_api_key is present!")
+ else:
+ print("\n❌ root_api_key is NOT present!")
+
+except Exception as e:
+ print(f"\n❌ Error: {e}")
+ import traceback
+
+ traceback.print_exc()
diff --git a/tests/api_test/tools/tests/test_create_app.py b/tests/api_test/tools/tests/test_create_app.py
new file mode 100644
index 000000000..2d27030b0
--- /dev/null
+++ b/tests/api_test/tools/tests/test_create_app.py
@@ -0,0 +1,30 @@
+from openviking.server.app import create_app
+from openviking.server.config import load_server_config
+
+print("Testing create app...")
+print("=" * 80)
+
+try:
+ config = load_server_config()
+ print("load_server_config result:")
+ print(f" host: {config.host}")
+ print(f" port: {config.port}")
+ print(f" root_api_key: {config.root_api_key}")
+ print(f" type(root_api_key): {type(config.root_api_key)}")
+
+ print("\nCreating app...")
+ app = create_app(config)
+
+ print("\nApp created successfully!")
+ print(f"app.state attributes: {dir(app.state)}")
+
+ if hasattr(app.state, "api_key_manager"):
+ print(f"api_key_manager exists: {app.state.api_key_manager}")
+ else:
+ print("api_key_manager does NOT exist!")
+
+except Exception as e:
+ print(f"Error: {e}")
+ import traceback
+
+ traceback.print_exc()
diff --git a/tests/api_test/tools/tests/test_direct_request.py b/tests/api_test/tools/tests/test_direct_request.py
new file mode 100644
index 000000000..c9c67c0aa
--- /dev/null
+++ b/tests/api_test/tools/tests/test_direct_request.py
@@ -0,0 +1,24 @@
+import json
+
+import requests
+
+print("Testing direct request...")
+print("=" * 80)
+
+url = "http://127.0.0.1:1933/api/v1/admin/accounts"
+headers = {"Authorization": "Bearer test-root-api-key", "Content-Type": "application/json"}
+
+print(f"URL: {url}")
+print(f"Headers: {headers}")
+
+try:
+ response = requests.get(url, headers=headers)
+ print(f"\nStatus code: {response.status_code}")
+ print(f"Response headers: {dict(response.headers)}")
+ print("\nResponse content:")
+ print(json.dumps(response.json(), indent=2))
+except Exception as e:
+ print(f"\nError: {e}")
+ import traceback
+
+ traceback.print_exc()
diff --git a/tests/api_test/tools/tests/test_full_startup.py b/tests/api_test/tools/tests/test_full_startup.py
new file mode 100644
index 000000000..40f8364f7
--- /dev/null
+++ b/tests/api_test/tools/tests/test_full_startup.py
@@ -0,0 +1,44 @@
+import asyncio
+
+from openviking.server.app import create_app
+from openviking.server.config import load_server_config
+
+print("Testing full startup...")
+print("=" * 80)
+
+
+async def test_lifespan():
+ try:
+ config = load_server_config()
+ print("Config loaded:")
+ print(f" host: {config.host}")
+ print(f" port: {config.port}")
+ print(f" root_api_key: {config.root_api_key}")
+
+ print("\nCreating app...")
+ app = create_app(config)
+
+ print("\nApp created! Now entering lifespan...")
+ lifespan = app.router.lifespan_context
+
+ print("\n" + "=" * 80)
+ print("Entering lifespan context...")
+
+ async with lifespan(app):
+ print("\nInside lifespan context!")
+ print(f"app.state attributes: {dir(app.state)}")
+
+ if hasattr(app.state, "api_key_manager"):
+ print("\n✅ api_key_manager exists!")
+ print(f" api_key_manager: {app.state.api_key_manager}")
+ else:
+ print("\n❌ api_key_manager does NOT exist!")
+
+ except Exception as e:
+ print(f"\n❌ Error: {e}")
+ import traceback
+
+ traceback.print_exc()
+
+
+asyncio.run(test_lifespan())
diff --git a/tests/api_test/tools/tests/test_headers.py b/tests/api_test/tools/tests/test_headers.py
new file mode 100644
index 000000000..1a656320c
--- /dev/null
+++ b/tests/api_test/tools/tests/test_headers.py
@@ -0,0 +1,32 @@
+import json
+import sys
+
+import requests
+
+sys.path.insert(0, ".")
+
+from api.client import OpenVikingAPIClient
+
+client = OpenVikingAPIClient()
+
+print("Client configuration:")
+print(f" API Key: {client.api_key}")
+print(f" Account: {client.account}")
+print(f" User: {client.user}")
+print(f" Session headers: {dict(client.session.headers)}")
+
+print("\n" + "=" * 80)
+print("Testing admin list accounts with debug...")
+
+url = f"{client.server_url}/api/v1/admin/accounts"
+headers = dict(client.session.headers)
+
+print(f"URL: {url}")
+print(f"Headers: {json.dumps(headers, indent=2)}")
+
+try:
+ response = requests.get(url, headers=headers)
+ print(f"\nStatus code: {response.status_code}")
+ print(f"Response: {json.dumps(response.json(), indent=2)}")
+except Exception as e:
+ print(f"Error: {e}")
diff --git a/tests/api_test/tools/tests/test_lifespan.py b/tests/api_test/tools/tests/test_lifespan.py
new file mode 100644
index 000000000..a707a6c31
--- /dev/null
+++ b/tests/api_test/tools/tests/test_lifespan.py
@@ -0,0 +1,41 @@
+import asyncio
+
+from openviking.server.app import create_app
+from openviking.server.config import load_server_config
+
+print("Testing lifespan...")
+print("=" * 80)
+
+
+async def test_lifespan():
+ try:
+ config = load_server_config()
+ print("load_server_config result:")
+ print(f" host: {config.host}")
+ print(f" port: {config.port}")
+ print(f" root_api_key: {config.root_api_key}")
+
+ print("\nCreating app...")
+ app = create_app(config)
+
+ print("\nGetting lifespan...")
+ lifespan = app.router.lifespan_context
+
+ print("\nEntering lifespan context...")
+ async with lifespan(app):
+ print("Inside lifespan context!")
+ print(f"app.state attributes: {dir(app.state)}")
+
+ if hasattr(app.state, "api_key_manager"):
+ print(f"api_key_manager exists: {app.state.api_key_manager}")
+ else:
+ print("api_key_manager does NOT exist!")
+
+ except Exception as e:
+ print(f"Error: {e}")
+ import traceback
+
+ traceback.print_exc()
+
+
+asyncio.run(test_lifespan())
diff --git a/tests/api_test/tools/tests/test_load_config.py b/tests/api_test/tools/tests/test_load_config.py
new file mode 100644
index 000000000..789fc8dc0
--- /dev/null
+++ b/tests/api_test/tools/tests/test_load_config.py
@@ -0,0 +1,36 @@
+import os
+
+from openviking.server.config import load_server_config
+
+print("Testing load_server_config directly...")
+print("=" * 80)
+
+try:
+ config = load_server_config()
+ print("Config loaded successfully!")
+ print(f" host: {config.host}")
+ print(f" port: {config.port}")
+ print(f" root_api_key: {config.root_api_key}")
+ print(f" workers: {config.workers}")
+except Exception as e:
+ print(f"Error loading config: {e}")
+ import traceback
+
+ traceback.print_exc()
+
+print("\n" + "=" * 80)
+print("Checking environment variables...")
+print(f"OPENVIKING_CONFIG_FILE: {os.environ.get('OPENVIKING_CONFIG_FILE')}")
+
+print("\n" + "=" * 80)
+print("Checking config file directly...")
+try:
+ with open("/etc/openviking/ov.conf", "r") as f:
+ import json
+
+ data = json.load(f)
+ print(f"File content: {json.dumps(data, indent=2)}")
+ print(f"\nserver section: {json.dumps(data.get('server', {}), indent=2)}")
+ print(f"root_api_key from file: {data.get('server', {}).get('root_api_key')}")
+except Exception as e:
+ print(f"Error reading file: {e}")
diff --git a/tests/api_test/tools/tests/test_logger.py b/tests/api_test/tools/tests/test_logger.py
new file mode 100644
index 000000000..bd100f12a
--- /dev/null
+++ b/tests/api_test/tools/tests/test_logger.py
@@ -0,0 +1,24 @@
+import logging
+
+from openviking_cli.utils import get_logger
+
+print("Testing logger...")
+print("=" * 80)
+
+logger = get_logger(__name__)
+print(f"Logger: {logger}")
+print(f"Logger level: {logger.level}")
+
+print(f"\nRoot logger level: {logging.getLogger().level}")
+
+print("\nTesting log messages:")
+logger.debug("Debug message")
+logger.info("Info message")
+logger.warning("Warning message")
+logger.error("Error message")
+
+print("\n" + "=" * 80)
+print("Checking openviking.server.app logger...")
+
+app_logger = get_logger("openviking.server.app")
+print(f"App logger level: {app_logger.level}")
diff --git a/tests/api_test/tools/tests/test_logger_config.py b/tests/api_test/tools/tests/test_logger_config.py
new file mode 100644
index 000000000..fc98f0070
--- /dev/null
+++ b/tests/api_test/tools/tests/test_logger_config.py
@@ -0,0 +1,30 @@
+import logging
+
+from openviking_cli.utils import get_logger
+
+print("Testing logger config...")
+print("=" * 80)
+
+logger = get_logger("openviking.server.app")
+print(f"Logger: {logger}")
+print(f"Logger level: {logger.level}")
+print(f"Logger effective level: {logger.getEffectiveLevel()}")
+
+print("\nLogging levels:")
+print(f" DEBUG: {logging.DEBUG}")
+print(f" INFO: {logging.INFO}")
+print(f" WARNING: {logging.WARNING}")
+print(f" ERROR: {logging.ERROR}")
+
+print("\nTesting log messages:")
+logger.debug("Debug message - should we see this?")
+logger.info("Info message - should we see this?")
+logger.warning("Warning message - should we see this?")
+logger.error("Error message - should we see this?")
+
+print("\n" + "=" * 80)
+print("Root logger:")
+root_logger = logging.getLogger()
+print(f"Root logger level: {root_logger.level}")
+print(f"Root logger effective level: {root_logger.getEffectiveLevel()}")
+print(f"Root logger handlers: {root_logger.handlers}")
diff --git a/tests/api_test/tools/tests/test_simple_startup.py b/tests/api_test/tools/tests/test_simple_startup.py
new file mode 100644
index 000000000..9408596cf
--- /dev/null
+++ b/tests/api_test/tools/tests/test_simple_startup.py
@@ -0,0 +1,40 @@
+from openviking.server.app import create_app
+from openviking.server.config import load_server_config
+
+print("Testing simple startup...")
+print("=" * 80)
+
+try:
+ config = load_server_config()
+ print("Config loaded:")
+ print(f" host: {config.host}")
+ print(f" port: {config.port}")
+ print(f" root_api_key: {config.root_api_key}")
+
+ print("\nCreating app...")
+ app = create_app(config)
+
+ print("\nApp created! Now checking lifespan...")
+
+ # Let's check what lifespan looks like
+ lifespan = app.router.lifespan_context
+ print(f"Lifespan: {lifespan}")
+
+ print("\n" + "=" * 80)
+ print("Let's try to manually create APIKeyManager!")
+
+ from openviking.server.auth import APIKeyManager
+
+ manager = APIKeyManager(config.root_api_key, None)
+ print("APIKeyManager created successfully!")
+ print(f" manager.root_api_key: {manager.root_api_key}")
+
+ print("\nTesting manager.get_accounts()...")
+ accounts = manager.get_accounts()
+ print(f" accounts: {accounts}")
+
+except Exception as e:
+ print(f"\nError: {e}")
+ import traceback
+
+ traceback.print_exc()
diff --git a/tests/api_test/tools/tests/test_simple_state.py b/tests/api_test/tools/tests/test_simple_state.py
new file mode 100644
index 000000000..f8ae9e975
--- /dev/null
+++ b/tests/api_test/tools/tests/test_simple_state.py
@@ -0,0 +1,26 @@
+import asyncio
+
+from openviking.server.app import create_app
+from openviking.server.config import load_server_config
+
+
+async def test_simple():
+ try:
+ config = load_server_config()
+ app = create_app(config)
+ lifespan = app.router.lifespan_context
+
+ async with lifespan(app):
+ print("app.state attributes:", dir(app.state))
+ if hasattr(app.state, "api_key_manager"):
+ print("✅ api_key_manager exists!")
+ else:
+ print("❌ api_key_manager does NOT exist!")
+ except Exception as e:
+ print(f"Error: {e}")
+ import traceback
+
+ traceback.print_exc()
+
+
+asyncio.run(test_simple())