Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
[feat] Test/add resource ci validation and fix session api case 400 error (#1599)
kaisonglic7df2971dbce
diff --git a/.github/workflows/api_test.yml b/.github/workflows/api_test.ymlindex 35ddd5eb9..aeedaf698 100644--- a/.github/workflows/api_test.yml+++ b/.github/workflows/api_test.yml@@ -33,7 +33,7 @@ jobs:fail-fast: falsemax-parallel: 1matrix:- os: ${{ (github.event_name == 'push' && github.ref == 'refs/heads/main') && fromJSON('["ubuntu-24.04", "macos-14", "windows-latest"]') || fromJSON('["ubuntu-24.04"]') }}+ os: ${{ ((github.event_name == 'push' && github.ref == 'refs/heads/main') || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && fromJSON('["ubuntu-24.04", "macos-14", "windows-latest"]') || fromJSON('["ubuntu-24.04"]') }}steps:- uses: actions/checkout@v6@@ -67,12 +67,12 @@ jobs:- name: Install system dependencies (Ubuntu)if: runner.os == 'Linux'run: |- sudo apt-get update -y && sudo apt-get install -y cmake build-essential --no-install-recommends+ sudo apt-get update -y && sudo apt-get install -y cmake build-essential ffmpeg --no-install-recommends- name: Install system dependencies (macOS)if: runner.os == 'macOS'run: |- brew install cmake+ brew install cmake ffmpeg- name: Install system dependencies (Windows)if: runner.os == 'Windows'@@ -127,7 +127,7 @@ jobs:shell: bashrun: |RAGFS_LIB_DIR="openviking/lib"- RAGFS_SO_COUNT=$(ls -1 "$RAGFS_LIB_DIR"/ragfs_python*.so "$RAGFS_LIB_DIR"/ragfs_python*.pyd "$RAGFS_LIB_DIR"/ragfs_python*.dylib 2>/dev/null | wc -l | xargs || echo "0")+ RAGFS_SO_COUNT=$(ls -1 "$RAGFS_LIB_DIR"/ragfs_python*.so "$RAGFS_LIB_DIR"/ragfs_python*.pyd "$RAGFS_LIB_DIR"/ragfs_python*.dylib 2>/dev/null | wc -l | tr -d '[:space:]' || echo "0")if [ "$RAGFS_SO_COUNT" -gt 0 ]; thenecho "✅ ragfs_python native extension already exists:"@@ -150,13 +150,15 @@ jobs:echo "Extracting ragfs_python from wheel: $WHL_FILE"mkdir -p "$RAGFS_LIB_DIR"+ WHL_FILE_PY=$(echo "$WHL_FILE" | sed 's/\\/\\\\/g')+ RAGFS_LIB_DIR_PY=$(echo "$RAGFS_LIB_DIR" | sed 's/\\/\\\\/g')uv run python -c "import zipfile, os, sys, stat- with zipfile.ZipFile('$WHL_FILE') as zf:+ with zipfile.ZipFile('${WHL_FILE_PY}') as zf:for name in zf.namelist():bn = os.path.basename(name)if bn.startswith('ragfs_python') and (bn.endswith('.so') or bn.endswith('.pyd') or bn.endswith('.dylib')):- dst = os.path.join('$RAGFS_LIB_DIR', bn)+ dst = os.path.join('${RAGFS_LIB_DIR_PY}', bn)with zf.open(name) as src, open(dst, 'wb') as f:f.write(src.read())os.chmod(dst, 0o755)@@ -443,13 +445,14 @@ jobs:if [ "${{ env.HAS_SECRETS }}" = "true" ]; thenecho "Running full test suite with VLM/Embedding"- uv run python -m pytest . -v --html=api-test-report.html --self-contained-html+ uv run python -m pytest . -v --html=api-test-report.html --self-contained-html \+ --ignore=scenarios/resources_retrieval_slow/elseecho "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 \- --ignore=scenarios/ --ignore=sessions/ -k "not test_observer"+ --ignore=scenarios/ -k "not test_observer"ficontinue-on-error: true@@ -464,10 +467,10 @@ jobs:if ($env:HAS_SECRETS -eq "true") {Write-Host "Running full test suite with VLM/Embedding (Windows: skipping filesystem tests)"- uv run python -m pytest . -v --html=api-test-report.html --self-contained-html --ignore=filesystem/+ uv run python -m pytest . -v --html=api-test-report.html --self-contained-html --ignore=filesystem/ --ignore=scenarios/resources_retrieval_slow/} else {Write-Host "Running basic tests only (no VLM/Embedding, Windows: skipping filesystem tests)"- 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 --ignore=filesystem/ --ignore=scenarios/ --ignore=sessions/ -k "not test_observer"+ 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 --ignore=filesystem/ --ignore=scenarios/ -k "not test_observer"}continue-on-error: truediff --git a/.github/workflows/api_test_effect.yml b/.github/workflows/api_test_effect.ymlnew file mode 100644index 000000000..c356a1c47--- /dev/null+++ b/.github/workflows/api_test_effect.yml@@ -0,0 +1,222 @@+name: 07. API Effect Tests++on:+ workflow_dispatch:+ schedule:+ - cron: '0 2 * * *'++concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: true++jobs:+ effect-tests:+ name: API Effect Tests (${{ matrix.os }})+ runs-on: ${{ matrix.os }}+ timeout-minutes: 120+ strategy:+ fail-fast: false+ max-parallel: 1+ matrix:+ os: [ubuntu-24.04]++ steps:+ - uses: actions/checkout@v6+ with:+ submodules: recursive+ fetch-depth: 100++ - name: Set up Python 3.10+ uses: actions/setup-python@v6+ with:+ python-version: '3.10'++ - name: Cache Python dependencies+ uses: actions/cache@v5+ with:+ path: ~/.cache/pip+ key: ${{ runner.os }}-pip-effect-${{ hashFiles('**/requirements.txt', '**/pyproject.toml') }}+ restore-keys: |+ ${{ runner.os }}-pip-effect-++ - name: Install system dependencies+ run: |+ sudo apt-get update -y && sudo apt-get install -y cmake build-essential ffmpeg --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++ - name: Install dependencies using uv sync+ run: uv sync --frozen++ - name: Install build dependencies (uv pip)+ run: uv pip install setuptools setuptools_scm cmake wheel maturin++ - name: Set up Rust toolchain+ uses: dtolnay/rust-toolchain@v1+ with:+ toolchain: stable++ - name: Build C++ extensions+ shell: bash+ run: |+ export OV_SKIP_OV_BUILD=1+ mkdir -p openviking/bin+ touch openviking/bin/ov+ chmod +x openviking/bin/ov+ if [ -z "$SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENVIKING" ]; then+ PRETEND_VERSION=$(git describe --tags --always 2>/dev/null | sed -E 's/^v?([0-9]+\.[0-9]+\.[0-9]+).*/\1.dev0/' || echo "0.0.0.dev0")+ echo "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENVIKING=$PRETEND_VERSION" >> $GITHUB_ENV+ fi+ uv run python setup.py build_ext --inplace++ - name: Build ragfs-python native extension+ shell: bash+ run: |+ RAGFS_LIB_DIR="openviking/lib"+ RAGFS_SO_COUNT=$(ls -1 "$RAGFS_LIB_DIR"/ragfs_python*.so "$RAGFS_LIB_DIR"/ragfs_python*.pyd "$RAGFS_LIB_DIR"/ragfs_python*.dylib 2>/dev/null | wc -l | tr -d '[:space:]' || echo "0")+ if [ "$RAGFS_SO_COUNT" -gt 0 ]; then exit 0; fi+ TMPDIR_RAGFS=$(mktemp -d)+ cd crates/ragfs-python+ uv run --no-project maturin build --release --features s3 --out "$TMPDIR_RAGFS"+ cd ../..+ WHL_FILE=$(ls -1 "$TMPDIR_RAGFS"/ragfs_python-*.whl 2>/dev/null | head -1)+ if [ -z "$WHL_FILE" ]; then exit 1; fi+ mkdir -p "$RAGFS_LIB_DIR"+ WHL_FILE_PY=$(echo "$WHL_FILE" | sed 's/\\/\\\\/g')+ RAGFS_LIB_DIR_PY=$(echo "$RAGFS_LIB_DIR" | sed 's/\\/\\\\/g')+ uv run python -c "+ import zipfile, os, sys+ with zipfile.ZipFile('${WHL_FILE_PY}') as zf:+ for name in zf.namelist():+ bn = os.path.basename(name)+ if bn.startswith('ragfs_python') and (bn.endswith('.so') or bn.endswith('.pyd') or bn.endswith('.dylib')):+ dst = os.path.join('${RAGFS_LIB_DIR_PY}', bn)+ with zf.open(name) as src, open(dst, 'wb') as f:+ f.write(src.read())+ os.chmod(dst, 0o755)+ sys.exit(0)+ sys.exit(1)+ "+ rm -rf "$TMPDIR_RAGFS"++ - name: Install API test dependencies+ run: |+ cd tests/api_test+ uv pip install -r requirements.txt++ - name: Create OpenViking config file+ env:+ VLM_API_KEY: ${{ secrets.VLM_API_KEY }}+ EMBEDDING_API_KEY: ${{ secrets.EMBEDDING_API_KEY }}+ run: |+ mkdir -p $HOME/.openviking+ if [ -n "$VLM_API_KEY" ] && [ -n "$EMBEDDING_API_KEY" ]; then+ echo "HAS_SECRETS=true" >> $GITHUB_ENV+ cat > $HOME/.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+ echo "HAS_SECRETS=false" >> $GITHUB_ENV+ cat > $HOME/.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++ - name: Start OpenViking Server+ run: |+ SERVER_PORT=1933+ echo "SERVER_PORT=$SERVER_PORT" >> $GITHUB_ENV+ 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 "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+ if ! curl -s http://127.0.0.1:$SERVER_PORT/health | grep -q '"healthy":true'; then+ echo "Server failed to start!"+ cat openviking-server.log+ exit 1+ fi++ - name: Run Effect Tests+ id: run-effect-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 }}+ uv run python -m pytest scenarios/resources_retrieval_slow/ -v --tb=short --durations=0 --html=api-effect-test-report.html --self-contained-html+ continue-on-error: true++ - name: Upload test reports+ uses: actions/upload-artifact@v7+ if: always()+ with:+ name: api-effect-test-reports-${{ github.run_id }}+ path: |+ tests/api_test/api-effect-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-effect-tests.outcome != 'success'+ run: |+ echo "Effect tests failed!"+ exit 1diff --git a/tests/api_test/api/client.py b/tests/api_test/api/client.pyindex 30cf2ca5a..b716a456b 100644--- a/tests/api_test/api/client.py+++ b/tests/api_test/api/client.py@@ -256,6 +256,7 @@ class OpenVikingAPIClient:path: str,to: Optional[str] = None,reason: Optional[str] = None,+ parent: Optional[str] = None,wait: bool = False,) -> requests.Response:endpoint = "/api/v1/resources"@@ -273,6 +274,8 @@ class OpenVikingAPIClient:payload["to"] = toif reason:payload["reason"] = reason+ if parent:+ payload["parent"] = parentif wait:payload["wait"] = waittry:diff --git a/tests/api_test/conftest.py b/tests/api_test/conftest.pyindex 1deb94bc7..56692f76b 100644--- a/tests/api_test/conftest.py+++ b/tests/api_test/conftest.py@@ -58,6 +58,49 @@ TEST_CASE_DESCRIPTIONS = {"test_concurrent_write.py::TestConcurrentWrite::test_concurrent_write_conflict": "并发写入冲突验证","test_account_isolation.py::TestAccountIsolation::test_processed_not_zero_after_resource_ops": "账户隔离完整性验证","test_account_isolation.py::TestAccountIsolation::test_consecutive_health_checks": "账户隔离连续健康检查",+ "test_build_text_resources_slow.py::TestBuildTextResourcesSlow::test_build_txt_file": "TC-B01 TXT文本构建",+ "test_build_text_resources_slow.py::TestBuildTextResourcesSlow::test_build_markdown_file": "TC-B02 Markdown构建",+ "test_build_text_resources_slow.py::TestBuildTextResourcesSlow::test_build_empty_file": "TC-B15 空文件构建",+ "test_build_text_resources_slow.py::TestBuildTextResourcesSlow::test_build_raw_content": "TC-B14 原始内容构建",+ "test_build_document_resources_slow.py::TestBuildDocumentResourcesSlow::test_build_pdf_file": "TC-B03 PDF构建",+ "test_build_document_resources_slow.py::TestBuildDocumentResourcesSlow::test_build_html_file": "TC-B04 HTML构建",+ "test_build_document_resources_slow.py::TestBuildDocumentResourcesSlow::test_build_docx_file": "TC-B05 DOCX构建",+ "test_build_document_resources_slow.py::TestBuildDocumentResourcesSlow::test_build_legacy_doc_file": "TC-B06 .doc构建",+ "test_build_document_resources_slow.py::TestBuildDocumentResourcesSlow::test_build_pptx_file": "TC-B07 PPTX构建",+ "test_build_document_resources_slow.py::TestBuildDocumentResourcesSlow::test_build_xlsx_file": "TC-B08 XLSX构建",+ "test_build_document_resources_slow.py::TestBuildDocumentResourcesSlow::test_build_epub_file": "TC-B09 EPUB构建",+ "test_build_archive_resources.py::TestBuildArchiveResources::test_build_zip_file": "TC-B10 ZIP构建",+ "test_build_archive_resources.py::TestBuildArchiveResources::test_build_directory": "TC-B11 目录构建",+ "test_build_archive_resources.py::TestBuildArchiveResources::test_build_code_repository_url": "TC-B12 代码仓库URL构建",+ "test_build_media_resources_slow.py::TestBuildMediaResourcesSlow::test_build_image_svg": "TC-B13 图片构建(SVG)",+ "test_build_media_resources_slow.py::TestBuildMediaResourcesSlow::test_build_image_jpg": "TC-B13 图片构建(JPG)",+ "test_build_media_resources_slow.py::TestBuildMediaResourcesSlow::test_build_image_png": "TC-B13 图片构建(PNG)",+ "test_build_media_resources_slow.py::TestBuildMediaResourcesSlow::test_build_image_webp": "TC-B13 图片构建(WebP)",+ "test_build_media_resources_slow.py::TestBuildMediaResourcesSlow::test_build_audio_mp3": "TC-B14 音频构建(MP3)",+ "test_build_media_resources_slow.py::TestBuildMediaResourcesSlow::test_build_audio_wav": "TC-B14 音频构建(WAV)",+ "test_build_media_resources_slow.py::TestBuildMediaResourcesSlow::test_build_video_mp4": "TC-B15 视频构建(MP4)",+ "test_build_platform_github.py::TestBuildPlatformGithub::test_build_github_repo": "TC-P01 GitHub仓库构建",+ "test_build_platform_github.py::TestBuildPlatformGithub::test_build_github_repo_with_branch": "TC-P02 GitHub分支构建",+ "test_build_platform_github.py::TestBuildPlatformGithub::test_build_github_raw_file": "TC-P03 GitHub原始文件构建",+ "test_build_platform_github.py::TestBuildPlatformGithub::test_build_github_blob_page": "TC-P04 GitHub Blob页构建",+ "test_build_platform_wikipedia.py::TestBuildPlatformWikipedia::test_build_wikipedia_page": "TC-P05 Wikipedia构建",+ "test_build_platform_arxiv.py::TestBuildPlatformArxiv::test_build_arxiv_pdf": "TC-P06 arXiv PDF构建",+ "test_build_platform_arxiv.py::TestBuildPlatformArxiv::test_build_arxiv_abstract_page": "TC-P07 arXiv摘要页构建",+ "test_build_platform_general_web.py::TestBuildPlatformGeneralWeb::test_build_general_webpage": "TC-P10 通用网页构建",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_remote_404": "TC-E01 远端404不存在",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_remote_403": "TC-E02 远端403禁止访问",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_remote_500": "TC-E03 远端500服务错误",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_http_to_https_redirect": "TC-E05 HTTP→HTTPS跳转",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_multi_redirect": "TC-E06 多重跳转",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_dns_resolve_failure": "TC-E08 DNS解析失败",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_ssh_url_invalid_format": "TC-E09 SSH URL格式错误",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_duplicate_resource_no_to": "TC-E12 同名资源二次添加",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_incremental_update_with_to": "TC-E13 同to增量更新",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_unsupported_file_type": "TC-E15 不支持的文件类型",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_corrupted_zip": "TC-E16 损坏的ZIP文件",+ "test_build_uri_params_slow.py::TestBuildUriParamsSlow::test_build_with_to_param": "TC-E17 to参数指定URI",+ "test_build_uri_params_slow.py::TestBuildUriParamsSlow::test_build_with_parent_param": "TC-E18 parent参数指定父目录",+ "test_build_uri_params_slow.py::TestBuildUriParamsSlow::test_build_non_resources_scope_rejected": "TC-E11 scope参数非resources拒绝",}@@ -114,6 +157,49 @@ TEST_CASE_APIS = {"test_concurrent_write.py::TestConcurrentWrite::test_concurrent_write_conflict": "/api/v1/resources (并发写入)","test_account_isolation.py::TestAccountIsolation::test_processed_not_zero_after_resource_ops": "/api/v1/resources,/api/v1/search,/api/v1/system/observer","test_account_isolation.py::TestAccountIsolation::test_consecutive_health_checks": "/api/v1/system/healthy,/api/v1/system/observer",+ "test_build_text_resources_slow.py::TestBuildTextResourcesSlow::test_build_txt_file": "/api/v1/resources",+ "test_build_text_resources_slow.py::TestBuildTextResourcesSlow::test_build_markdown_file": "/api/v1/resources",+ "test_build_text_resources_slow.py::TestBuildTextResourcesSlow::test_build_empty_file": "/api/v1/resources",+ "test_build_text_resources_slow.py::TestBuildTextResourcesSlow::test_build_raw_content": "/api/v1/resources",+ "test_build_document_resources_slow.py::TestBuildDocumentResourcesSlow::test_build_pdf_file": "/api/v1/resources",+ "test_build_document_resources_slow.py::TestBuildDocumentResourcesSlow::test_build_html_file": "/api/v1/resources",+ "test_build_document_resources_slow.py::TestBuildDocumentResourcesSlow::test_build_docx_file": "/api/v1/resources",+ "test_build_document_resources_slow.py::TestBuildDocumentResourcesSlow::test_build_legacy_doc_file": "/api/v1/resources",+ "test_build_document_resources_slow.py::TestBuildDocumentResourcesSlow::test_build_pptx_file": "/api/v1/resources",+ "test_build_document_resources_slow.py::TestBuildDocumentResourcesSlow::test_build_xlsx_file": "/api/v1/resources",+ "test_build_document_resources_slow.py::TestBuildDocumentResourcesSlow::test_build_epub_file": "/api/v1/resources",+ "test_build_archive_resources.py::TestBuildArchiveResources::test_build_zip_file": "/api/v1/resources",+ "test_build_archive_resources.py::TestBuildArchiveResources::test_build_directory": "/api/v1/resources",+ "test_build_archive_resources.py::TestBuildArchiveResources::test_build_code_repository_url": "/api/v1/resources",+ "test_build_media_resources_slow.py::TestBuildMediaResourcesSlow::test_build_image_svg": "/api/v1/resources",+ "test_build_media_resources_slow.py::TestBuildMediaResourcesSlow::test_build_image_jpg": "/api/v1/resources",+ "test_build_media_resources_slow.py::TestBuildMediaResourcesSlow::test_build_image_png": "/api/v1/resources",+ "test_build_media_resources_slow.py::TestBuildMediaResourcesSlow::test_build_image_webp": "/api/v1/resources",+ "test_build_media_resources_slow.py::TestBuildMediaResourcesSlow::test_build_audio_mp3": "/api/v1/resources",+ "test_build_media_resources_slow.py::TestBuildMediaResourcesSlow::test_build_audio_wav": "/api/v1/resources",+ "test_build_media_resources_slow.py::TestBuildMediaResourcesSlow::test_build_video_mp4": "/api/v1/resources",+ "test_build_platform_github.py::TestBuildPlatformGithub::test_build_github_repo": "/api/v1/resources",+ "test_build_platform_github.py::TestBuildPlatformGithub::test_build_github_repo_with_branch": "/api/v1/resources",+ "test_build_platform_github.py::TestBuildPlatformGithub::test_build_github_raw_file": "/api/v1/resources",+ "test_build_platform_github.py::TestBuildPlatformGithub::test_build_github_blob_page": "/api/v1/resources",+ "test_build_platform_wikipedia.py::TestBuildPlatformWikipedia::test_build_wikipedia_page": "/api/v1/resources",+ "test_build_platform_arxiv.py::TestBuildPlatformArxiv::test_build_arxiv_pdf": "/api/v1/resources",+ "test_build_platform_arxiv.py::TestBuildPlatformArxiv::test_build_arxiv_abstract_page": "/api/v1/resources",+ "test_build_platform_general_web.py::TestBuildPlatformGeneralWeb::test_build_general_webpage": "/api/v1/resources",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_remote_404": "/api/v1/resources",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_remote_403": "/api/v1/resources",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_remote_500": "/api/v1/resources",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_http_to_https_redirect": "/api/v1/resources",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_multi_redirect": "/api/v1/resources",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_dns_resolve_failure": "/api/v1/resources",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_ssh_url_invalid_format": "/api/v1/resources",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_duplicate_resource_no_to": "/api/v1/resources",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_incremental_update_with_to": "/api/v1/resources",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_unsupported_file_type": "/api/v1/resources",+ "test_build_error_handling_slow.py::TestBuildErrorHandlingSlow::test_error_corrupted_zip": "/api/v1/resources",+ "test_build_uri_params_slow.py::TestBuildUriParamsSlow::test_build_with_to_param": "/api/v1/resources",+ "test_build_uri_params_slow.py::TestBuildUriParamsSlow::test_build_with_parent_param": "/api/v1/resources",+ "test_build_uri_params_slow.py::TestBuildUriParamsSlow::test_build_non_resources_scope_rejected": "/api/v1/resources",}@@ -189,10 +275,10 @@ def format_memory_delta(delta_bytes):def get_test_category(nodeid):parts = nodeid.split(os.sep)-+# 优先匹配更具体的路径(倒序匹配)priority_categories = ["stability_error", "resources_retrieval", "filesystem", "sessions"]-+for part in parts:if part in priority_categories:# 特殊处理:将子目录映射到正确的分类@@ -204,18 +290,45 @@ def get_test_category(nodeid):return "文件系统API"elif part == "sessions":return "会话管理API"-+# 如果没有匹配到优先分类,则按原逻辑匹配for part in parts:if part in CATEGORY_NAMES:return CATEGORY_NAMES[part]-+return "其他"@pytest.fixture(scope="session")def api_client():client = OpenVikingAPIClient(server_url=Config.SERVER_URL, api_key=Config.OPENVIKING_API_KEY)++ account_id = Config.OPENVIKING_ACCOUNT+ user_id = Config.OPENVIKING_USER++ try:+ resp = client.admin_list_users(account_id)+ if resp.status_code == 200:+ data = resp.json()+ users = data.get("result", [])+ user_exists = any(+ (isinstance(u, dict) and u.get("user_id") == user_id)+ or (isinstance(u, str) and u == user_id)+ for u in users+ )+ if not user_exists:+ reg_resp = client.admin_register_user(account_id, user_id, role="admin")+ if reg_resp.status_code in (200, 201):+ print(f"已注册用户 {account_id}/{user_id}")+ else:+ print(f"注册用户失败({reg_resp.status_code}): {reg_resp.text[:200]}")+ else:+ print(f"用户 {account_id}/{user_id} 已存在")+ else:+ print(f"无法查询用户列表({resp.status_code}), 跳过用户注册(可能为开发模式)")+ except Exception as e:+ print(f"用户注册检查异常, 跳过: {e}")+return client@@ -263,7 +376,7 @@ def pytest_runtest_makereport(item, call):curl = fixture_value.to_curl()if curl:report.sections.append(("cURL Command", curl))-+# 添加 Response Body 显示if hasattr(fixture_value, "last_response") and fixture_value.last_response:response = fixture_value.last_response@@ -272,9 +385,14 @@ def pytest_runtest_makereport(item, call):if response_text:try:import json+response_json = json.loads(response_text)- formatted_response = json.dumps(response_json, indent=2, ensure_ascii=False)- report.sections.append(("Response Body", f"<pre>{formatted_response}</pre>"))+ formatted_response = json.dumps(+ response_json, indent=2, ensure_ascii=False+ )+ report.sections.append(+ ("Response Body", f"<pre>{formatted_response}</pre>")+ )except Exception:report.sections.append(("Response Body", f"<pre>{response_text}</pre>"))diff --git a/tests/api_test/requirements.txt b/tests/api_test/requirements.txtindex e03da1947..656a41dbb 100644--- a/tests/api_test/requirements.txt+++ b/tests/api_test/requirements.txt@@ -4,3 +4,10 @@ pytest-html>=4.0.0requests>=2.28.0psutil>=5.9.0aiohttp>=3.8.0+fpdf2>=2.7.0+python-docx>=0.8.11+python-pptx>=0.6.21+openpyxl>=3.1.0+ebooklib>=0.18+Pillow>=9.0.0+# ffmpeg is a system dependency, install via: apt-get install ffmpeg (Ubuntu) or brew install ffmpeg (macOS)diff --git a/tests/api_test/scenarios/resources_retrieval/build_test_helpers.py b/tests/api_test/scenarios/resources_retrieval/build_test_helpers.pynew file mode 100644index 000000000..9961708e0--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval/build_test_helpers.py@@ -0,0 +1,270 @@+import os+import shutil+import tempfile+import uuid+++def create_test_file(content=None, suffix=".txt", filename=None):+ if content is None:+ content = (+ f"测试文件内容 - {uuid.uuid4()}\n这是一个用于构建测试的临时文件。\n包含一些测试数据。"+ )++ temp_dir = tempfile.mkdtemp()+ fname = filename or f"test_file_{str(uuid.uuid4())[:8]}{suffix}"+ test_file_path = os.path.join(temp_dir, fname)++ with open(test_file_path, "w", encoding="utf-8") as f:+ f.write(content)++ return test_file_path, temp_dir+++def create_test_directory(file_count=3, nested=True):+ temp_dir = tempfile.mkdtemp()++ for i in range(file_count):+ file_path = os.path.join(temp_dir, f"file_{i}.txt")+ with open(file_path, "w", encoding="utf-8") as f:+ f.write(f"测试文件 {i} 的内容\n一些测试数据 {uuid.uuid4()}")++ if nested:+ subdir = os.path.join(temp_dir, "subdir")+ os.makedirs(subdir)+ with open(os.path.join(subdir, "nested_file.txt"), "w", encoding="utf-8") as f:+ f.write("嵌套文件的内容")++ return temp_dir+++def create_test_zip(file_count=3):+ import zipfile++ temp_dir = tempfile.mkdtemp()+ zip_path = os.path.join(temp_dir, f"test_archive_{str(uuid.uuid4())[:8]}.zip")++ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:+ for i in range(file_count):+ content = f"压缩包内文件 {i} 的内容\n测试数据 {uuid.uuid4()}"+ zf.writestr(f"file_{i}.txt", content)+ zf.writestr("subdir/nested_file.txt", "压缩包内嵌套文件的内容")++ return zip_path, temp_dir+++def cleanup_temp_dir(temp_dir):+ if temp_dir and os.path.exists(temp_dir):+ shutil.rmtree(temp_dir, ignore_errors=True)+++def assert_root_uri_valid(root_uri):+ assert root_uri, "add_resource 必须返回 root_uri"+ assert root_uri.startswith("viking://resources/"), (+ f"root_uri 应以 viking://resources/ 开头, 实际: {root_uri}"+ )+++def assert_resource_findable(api_client, root_uri, keyword, timeout=90, poll_interval=3):+ import time++ api_client.wait_processed()++ start = time.time()+ poll_count = 0+ while time.time() - start < timeout:+ poll_count += 1++ if poll_count % 3 == 0:+ api_client.wait_processed()++ find_resp = api_client.find(keyword, target_uri=root_uri)+ if find_resp.status_code == 200:+ find_data = find_resp.json()+ if find_data.get("status") == "ok":+ search_result = find_data.get("result", {})+ for field in ["resources", "memories", "matches"]:+ items = search_result.get(field, [])+ if not isinstance(items, list):+ continue+ for item in items:+ if isinstance(item, dict) and "uri" in item and root_uri in item["uri"]:+ return True+ elif isinstance(item, str) and root_uri in item:+ return True++ if time.time() - start >= timeout:+ break+ time.sleep(poll_interval)++ return False+++def assert_resource_indexed(api_client, root_uri, keyword, timeout=120):+ found = assert_resource_findable(api_client, root_uri, keyword, timeout=timeout)+ assert found, f"搜索应能检索到资源 {root_uri}, 关键词: {keyword}"+ return found+++def _extract_error_message(data):+ if not isinstance(data, dict):+ return str(data)+ error = data.get("error")+ if isinstance(error, dict):+ return error.get("message", "") + " " + error.get("code", "")+ errors = data.get("errors", [])+ if isinstance(errors, list):+ return " ".join(str(e) for e in errors)+ return str(data.get("message", data.get("msg", "")))+++def assert_source_format(api_client, root_uri, expected_format):+ if isinstance(expected_format, str):+ expected_format = [expected_format]++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200, f"fs_stat 应返回200, root_uri: {root_uri}"+ stat_data = stat_resp.json()+ stat_result = stat_data.get("result")++ if isinstance(stat_result, dict):+ actual_format = stat_result.get("source_format")+ if actual_format:+ assert actual_format in expected_format, (+ f"source_format 应为 {expected_format}, 实际: {actual_format}"+ )+ return++ tree_resp = api_client.fs_tree(root_uri)+ if tree_resp.status_code == 200:+ tree_data = tree_resp.json()+ tree_result = tree_data.get("result")+ if isinstance(tree_result, dict):+ actual_format = tree_result.get("source_format")+ if actual_format:+ assert actual_format in expected_format, (+ f"source_format 应为 {expected_format}, 实际: {actual_format}"+ )+ return+ children = tree_result.get("children", [])+ elif isinstance(tree_result, list):+ children = tree_result+ else:+ children = []++ for child in children:+ if isinstance(child, dict):+ actual_format = child.get("source_format")+ if actual_format:+ assert actual_format in expected_format, (+ f"source_format 应为 {expected_format}, 实际: {actual_format}"+ )+ return++ ls_resp = api_client.fs_ls(root_uri, recursive=True)+ if ls_resp.status_code == 200:+ ls_data = ls_resp.json()+ ls_result = ls_data.get("result")+ items = ls_result if isinstance(ls_result, list) else []+ for item in items:+ if isinstance(item, dict):+ actual_format = item.get("source_format")+ if actual_format:+ assert actual_format in expected_format, (+ f"source_format 应为 {expected_format}, 实际: {actual_format}"+ )+ return++ ext_format_map = {+ ".txt": ["text", "markdown"],+ ".text": ["text"],+ ".md": ["markdown"],+ ".markdown": ["markdown"],+ ".pdf": ["pdf"],+ ".html": ["html"],+ ".htm": ["html"],+ ".docx": ["docx"],+ ".doc": ["doc"],+ ".pptx": ["pptx"],+ ".xlsx": ["xlsx"],+ ".epub": ["epub"],+ ".zip": ["zip"],+ ".png": ["image"],+ ".jpg": ["image"],+ ".jpeg": ["image"],+ ".mp3": ["audio"],+ ".wav": ["audio"],+ ".mp4": ["video"],+ }+ if ls_resp.status_code == 200:+ ls_data = ls_resp.json()+ ls_result = ls_data.get("result")+ items = ls_result if isinstance(ls_result, list) else []+ for item in items:+ if isinstance(item, dict):+ rel_path = item.get("rel_path", "")+ uri = item.get("uri", "")+ for ext, fmt_list in ext_format_map.items():+ if rel_path.endswith(ext) or uri.endswith(ext):+ assert any(f in expected_format for f in fmt_list), (+ f"根据扩展名 {ext} 推断 source_format 应为 {fmt_list}, 期望: {expected_format}"+ )+ return+++def assert_tree_has_child_nodes(api_client, root_uri, min_nodes=1):+ tree_resp = api_client.fs_tree(root_uri)+ assert tree_resp.status_code == 200, f"fs_tree 应返回200, root_uri: {root_uri}"+ tree_data = tree_resp.json()+ tree_result = tree_data.get("result")++ if isinstance(tree_result, list):+ children = tree_result+ elif isinstance(tree_result, dict):+ children = tree_result.get("children", [])+ else:+ children = []++ assert len(children) >= min_nodes, (+ f"tree 应至少包含 {min_nodes} 个子节点, 实际: {len(children)}"+ )+++def assert_content_no_html_tags(api_client, root_uri):+ grep_resp = api_client.grep(root_uri, pattern="<[a-z][a-z0-9]*[^>]*>")+ if grep_resp.status_code != 200:+ return+ grep_data = grep_resp.json()+ grep_result = grep_data.get("result", {})+ matches = grep_result.get("matches", [])+ html_matches = [m for m in matches if isinstance(m, dict) and "<" in str(m.get("line", ""))]+ assert len(html_matches) == 0, (+ f"HTML内容应被剥离, 但仍包含HTML标签: {[m.get('line', '')[:80] for m in html_matches[:3]]}"+ )+++def assert_overview_or_abstract_contains(+ api_client, root_uri, keyword, timeout=60, poll_interval=3+):+ import time++ start = time.time()+ while time.time() - start < timeout:+ overview_resp = api_client.get_overview(root_uri)+ if overview_resp.status_code == 200:+ overview_data = overview_resp.json()+ overview_text = str(overview_data.get("result", ""))+ if keyword.lower() in overview_text.lower():+ return True++ abstract_resp = api_client.get_abstract(root_uri)+ if abstract_resp.status_code == 200:+ abstract_data = abstract_resp.json()+ abstract_text = str(abstract_data.get("result", ""))+ if keyword.lower() in abstract_text.lower():+ return True++ if time.time() - start >= timeout:+ break+ time.sleep(poll_interval)++ return Falsediff --git a/tests/api_test/scenarios/resources_retrieval/conftest.py b/tests/api_test/scenarios/resources_retrieval/conftest.pynew file mode 100644index 000000000..e669d95eb--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval/conftest.py@@ -0,0 +1,4 @@+import os+import sys++sys.path.insert(0, os.path.dirname(__file__))diff --git a/tests/api_test/scenarios/resources_retrieval/test_build_document_resources.py b/tests/api_test/scenarios/resources_retrieval/test_build_document_resources.pynew file mode 100644index 000000000..59bcbf6b5--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval/test_build_document_resources.py@@ -0,0 +1,109 @@+import os+import shutil+import tempfile+import uuid++import pytest+from build_test_helpers import (+ assert_content_no_html_tags,+ assert_resource_indexed,+ assert_root_uri_valid,+ assert_source_format,+)+++def _create_html_file():+ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"html_keyword_{random_id}"+ temp_dir = tempfile.mkdtemp()+ html_path = os.path.join(temp_dir, f"test_{random_id}.html")++ content = (+ f"<html><head><title>HTML Test {random_id}</title></head>"+ f"<body><h1>HTML测试标题 {random_id}</h1>"+ f"<p>包含唯一关键词:{unique_keyword}</p>"+ f"<p>用于验证HTML文件构建产物。</p>"+ f"</body></html>"+ )+ with open(html_path, "w", encoding="utf-8") as f:+ f.write(content)++ return html_path, temp_dir, unique_keyword+++def _create_pptx_file():+ try:+ from pptx import Presentation+ except ImportError:+ pytest.skip("python-pptx 未安装,跳过 PPTX 构建测试")++ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"pptx_keyword_{random_id}"+ temp_dir = tempfile.mkdtemp()+ pptx_path = os.path.join(temp_dir, f"test_{random_id}.pptx")++ prs = Presentation()+ slide = prs.slides.add_slide(prs.slide_layouts[1])+ title = slide.shapes.title+ title.text = f"PPT测试标题 {random_id}"+ body = slide.placeholders[1]+ body.text = f"包含唯一关键词:{unique_keyword}\n用于验证PPT文件构建产物。"+ prs.save(pptx_path)++ return pptx_path, temp_dir, unique_keyword+++class TestBuildDocumentResources:+ """TC-B04, B07 文档类资源构建测试(快速用例,≤20s)"""++ def test_build_html_file(self, api_client):+ """TC-B04 HTML文件构建:验证 .html 文件添加后 source_format=html 且标签被剥离"""+ html_path, temp_dir, unique_keyword = _create_html_file()+ try:+ response = api_client.add_resource(path=html_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, ["html", "markdown"])++ assert_content_no_html_tags(api_client, root_uri)++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B04 HTML文件构建通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_pptx_file(self, api_client):+ """TC-B07 PowerPoint构建:验证 .pptx 文件添加后 source_format=pptx 且内容可检索"""+ pptx_path, temp_dir, unique_keyword = _create_pptx_file()+ try:+ response = api_client.add_resource(path=pptx_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, ["pptx", "markdown"])++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B07 PowerPoint构建通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)diff --git a/tests/api_test/scenarios/resources_retrieval/test_build_error_handling.py b/tests/api_test/scenarios/resources_retrieval/test_build_error_handling.pynew file mode 100644index 000000000..72a97d7d5--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval/test_build_error_handling.py@@ -0,0 +1,158 @@+import os+import shutil+import tempfile+import uuid++from build_test_helpers import (+ _extract_error_message,+ assert_root_uri_valid,+ cleanup_temp_dir,+ create_test_file,+)+++class TestBuildErrorHandling:+ """TC-E01, E08, E09, E11, E16 异常与边界测试(快速用例,≤20s)"""++ def test_error_remote_404(self, api_client):+ """TC-E01 远端404不存在:验证 404 URL 返回错误且不崩溃,错误信息应包含状态码"""+ url_404 = "https://httpbin.org/status/404"++ response = api_client.add_resource(path=url_404, wait=True)++ data = response.json()+ if data.get("status") == "error":+ error_msg = _extract_error_message(data).lower()+ assert "404" in error_msg or "not found" in error_msg or "error" in error_msg, (+ f"404错误信息应包含 404/not found/error, 实际: {error_msg}"+ )+ print("✓ TC-E01 远端404不存在处理通过(返回error)")+ return++ if data.get("status") == "ok":+ result = data.get("result", {})+ root_uri = result.get("root_uri")+ if root_uri:+ assert_root_uri_valid(root_uri)+ print("✓ TC-E01 远端404处理通过(降级为空资源)")+ return++ raise AssertionError(f"404 URL 应返回 error 或 ok, 实际: {data.get('status')}")++ def test_error_dns_resolve_failure(self, api_client):+ """TC-E08 DNS解析失败:验证不存在的域名返回错误且不挂起"""+ bad_dns_url = "https://nonexistent.domain.invalid.for.test/page"++ response = api_client.add_resource(path=bad_dns_url, wait=True)++ data = response.json()+ if data.get("status") == "error":+ error_msg = _extract_error_message(data).lower()+ assert (+ "resolve" in error_msg+ or "hostname" in error_msg+ or "dns" in error_msg+ or "error" in error_msg+ ), f"DNS失败错误信息应包含 resolve/hostname/dns/error, 实际: {error_msg}"+ print("✓ TC-E08 DNS解析失败处理通过(返回error)")+ return++ if data.get("status") == "ok":+ result = data.get("result", {})+ root_uri = result.get("root_uri")+ if root_uri:+ assert_root_uri_valid(root_uri)+ print("✓ TC-E08 DNS解析失败处理通过(降级为空资源)")+ return++ raise AssertionError(f"DNS失败 URL 应返回 error 或 ok, 实际: {data.get('status')}")++ def test_error_ssh_url_invalid_format(self, api_client):+ """TC-E09 SSH URL格式错误:验证 git@invalid (无冒号) 返回 InvalidArgumentError"""+ invalid_ssh_url = "git@invalid"++ response = api_client.add_resource(path=invalid_ssh_url, wait=True)++ data = response.json()+ if data.get("status") == "error":+ error_msg = _extract_error_message(data).lower()+ assert (+ "invalid" in error_msg+ or "ssh" in error_msg+ or "uri" in error_msg+ or "colon" in error_msg+ or "error" in error_msg+ or "permission" in error_msg+ ), f"SSH格式错误应包含 invalid/ssh/uri/colon/error/permission, 实际: {error_msg}"+ print("✓ TC-E09 SSH URL格式错误处理通过")+ return++ if data.get("status") == "ok":+ print("✓ TC-E09 SSH URL格式错误处理通过(服务端降级)")+ return++ raise AssertionError(f"SSH URL格式错误应返回 error 或降级, 实际: {data.get('status')}")++ def test_error_non_resources_scope_rejected(self, api_client):+ """TC-E11 非resources scope拒绝:验证 to=viking://sessions/xxx 返回错误"""+ random_id = str(uuid.uuid4())[:8]+ test_content = f"scope测试内容 {random_id}"+ test_file_path, temp_dir = create_test_file(content=test_content, suffix=".txt")+ try:+ response = api_client.add_resource(+ path=test_file_path,+ to="viking://sessions/test_session",+ wait=True,+ )++ data = response.json()+ if data.get("status") == "error":+ error_msg = _extract_error_message(data).lower()+ assert (+ "scope" in error_msg+ or "resources" in error_msg+ or "invalid" in error_msg+ or "permission" in error_msg+ or "internal" in error_msg+ ), f"scope拒绝应包含 scope/resources/invalid/permission/internal, 实际: {error_msg}"+ print("✓ TC-E11 非resources scope拒绝通过")+ return++ if data.get("status") == "ok":+ result = data.get("result", {})+ root_uri = result.get("root_uri", "")+ assert "sessions" not in root_uri, (+ f"非resources scope不应成功写入sessions, root_uri: {root_uri}"+ )+ print("✓ TC-E11 非resources scope处理通过(服务端重定向)")+ return+ finally:+ cleanup_temp_dir(temp_dir)++ def test_error_corrupted_zip(self, api_client):+ """TC-E16 损坏的ZIP文件:验证伪造 .zip 文件回退或报错且不崩溃"""+ random_id = str(uuid.uuid4())[:8]++ temp_dir = tempfile.mkdtemp()+ zip_path = os.path.join(temp_dir, f"corrupted_{random_id}.zip")+ with open(zip_path, "w", encoding="utf-8") as f:+ f.write("这不是一个真正的ZIP文件内容")++ try:+ response = api_client.add_resource(path=zip_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") in ("ok", "error"), (+ f"损坏ZIP应返回 ok 或 error, 实际: {data.get('status')}"+ )++ if data.get("status") == "ok":+ result = data.get("result", {})+ root_uri = result.get("root_uri")+ if root_uri:+ assert_root_uri_valid(root_uri)++ print("✓ TC-E16 损坏的ZIP文件处理通过")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)diff --git a/tests/api_test/scenarios/resources_retrieval/test_build_media_resources.py b/tests/api_test/scenarios/resources_retrieval/test_build_media_resources.pynew file mode 100644index 000000000..6473580ed--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval/test_build_media_resources.py@@ -0,0 +1,95 @@+import os+import shutil+import struct+import tempfile+import uuid+import wave++import pytest+from build_test_helpers import assert_root_uri_valid, assert_source_format+++def _create_image_file(ext=".png"):+ try:+ from PIL import Image+ except ImportError:+ pytest.skip("Pillow 未安装,跳过图片构建测试")++ random_id = str(uuid.uuid4())[:8]+ temp_dir = tempfile.mkdtemp()+ img_path = os.path.join(temp_dir, f"test_{random_id}{ext}")++ img = Image.new("RGB", (100, 100), color=(73, 109, 137))+ img.save(img_path)++ return img_path, temp_dir, random_id+++def _create_audio_file(ext=".wav"):+ random_id = str(uuid.uuid4())[:8]+ temp_dir = tempfile.mkdtemp()+ audio_path = os.path.join(temp_dir, f"test_{random_id}{ext}")++ with wave.open(audio_path, "w") as wf:+ wf.setnchannels(1)+ wf.setsampwidth(2)+ wf.setframerate(44100)+ frames = b""+ for _i in range(44100):+ value = int(32767 * 0.5)+ frames += struct.pack("<h", value)+ wf.writeframes(frames)++ return audio_path, temp_dir, random_id+++class TestBuildMediaResources:+ """TC-B13(PNG), B14(WAV) 媒体类资源构建测试(快速用例,≤20s)"""++ def test_build_image_png(self, api_client):+ """TC-B13 图片构建(PNG):验证 .png 文件添加后产物路径含 /images/ 且 source_format=image"""+ img_path, temp_dir, random_id = _create_image_file(".png")+ try:+ response = api_client.add_resource(path=img_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)+ assert "/images/" in root_uri, f"图片 root_uri 应含 /images/, 实际: {root_uri}"++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, "image")++ print(f"✓ TC-B13 图片构建(PNG)通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_audio_wav(self, api_client):+ """TC-B14 音频构建(WAV):验证 .wav 文件添加后产物路径含 /audio/ 且 source_format=audio"""+ audio_path, temp_dir, random_id = _create_audio_file(".wav")+ try:+ response = api_client.add_resource(path=audio_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)+ assert "/audio/" in root_uri, f"音频 root_uri 应含 /audio/, 实际: {root_uri}"++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, "audio")++ print(f"✓ TC-B14 音频构建(WAV)通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)diff --git a/tests/api_test/scenarios/resources_retrieval/test_build_text_resources.py b/tests/api_test/scenarios/resources_retrieval/test_build_text_resources.pynew file mode 100644index 000000000..8db0ab9fc--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval/test_build_text_resources.py@@ -0,0 +1,73 @@+import uuid++from build_test_helpers import (+ assert_resource_indexed,+ assert_root_uri_valid,+ assert_source_format,+ assert_tree_has_child_nodes,+ cleanup_temp_dir,+ create_test_file,+)+++class TestBuildTextResources:+ """TC-B02, B15 文本类资源构建测试(快速用例,≤20s)"""++ def test_build_markdown_file(self, api_client):+ """TC-B02 Markdown文件构建:验证 .md 文件添加后 heading 结构保留为子节点"""+ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"md_keyword_{random_id}"+ content = (+ f"# Markdown测试标题 {random_id}\n\n"+ f"包含唯一关键词:{unique_keyword}\n\n"+ f"## 第一节\n\n第一段内容。\n\n"+ f"## 第二节\n\n第二段内容。\n\n"+ f"### 子节\n\n子节内容。\n"+ )++ test_file_path, temp_dir = create_test_file(content=content, suffix=".md")+ try:+ response = api_client.add_resource(path=test_file_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, "markdown")++ assert_tree_has_child_nodes(api_client, root_uri, min_nodes=1)++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B02 Markdown文件构建通过, root_uri: {root_uri}")+ finally:+ cleanup_temp_dir(temp_dir)++ def test_build_empty_file(self, api_client):+ """TC-B15 空文件构建:验证空 .txt 文件添加不崩溃并返回合理结果"""+ test_file_path, temp_dir = create_test_file(content="", suffix=".txt")+ try:+ response = api_client.add_resource(path=test_file_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") in ("ok", "error"), (+ f"空文件构建应返回 ok 或 error, 实际: {data.get('status')}"+ )++ if data.get("status") == "ok":+ result = data.get("result", {})+ root_uri = result.get("root_uri")+ if root_uri:+ assert_root_uri_valid(root_uri)++ print("✓ TC-B15 空文件构建通过")+ finally:+ cleanup_temp_dir(temp_dir)diff --git a/tests/api_test/scenarios/resources_retrieval/test_build_uri_params.py b/tests/api_test/scenarios/resources_retrieval/test_build_uri_params.pynew file mode 100644index 000000000..6ea4fb596--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval/test_build_uri_params.py@@ -0,0 +1,89 @@+import uuid++from build_test_helpers import (+ _extract_error_message,+ assert_root_uri_valid,+ cleanup_temp_dir,+ create_test_file,+)+++class TestBuildUriParams:+ """TC-E11(参数部分), TC-E18 URI 参数与边界测试(快速用例,≤20s)"""++ def test_build_with_parent_param(self, api_client):+ """TC-E18 指定parent参数构建:验证 root_uri 以 parent 为前缀"""+ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"parent_keyword_{random_id}"+ parent_uri = f"viking://resources/parent_test_{random_id}"++ mkdir_resp = api_client.fs_mkdir(parent_uri)+ assert mkdir_resp.status_code == 200, (+ f"无法创建parent目录, fs_mkdir返回: {mkdir_resp.status_code}, body: {mkdir_resp.text}"+ )++ content = f"parent参数测试 {random_id}\n包含唯一关键词:{unique_keyword}"+ test_file_path, temp_dir = create_test_file(content=content, suffix=".txt")+ try:+ response = api_client.add_resource(path=test_file_path, parent=parent_uri, wait=True)+ assert response.status_code == 200++ data = response.json()+ if data.get("status") == "error":+ error_msg = _extract_error_message(data)+ raise AssertionError(f"parent参数构建失败, 服务端不支持parent参数: {error_msg}")++ result = data.get("result", {})+ if isinstance(result, dict) and result.get("status") == "error":+ inner_errors = result.get("errors", [])+ inner_msg = " ".join(str(e) for e in inner_errors)+ raise AssertionError(f"parent参数构建失败(内层错误): {inner_msg}")++ root_uri = result.get("root_uri") if isinstance(result, dict) else None+ assert_root_uri_valid(root_uri)+ assert root_uri.startswith(parent_uri), (+ f"指定parent时 root_uri 应以 parent 为前缀, parent: {parent_uri}, 实际: {root_uri}"+ )++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ print(f"✓ TC-E18 指定parent参数构建通过, root_uri: {root_uri}")+ finally:+ cleanup_temp_dir(temp_dir)++ def test_build_non_resources_scope_rejected(self, api_client):+ """TC-E11 非resources scope拒绝:验证 to=viking://sessions/xxx 返回错误"""+ random_id = str(uuid.uuid4())[:8]+ test_content = f"scope测试内容 {random_id}"+ test_file_path, temp_dir = create_test_file(content=test_content, suffix=".txt")+ try:+ response = api_client.add_resource(+ path=test_file_path,+ to="viking://sessions/test_session",+ wait=True,+ )++ data = response.json()+ if data.get("status") == "error":+ error_msg = _extract_error_message(data).lower()+ assert (+ "scope" in error_msg+ or "resources" in error_msg+ or "invalid" in error_msg+ or "permission" in error_msg+ or "internal" in error_msg+ ), f"scope拒绝应包含 scope/resources/invalid/permission/internal, 实际: {error_msg}"+ print("✓ TC-E11 非resources scope拒绝通过")+ return++ if data.get("status") == "ok":+ result = data.get("result", {})+ root_uri = result.get("root_uri", "")+ assert "sessions" not in root_uri, (+ f"非resources scope不应成功写入sessions, root_uri: {root_uri}"+ )+ print("✓ TC-E11 非resources scope处理通过(服务端重定向)")+ return+ finally:+ cleanup_temp_dir(temp_dir)diff --git a/tests/api_test/scenarios/resources_retrieval_slow/build_test_helpers.py b/tests/api_test/scenarios/resources_retrieval_slow/build_test_helpers.pynew file mode 100644index 000000000..9961708e0--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval_slow/build_test_helpers.py@@ -0,0 +1,270 @@+import os+import shutil+import tempfile+import uuid+++def create_test_file(content=None, suffix=".txt", filename=None):+ if content is None:+ content = (+ f"测试文件内容 - {uuid.uuid4()}\n这是一个用于构建测试的临时文件。\n包含一些测试数据。"+ )++ temp_dir = tempfile.mkdtemp()+ fname = filename or f"test_file_{str(uuid.uuid4())[:8]}{suffix}"+ test_file_path = os.path.join(temp_dir, fname)++ with open(test_file_path, "w", encoding="utf-8") as f:+ f.write(content)++ return test_file_path, temp_dir+++def create_test_directory(file_count=3, nested=True):+ temp_dir = tempfile.mkdtemp()++ for i in range(file_count):+ file_path = os.path.join(temp_dir, f"file_{i}.txt")+ with open(file_path, "w", encoding="utf-8") as f:+ f.write(f"测试文件 {i} 的内容\n一些测试数据 {uuid.uuid4()}")++ if nested:+ subdir = os.path.join(temp_dir, "subdir")+ os.makedirs(subdir)+ with open(os.path.join(subdir, "nested_file.txt"), "w", encoding="utf-8") as f:+ f.write("嵌套文件的内容")++ return temp_dir+++def create_test_zip(file_count=3):+ import zipfile++ temp_dir = tempfile.mkdtemp()+ zip_path = os.path.join(temp_dir, f"test_archive_{str(uuid.uuid4())[:8]}.zip")++ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:+ for i in range(file_count):+ content = f"压缩包内文件 {i} 的内容\n测试数据 {uuid.uuid4()}"+ zf.writestr(f"file_{i}.txt", content)+ zf.writestr("subdir/nested_file.txt", "压缩包内嵌套文件的内容")++ return zip_path, temp_dir+++def cleanup_temp_dir(temp_dir):+ if temp_dir and os.path.exists(temp_dir):+ shutil.rmtree(temp_dir, ignore_errors=True)+++def assert_root_uri_valid(root_uri):+ assert root_uri, "add_resource 必须返回 root_uri"+ assert root_uri.startswith("viking://resources/"), (+ f"root_uri 应以 viking://resources/ 开头, 实际: {root_uri}"+ )+++def assert_resource_findable(api_client, root_uri, keyword, timeout=90, poll_interval=3):+ import time++ api_client.wait_processed()++ start = time.time()+ poll_count = 0+ while time.time() - start < timeout:+ poll_count += 1++ if poll_count % 3 == 0:+ api_client.wait_processed()++ find_resp = api_client.find(keyword, target_uri=root_uri)+ if find_resp.status_code == 200:+ find_data = find_resp.json()+ if find_data.get("status") == "ok":+ search_result = find_data.get("result", {})+ for field in ["resources", "memories", "matches"]:+ items = search_result.get(field, [])+ if not isinstance(items, list):+ continue+ for item in items:+ if isinstance(item, dict) and "uri" in item and root_uri in item["uri"]:+ return True+ elif isinstance(item, str) and root_uri in item:+ return True++ if time.time() - start >= timeout:+ break+ time.sleep(poll_interval)++ return False+++def assert_resource_indexed(api_client, root_uri, keyword, timeout=120):+ found = assert_resource_findable(api_client, root_uri, keyword, timeout=timeout)+ assert found, f"搜索应能检索到资源 {root_uri}, 关键词: {keyword}"+ return found+++def _extract_error_message(data):+ if not isinstance(data, dict):+ return str(data)+ error = data.get("error")+ if isinstance(error, dict):+ return error.get("message", "") + " " + error.get("code", "")+ errors = data.get("errors", [])+ if isinstance(errors, list):+ return " ".join(str(e) for e in errors)+ return str(data.get("message", data.get("msg", "")))+++def assert_source_format(api_client, root_uri, expected_format):+ if isinstance(expected_format, str):+ expected_format = [expected_format]++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200, f"fs_stat 应返回200, root_uri: {root_uri}"+ stat_data = stat_resp.json()+ stat_result = stat_data.get("result")++ if isinstance(stat_result, dict):+ actual_format = stat_result.get("source_format")+ if actual_format:+ assert actual_format in expected_format, (+ f"source_format 应为 {expected_format}, 实际: {actual_format}"+ )+ return++ tree_resp = api_client.fs_tree(root_uri)+ if tree_resp.status_code == 200:+ tree_data = tree_resp.json()+ tree_result = tree_data.get("result")+ if isinstance(tree_result, dict):+ actual_format = tree_result.get("source_format")+ if actual_format:+ assert actual_format in expected_format, (+ f"source_format 应为 {expected_format}, 实际: {actual_format}"+ )+ return+ children = tree_result.get("children", [])+ elif isinstance(tree_result, list):+ children = tree_result+ else:+ children = []++ for child in children:+ if isinstance(child, dict):+ actual_format = child.get("source_format")+ if actual_format:+ assert actual_format in expected_format, (+ f"source_format 应为 {expected_format}, 实际: {actual_format}"+ )+ return++ ls_resp = api_client.fs_ls(root_uri, recursive=True)+ if ls_resp.status_code == 200:+ ls_data = ls_resp.json()+ ls_result = ls_data.get("result")+ items = ls_result if isinstance(ls_result, list) else []+ for item in items:+ if isinstance(item, dict):+ actual_format = item.get("source_format")+ if actual_format:+ assert actual_format in expected_format, (+ f"source_format 应为 {expected_format}, 实际: {actual_format}"+ )+ return++ ext_format_map = {+ ".txt": ["text", "markdown"],+ ".text": ["text"],+ ".md": ["markdown"],+ ".markdown": ["markdown"],+ ".pdf": ["pdf"],+ ".html": ["html"],+ ".htm": ["html"],+ ".docx": ["docx"],+ ".doc": ["doc"],+ ".pptx": ["pptx"],+ ".xlsx": ["xlsx"],+ ".epub": ["epub"],+ ".zip": ["zip"],+ ".png": ["image"],+ ".jpg": ["image"],+ ".jpeg": ["image"],+ ".mp3": ["audio"],+ ".wav": ["audio"],+ ".mp4": ["video"],+ }+ if ls_resp.status_code == 200:+ ls_data = ls_resp.json()+ ls_result = ls_data.get("result")+ items = ls_result if isinstance(ls_result, list) else []+ for item in items:+ if isinstance(item, dict):+ rel_path = item.get("rel_path", "")+ uri = item.get("uri", "")+ for ext, fmt_list in ext_format_map.items():+ if rel_path.endswith(ext) or uri.endswith(ext):+ assert any(f in expected_format for f in fmt_list), (+ f"根据扩展名 {ext} 推断 source_format 应为 {fmt_list}, 期望: {expected_format}"+ )+ return+++def assert_tree_has_child_nodes(api_client, root_uri, min_nodes=1):+ tree_resp = api_client.fs_tree(root_uri)+ assert tree_resp.status_code == 200, f"fs_tree 应返回200, root_uri: {root_uri}"+ tree_data = tree_resp.json()+ tree_result = tree_data.get("result")++ if isinstance(tree_result, list):+ children = tree_result+ elif isinstance(tree_result, dict):+ children = tree_result.get("children", [])+ else:+ children = []++ assert len(children) >= min_nodes, (+ f"tree 应至少包含 {min_nodes} 个子节点, 实际: {len(children)}"+ )+++def assert_content_no_html_tags(api_client, root_uri):+ grep_resp = api_client.grep(root_uri, pattern="<[a-z][a-z0-9]*[^>]*>")+ if grep_resp.status_code != 200:+ return+ grep_data = grep_resp.json()+ grep_result = grep_data.get("result", {})+ matches = grep_result.get("matches", [])+ html_matches = [m for m in matches if isinstance(m, dict) and "<" in str(m.get("line", ""))]+ assert len(html_matches) == 0, (+ f"HTML内容应被剥离, 但仍包含HTML标签: {[m.get('line', '')[:80] for m in html_matches[:3]]}"+ )+++def assert_overview_or_abstract_contains(+ api_client, root_uri, keyword, timeout=60, poll_interval=3+):+ import time++ start = time.time()+ while time.time() - start < timeout:+ overview_resp = api_client.get_overview(root_uri)+ if overview_resp.status_code == 200:+ overview_data = overview_resp.json()+ overview_text = str(overview_data.get("result", ""))+ if keyword.lower() in overview_text.lower():+ return True++ abstract_resp = api_client.get_abstract(root_uri)+ if abstract_resp.status_code == 200:+ abstract_data = abstract_resp.json()+ abstract_text = str(abstract_data.get("result", ""))+ if keyword.lower() in abstract_text.lower():+ return True++ if time.time() - start >= timeout:+ break+ time.sleep(poll_interval)++ return Falsediff --git a/tests/api_test/scenarios/resources_retrieval_slow/conftest.py b/tests/api_test/scenarios/resources_retrieval_slow/conftest.pynew file mode 100644index 000000000..e669d95eb--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval_slow/conftest.py@@ -0,0 +1,4 @@+import os+import sys++sys.path.insert(0, os.path.dirname(__file__))diff --git a/tests/api_test/scenarios/resources_retrieval_slow/test_build_archive_resources.py b/tests/api_test/scenarios/resources_retrieval_slow/test_build_archive_resources.pynew file mode 100644index 000000000..965631e17--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval_slow/test_build_archive_resources.py@@ -0,0 +1,112 @@+import os+import shutil+import tempfile+import uuid+import zipfile++from build_test_helpers import assert_resource_indexed, assert_root_uri_valid, assert_source_format+++class TestBuildArchiveResources:+ """TC-B10~B12 压缩包与目录类资源构建测试"""++ def test_build_zip_file(self, api_client):+ """TC-B10 ZIP压缩包构建:验证 .zip 文件添加后解压并按目录结构处理"""+ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"zip_keyword_{random_id}"+ temp_dir = tempfile.mkdtemp()+ zip_path = os.path.join(temp_dir, f"test_{random_id}.zip")++ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:+ zf.writestr("file_0.txt", f"压缩包内文件0\n包含唯一关键词:{unique_keyword}")+ zf.writestr("file_1.txt", f"压缩包内文件1\n测试数据 {random_id}")+ zf.writestr("subdir/nested.txt", "嵌套文件内容")++ try:+ response = api_client.add_resource(path=zip_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, ["zip", "markdown"])++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B10 ZIP压缩包构建通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_directory(self, api_client):+ """TC-B11 目录递归构建:验证目录添加后子文件全部被索引"""+ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"dir_keyword_{random_id}"+ temp_dir = tempfile.mkdtemp()++ for i in range(3):+ file_path = os.path.join(temp_dir, f"file_{i}.txt")+ with open(file_path, "w", encoding="utf-8") as f:+ f.write(f"目录内文件 {i}\n测试数据 {random_id}")++ subdir = os.path.join(temp_dir, "subdir")+ os.makedirs(subdir)+ with open(os.path.join(subdir, "nested_file.txt"), "w", encoding="utf-8") as f:+ f.write(f"嵌套文件内容\n包含唯一关键词:{unique_keyword}")++ try:+ response = api_client.add_resource(path=temp_dir, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, ["directory", "markdown"])++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B11 目录递归构建通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_code_repository_url(self, api_client):+ """TC-B12 代码仓库URL构建:验证 GitHub 仓库 URL 添加后 source_format=repository 且 URI 含 org/repo"""+ repo_url = "https://github.com/volcengine/OpenViking"++ response = api_client.add_resource(path=repo_url, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)+ assert "volcengine" in root_uri and "OpenViking" in root_uri, (+ f"代码仓库 root_uri 应含 org/repo, 实际: {root_uri}"+ )++ meta = result.get("meta", {})+ assert meta.get("url_type") in ("code_repository", None), (+ f"meta.url_type 应为 code_repository, 实际: {meta.get('url_type')}"+ )++ assert_source_format(api_client, root_uri, ["repository", "markdown"])++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ print(f"✓ TC-B12 代码仓库URL构建通过, root_uri: {root_uri}")diff --git a/tests/api_test/scenarios/resources_retrieval_slow/test_build_document_resources_slow.py b/tests/api_test/scenarios/resources_retrieval_slow/test_build_document_resources_slow.pynew file mode 100644index 000000000..db47459a1--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval_slow/test_build_document_resources_slow.py@@ -0,0 +1,332 @@+import os+import shutil+import tempfile+import uuid++import pytest+from build_test_helpers import (+ assert_resource_indexed,+ assert_root_uri_valid,+ assert_source_format,+)+++def _create_pdf_file():+ try:+ from fpdf import FPDF+ except ImportError:+ pytest.skip("fpdf 未安装,跳过 PDF 构建测试")++ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"pdf_keyword_{random_id}"+ temp_dir = tempfile.mkdtemp()+ pdf_path = os.path.join(temp_dir, f"test_{random_id}.pdf")++ pdf = FPDF()+ pdf.add_page()+ pdf.set_font("Helvetica", size=12)+ pdf.cell(200, 10, text=f"PDF Test Document {random_id}", new_x="LMARGIN", new_y="NEXT")+ pdf.cell(200, 10, text=f"Unique keyword: {unique_keyword}", new_x="LMARGIN", new_y="NEXT")+ pdf.cell(+ 200, 10, text="This is a test PDF file for build validation.", new_x="LMARGIN", new_y="NEXT"+ )+ pdf.output(pdf_path)++ return pdf_path, temp_dir, unique_keyword+++def _create_docx_file():+ try:+ from docx import Document+ except ImportError:+ pytest.skip("python-docx 未安装,跳过 DOCX 构建测试")++ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"docx_keyword_{random_id}"+ temp_dir = tempfile.mkdtemp()+ docx_path = os.path.join(temp_dir, f"test_{random_id}.docx")++ doc = Document()+ doc.add_heading(f"Word测试标题 {random_id}", level=1)+ doc.add_paragraph(f"包含唯一关键词:{unique_keyword}")+ doc.add_paragraph("用于验证Word文档构建产物。")+ doc.save(docx_path)++ return docx_path, temp_dir, unique_keyword+++def _create_xlsx_file():+ try:+ from openpyxl import Workbook+ except ImportError:+ pytest.skip("openpyxl 未安装,跳过 XLSX 构建测试")++ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"xlsx_keyword_{random_id}"+ temp_dir = tempfile.mkdtemp()+ xlsx_path = os.path.join(temp_dir, f"test_{random_id}.xlsx")++ wb = Workbook()+ ws = wb.active+ ws.title = "TestSheet"+ ws.append(["Column A", "Column B", "Column C"])+ ws.append([f"数据1 {random_id}", unique_keyword, "数据3"])+ ws.append(["数据4", "数据5", "数据6"])+ wb.save(xlsx_path)++ return xlsx_path, temp_dir, unique_keyword+++class TestBuildDocumentResourcesSlow:+ """TC-B03~B09 文档类资源构建测试"""++ def test_build_pdf_file(self, api_client):+ """TC-B03 PDF文件构建:验证 .pdf 文件添加后 source_format=pdf 且内容可检索"""+ pdf_path, temp_dir, unique_keyword = _create_pdf_file()+ try:+ response = api_client.add_resource(path=pdf_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, ["pdf", "markdown"])++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B03 PDF文件构建通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_docx_file(self, api_client):+ """TC-B05 Word文档构建:验证 .docx 文件添加后 source_format=docx 且内容可检索"""+ docx_path, temp_dir, unique_keyword = _create_docx_file()+ try:+ response = api_client.add_resource(path=docx_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, ["docx", "markdown"])++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B05 Word文档构建通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_xlsx_file(self, api_client):+ """TC-B08 Excel构建:验证 .xlsx 文件添加后 source_format=xlsx 且表格数据可检索"""+ xlsx_path, temp_dir, unique_keyword = _create_xlsx_file()+ try:+ response = api_client.add_resource(path=xlsx_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, ["xlsx", "markdown"])++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B08 Excel构建通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_html_file(self, api_client):+ """TC-B04 HTML文件构建:验证 .html 文件添加后 source_format=html 且标签被剥离"""+ from build_test_helpers import assert_content_no_html_tags++ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"html_keyword_{random_id}"+ temp_dir = tempfile.mkdtemp()+ html_path = os.path.join(temp_dir, f"test_{random_id}.html")++ content = (+ f"<html><head><title>HTML Test {random_id}</title></head>"+ f"<body><h1>HTML测试标题 {random_id}</h1>"+ f"<p>包含唯一关键词:{unique_keyword}</p>"+ f"<p>用于验证HTML文件构建产物。</p>"+ f"</body></html>"+ )+ with open(html_path, "w", encoding="utf-8") as f:+ f.write(content)++ try:+ response = api_client.add_resource(path=html_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, ["html", "markdown"])++ assert_content_no_html_tags(api_client, root_uri)++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B04 HTML文件构建通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_legacy_doc_file(self, api_client):+ """TC-B06 旧版Word(.doc)构建:验证 .doc 文件添加后 source_format=doc 且内容可检索"""+ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"doc_keyword_{random_id}"+ temp_dir = tempfile.mkdtemp()+ doc_path = os.path.join(temp_dir, f"test_{random_id}.doc")++ try:+ from docx import Document++ doc = Document()+ doc.add_heading(f"旧版Word测试标题 {random_id}", level=1)+ doc.add_paragraph(f"包含唯一关键词:{unique_keyword}")+ doc.save(doc_path)+ except ImportError:+ pytest.skip("python-docx 未安装,跳过旧版Word构建测试")++ try:+ response = api_client.add_resource(path=doc_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, ["doc", "docx", "markdown"])++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B06 旧版Word(.doc)构建通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_pptx_file(self, api_client):+ """TC-B07 PowerPoint构建:验证 .pptx 文件添加后 source_format=pptx 且内容可检索"""+ try:+ from pptx import Presentation+ except ImportError:+ pytest.skip("python-pptx 未安装,跳过 PPTX 构建测试")++ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"pptx_keyword_{random_id}"+ temp_dir = tempfile.mkdtemp()+ pptx_path = os.path.join(temp_dir, f"test_{random_id}.pptx")++ prs = Presentation()+ slide = prs.slides.add_slide(prs.slide_layouts[1])+ title = slide.shapes.title+ title.text = f"PPT测试标题 {random_id}"+ body = slide.placeholders[1]+ body.text = f"包含唯一关键词:{unique_keyword}\n用于验证PPT文件构建产物。"+ prs.save(pptx_path)++ try:+ response = api_client.add_resource(path=pptx_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, ["pptx", "markdown"])++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B07 PowerPoint构建通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_epub_file(self, api_client):+ """TC-B09 EPUB构建:验证 .epub 文件添加后 source_format=epub 且内容可检索"""+ try:+ from ebooklib import epub+ except ImportError:+ pytest.skip("ebooklib 未安装,跳过 EPUB 构建测试")++ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"epub_keyword_{random_id}"+ temp_dir = tempfile.mkdtemp()+ epub_path = os.path.join(temp_dir, f"test_{random_id}.epub")++ book = epub.EpubBook()+ book.set_identifier(f"test-epub-{random_id}")+ book.set_title(f"EPUB测试 {random_id}")+ book.set_language("zh")++ chapter = epub.EpubHtml(title="Chapter 1", file_name="chap_01.xhtml", lang="zh")+ chapter.content = (+ f"<html><body><h1>EPUB测试章节 {random_id}</h1>"+ f"<p>包含唯一关键词:{unique_keyword}</p>"+ f"<p>用于验证EPUB文件构建产物。</p>"+ f"</body></html>"+ )+ book.add_item(chapter)+ book.toc = (chapter,)+ book.add_item(epub.EpubNcx())+ book.add_item(epub.EpubNav())+ epub.write_epub(epub_path, book, {})++ try:+ response = api_client.add_resource(path=epub_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, ["epub", "markdown"])++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B09 EPUB构建通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)diff --git a/tests/api_test/scenarios/resources_retrieval_slow/test_build_error_handling_slow.py b/tests/api_test/scenarios/resources_retrieval_slow/test_build_error_handling_slow.pynew file mode 100644index 000000000..257ca7b0f--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval_slow/test_build_error_handling_slow.py@@ -0,0 +1,429 @@+import os+import shutil+import tempfile+import uuid++from build_test_helpers import (+ _extract_error_message,+ assert_resource_indexed,+ assert_root_uri_valid,+ assert_source_format,+ cleanup_temp_dir,+ create_test_file,+)+++class TestBuildErrorHandlingSlow:+ """TC-E01~E16 异常与边界测试"""++ def test_error_remote_404(self, api_client):+ """TC-E01 远端404不存在:验证 404 URL 返回错误含状态码信息且不崩溃"""+ url_404 = "https://httpbin.org/status/404"++ response = api_client.add_resource(path=url_404, wait=True)++ data = response.json()+ if data.get("status") == "error":+ error_msg = _extract_error_message(data).lower()+ assert "404" in error_msg or "not found" in error_msg or "error" in error_msg, (+ f"404错误信息应包含 404/not found/error, 实际: {error_msg}"+ )+ print("✓ TC-E01 远端404不存在处理通过(返回error)")+ return++ if data.get("status") == "ok":+ result = data.get("result", {})+ if isinstance(result, dict) and result.get("status") == "error":+ inner_errors = result.get("errors", [])+ inner_msg = " ".join(str(e) for e in inner_errors).lower()+ assert (+ "404" in inner_msg+ or "not found" in inner_msg+ or "failed" in inner_msg+ or "error" in inner_msg+ ), f"404内层错误应包含 404/not found/failed/error, 实际: {inner_msg}"+ print(f"✓ TC-E01 远端404不存在处理通过(内层错误): {inner_msg[:80]}")+ return++ root_uri = result.get("root_uri")+ if root_uri:+ assert_root_uri_valid(root_uri)+ print("✓ TC-E01 远端404处理通过(降级为空资源)")+ return++ raise AssertionError(f"404 URL 应返回 error 或 ok, 实际: {data.get('status')}")++ def test_error_http_to_https_redirect(self, api_client):+ """TC-E05 HTTP→HTTPS跳转:验证 http URL 自动跟随跳转且 root_uri 正常"""+ redirect_url = "http://github.com/volcengine/OpenViking"++ response = api_client.add_resource(path=redirect_url, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)+ assert "volcengine" in root_uri and "OpenViking" in root_uri, (+ f"跳转后 root_uri 应含 volcengine/OpenViking, 实际: {root_uri}"+ )++ print(f"✓ TC-E05 HTTP→HTTPS跳转通过, root_uri: {root_uri}")++ def test_error_multi_redirect(self, api_client):+ """TC-E06 多重跳转:验证短链 URL 自动跟随跳转且内容可检索"""+ redirect_url = (+ "https://httpbin.org/redirect-to?url=https://httpbin.org/html&status_code=302"+ )++ response = api_client.add_resource(path=redirect_url, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ assert_resource_indexed(api_client, root_uri, "httpbin")++ print(f"✓ TC-E06 多重跳转通过, root_uri: {root_uri}")++ def test_error_duplicate_resource_no_to(self, api_client):+ """TC-E12 同名资源二次添加(无to):验证两次添加的 root_uri 不同(URI 附加后缀)"""+ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"dup_keyword_{random_id}"+ content = f"重复添加测试 {random_id}\n包含唯一关键词:{unique_keyword}"++ test_file_path, temp_dir = create_test_file(content=content, suffix=".txt")+ try:+ resp1 = api_client.add_resource(path=test_file_path, wait=True)+ assert resp1.status_code == 200+ data1 = resp1.json()+ assert data1.get("status") == "ok"+ root_uri_1 = data1.get("result", {}).get("root_uri")+ assert_root_uri_valid(root_uri_1)++ resp2 = api_client.add_resource(path=test_file_path, wait=True)+ assert resp2.status_code == 200+ data2 = resp2.json()+ assert data2.get("status") == "ok"+ root_uri_2 = data2.get("result", {}).get("root_uri")+ assert_root_uri_valid(root_uri_2)++ assert root_uri_1 != root_uri_2, (+ f"同名资源二次添加(无to) root_uri 应不同, uri1: {root_uri_1}, uri2: {root_uri_2}"+ )++ print(f"✓ TC-E12 同名资源二次添加通过, uri1: {root_uri_1}, uri2: {root_uri_2}")+ finally:+ cleanup_temp_dir(temp_dir)++ def test_error_incremental_update_with_to(self, api_client):+ """TC-E13 同to增量更新:验证同一 to 二次添加后 root_uri 不变且不报错"""+ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"incr_keyword_{random_id}"+ target_uri = f"viking://resources/incr_test_{random_id}"++ content1 = f"增量更新测试1 {random_id}\n包含唯一关键词:{unique_keyword}_v1"+ content2 = f"增量更新测试2 {random_id}\n包含唯一关键词:{unique_keyword}_v2"++ file1, temp_dir1 = create_test_file(content=content1, suffix=".txt")+ file2, temp_dir2 = create_test_file(content=content2, suffix=".txt")+ try:+ resp1 = api_client.add_resource(path=file1, to=target_uri, wait=True)+ assert resp1.status_code == 200+ data1 = resp1.json()+ assert data1.get("status") == "ok"+ root_uri_1 = data1.get("result", {}).get("root_uri")++ resp2 = api_client.add_resource(path=file2, to=target_uri, wait=True)+ assert resp2.status_code == 200+ data2 = resp2.json()+ assert data2.get("status") == "ok"+ root_uri_2 = data2.get("result", {}).get("root_uri")++ assert root_uri_1 == root_uri_2, (+ f"同to增量更新 root_uri 应不变, uri1: {root_uri_1}, uri2: {root_uri_2}"+ )++ print(f"✓ TC-E13 同to增量更新通过, root_uri: {root_uri_1}")+ finally:+ cleanup_temp_dir(temp_dir1)+ cleanup_temp_dir(temp_dir2)++ def test_error_unsupported_file_type(self, api_client):+ """TC-E15 不支持的文件类型:验证 .xyz 文件回退到 TextParser 且 source_format=text、内容可检索"""+ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"xyz_keyword_{random_id}"++ temp_dir = tempfile.mkdtemp()+ file_path = os.path.join(temp_dir, f"test_{random_id}.xyz")+ with open(file_path, "w", encoding="utf-8") as f:+ f.write(f"不支持的文件类型测试 {random_id}\n包含唯一关键词:{unique_keyword}")++ try:+ response = api_client.add_resource(path=file_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ if data.get("status") == "error":+ error_msg = _extract_error_message(data).lower()+ assert "unsupported" in error_msg or "error" in error_msg or "type" in error_msg, (+ f"不支持文件类型错误应包含 unsupported/error/type, 实际: {error_msg}"+ )+ print(f"✓ TC-E15 不支持的文件类型处理通过(服务端拒绝): {error_msg[:80]}")+ return++ assert data.get("status") == "ok"++ result = data.get("result", {})+ if isinstance(result, dict) and result.get("status") == "error":+ inner_errors = result.get("errors", [])+ inner_msg = " ".join(str(e) for e in inner_errors)+ assert (+ "unsupported" in inner_msg.lower()+ or "error" in inner_msg.lower()+ or "parse" in inner_msg.lower()+ ), f"不支持文件类型内层错误应包含 unsupported/error/parse, 实际: {inner_msg}"+ print(f"✓ TC-E15 不支持的文件类型处理通过(内层错误): {inner_msg[:80]}")+ return++ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200, (+ f"不支持文件类型 fs_stat 应返回200, root_uri: {root_uri}"+ )++ assert_source_format(api_client, root_uri, ["text", "markdown"])++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-E15 不支持的文件类型处理通过(回退TextParser), root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_error_remote_403(self, api_client):+ """TC-E02 远端403禁止访问:验证 403 URL 返回错误含状态码信息且不崩溃"""+ url_403 = "https://httpbin.org/status/403"++ response = api_client.add_resource(path=url_403, wait=True)++ data = response.json()+ if data.get("status") == "error":+ error_msg = _extract_error_message(data).lower()+ assert "403" in error_msg or "forbidden" in error_msg or "error" in error_msg, (+ f"403错误信息应包含 403/forbidden/error, 实际: {error_msg}"+ )+ print("✓ TC-E02 远端403禁止访问处理通过(返回error)")+ return++ if data.get("status") == "ok":+ result = data.get("result", {})+ if isinstance(result, dict) and result.get("status") == "error":+ inner_errors = result.get("errors", [])+ inner_msg = " ".join(str(e) for e in inner_errors).lower()+ assert (+ "403" in inner_msg+ or "forbidden" in inner_msg+ or "failed" in inner_msg+ or "error" in inner_msg+ ), f"403内层错误应包含 403/forbidden/failed/error, 实际: {inner_msg}"+ print(f"✓ TC-E02 远端403禁止访问处理通过(内层错误): {inner_msg[:80]}")+ return++ root_uri = result.get("root_uri")+ if root_uri:+ assert_root_uri_valid(root_uri)+ print("✓ TC-E02 远端403处理通过(降级为空资源)")+ return++ raise AssertionError(f"403 URL 应返回 error 或 ok, 实际: {data.get('status')}")++ def test_error_remote_500(self, api_client):+ """TC-E03 远端500服务错误:验证 500 URL 返回错误含状态码信息且不崩溃"""+ url_500 = "https://httpbin.org/status/500"++ response = api_client.add_resource(path=url_500, wait=True)++ data = response.json()+ if data.get("status") == "error":+ error_msg = _extract_error_message(data).lower()+ assert "500" in error_msg or "server" in error_msg or "error" in error_msg, (+ f"500错误信息应包含 500/server/error, 实际: {error_msg}"+ )+ print("✓ TC-E03 远端500服务错误处理通过(返回error)")+ return++ if data.get("status") == "ok":+ result = data.get("result", {})+ if isinstance(result, dict) and result.get("status") == "error":+ inner_errors = result.get("errors", [])+ inner_msg = " ".join(str(e) for e in inner_errors).lower()+ assert (+ "500" in inner_msg+ or "server" in inner_msg+ or "internal" in inner_msg+ or "failed" in inner_msg+ or "error" in inner_msg+ ), f"500内层错误应包含 500/server/internal/failed/error, 实际: {inner_msg}"+ print(f"✓ TC-E03 远端500服务错误处理通过(内层错误): {inner_msg[:80]}")+ return++ root_uri = result.get("root_uri")+ if root_uri:+ assert_root_uri_valid(root_uri)+ print("✓ TC-E03 远端500处理通过(降级为空资源)")+ return++ raise AssertionError(f"500 URL 应返回 error 或 ok, 实际: {data.get('status')}")++ def test_error_dns_resolve_failure(self, api_client):+ """TC-E08 DNS解析失败:验证不存在的域名返回错误含DNS相关信息且不挂起"""+ bad_dns_url = "https://nonexistent.domain.invalid.for.test/page"++ response = api_client.add_resource(path=bad_dns_url, wait=True)++ data = response.json()+ if data.get("status") == "error":+ error_msg = _extract_error_message(data).lower()+ assert (+ "resolve" in error_msg+ or "hostname" in error_msg+ or "dns" in error_msg+ or "error" in error_msg+ or "connect" in error_msg+ ), f"DNS失败错误信息应包含 resolve/hostname/dns/error/connect, 实际: {error_msg}"+ print("✓ TC-E08 DNS解析失败处理通过(返回error)")+ return++ if data.get("status") == "ok":+ result = data.get("result", {})+ if isinstance(result, dict) and result.get("status") == "error":+ inner_errors = result.get("errors", [])+ inner_msg = " ".join(str(e) for e in inner_errors).lower()+ assert (+ "resolve" in inner_msg+ or "hostname" in inner_msg+ or "dns" in inner_msg+ or "connect" in inner_msg+ or "failed" in inner_msg+ or "error" in inner_msg+ ), f"DNS内层错误应包含 resolve/hostname/dns/connect/failed/error, 实际: {inner_msg}"+ print(f"✓ TC-E08 DNS解析失败处理通过(内层错误): {inner_msg[:80]}")+ return++ root_uri = result.get("root_uri")+ if root_uri:+ assert_root_uri_valid(root_uri)+ print("✓ TC-E08 DNS解析失败处理通过(降级为空资源)")+ return++ raise AssertionError(f"DNS失败 URL 应返回 error 或 ok, 实际: {data.get('status')}")++ def test_error_ssh_url_invalid_format(self, api_client):+ """TC-E09 SSH URL格式错误:验证 git@invalid (无冒号) 返回错误含SSH/URI相关信息"""+ invalid_ssh_url = "git@invalid"++ response = api_client.add_resource(path=invalid_ssh_url, wait=True)++ data = response.json()+ if data.get("status") == "error":+ error_msg = _extract_error_message(data).lower()+ assert (+ "invalid" in error_msg+ or "ssh" in error_msg+ or "uri" in error_msg+ or "colon" in error_msg+ or "error" in error_msg+ or "permission" in error_msg+ ), f"SSH格式错误应包含 invalid/ssh/uri/colon/error/permission, 实际: {error_msg}"+ print("✓ TC-E09 SSH URL格式错误处理通过(返回error)")+ return++ if data.get("status") == "ok":+ result = data.get("result", {})+ if isinstance(result, dict) and result.get("status") == "error":+ inner_errors = result.get("errors", [])+ inner_msg = " ".join(str(e) for e in inner_errors).lower()+ assert (+ "invalid" in inner_msg+ or "ssh" in inner_msg+ or "uri" in inner_msg+ or "failed" in inner_msg+ or "error" in inner_msg+ ), f"SSH内层错误应包含 invalid/ssh/uri/failed/error, 实际: {inner_msg}"+ print(f"✓ TC-E09 SSH URL格式错误处理通过(内层错误): {inner_msg[:80]}")+ return++ print("✓ TC-E09 SSH URL格式错误处理通过(服务端降级)")+ return++ raise AssertionError(f"SSH URL格式错误应返回 error 或降级, 实际: {data.get('status')}")++ def test_error_corrupted_zip(self, api_client):+ """TC-E16 损坏的ZIP文件:验证伪造 .zip 文件报错含 zip/corrupt 或回退处理,不产生有效子节点"""+ random_id = str(uuid.uuid4())[:8]++ temp_dir = tempfile.mkdtemp()+ zip_path = os.path.join(temp_dir, f"corrupted_{random_id}.zip")+ with open(zip_path, "w", encoding="utf-8") as f:+ f.write("这不是一个真正的ZIP文件内容")++ try:+ response = api_client.add_resource(path=zip_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ if data.get("status") == "error":+ error_msg = _extract_error_message(data).lower()+ assert (+ "zip" in error_msg+ or "corrupt" in error_msg+ or "error" in error_msg+ or "archive" in error_msg+ ), f"损坏ZIP错误信息应包含 zip/corrupt/error/archive, 实际: {error_msg}"+ print(f"✓ TC-E16 损坏的ZIP文件处理通过(返回error): {error_msg[:80]}")+ return++ assert data.get("status") == "ok"++ result = data.get("result", {})+ if isinstance(result, dict) and result.get("status") == "error":+ inner_errors = result.get("errors", [])+ inner_msg = " ".join(str(e) for e in inner_errors)+ assert (+ "zip" in inner_msg.lower()+ or "corrupt" in inner_msg.lower()+ or "error" in inner_msg.lower()+ or "bad" in inner_msg.lower()+ ), f"损坏ZIP内层错误应包含 zip/corrupt/error/bad, 实际: {inner_msg}"+ print(f"✓ TC-E16 损坏的ZIP文件处理通过(内层错误): {inner_msg[:80]}")+ return++ root_uri = result.get("root_uri")+ if root_uri:+ assert_root_uri_valid(root_uri)++ tree_resp = api_client.fs_tree(root_uri)+ if tree_resp.status_code == 200:+ tree_data = tree_resp.json()+ tree_result = tree_data.get("result")+ if isinstance(tree_result, list):+ children = tree_result+ elif isinstance(tree_result, dict):+ children = tree_result.get("children", [])+ else:+ children = []+ assert len(children) == 0, (+ f"损坏ZIP不应产生有效子节点, 实际子节点数: {len(children)}"+ )++ print(f"✓ TC-E16 损坏的ZIP文件处理通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)diff --git a/tests/api_test/scenarios/resources_retrieval_slow/test_build_media_resources_slow.py b/tests/api_test/scenarios/resources_retrieval_slow/test_build_media_resources_slow.pynew file mode 100644index 000000000..be29452c4--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval_slow/test_build_media_resources_slow.py@@ -0,0 +1,322 @@+import os+import shutil+import tempfile+import uuid++import pytest+from build_test_helpers import (+ assert_resource_indexed,+ assert_root_uri_valid,+ assert_source_format,+)+++class TestBuildMediaResourcesSlow:+ """TC-B13~B15 媒体类资源构建测试"""++ def test_build_image_svg(self, api_client):+ """TC-B13 图片构建(SVG):验证 .svg 文件解析失败时错误信息合理,成功时 source_format=image 且可检索"""+ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"svg_keyword_{random_id}"+ temp_dir = tempfile.mkdtemp()+ svg_path = os.path.join(temp_dir, f"test_{random_id}.svg")++ svg_content = f'<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><rect width="100" height="100" fill="blue"/><text x="10" y="50">SVG test {unique_keyword}</text></svg>'+ with open(svg_path, "w", encoding="utf-8") as f:+ f.write(svg_content)++ try:+ response = api_client.add_resource(path=svg_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") in ("ok", "error"), (+ f"SVG文件应返回 ok 或 error, 实际: {data.get('status')}"+ )++ if data.get("status") == "error":+ error_msg = str(data.get("error", "")).lower()+ assert (+ "image" in error_msg+ or "svg" in error_msg+ or "parse" in error_msg+ or "error" in error_msg+ ), f"SVG外层错误应包含 image/svg/parse/error, 实际: {error_msg}"+ print("✓ TC-B13 图片构建(SVG)通过(服务端返回error,SVG格式不被支持)")+ return++ result = data.get("result", {})+ if isinstance(result, dict) and result.get("status") == "error":+ inner_errors = result.get("errors", [])+ inner_msg = " ".join(str(e) for e in inner_errors)+ assert (+ "image" in inner_msg.lower()+ or "parse" in inner_msg.lower()+ or "identify" in inner_msg.lower()+ or "svg" in inner_msg.lower()+ ), f"SVG解析错误信息应包含 image/parse/identify/svg, 实际: {inner_msg}"+ print(+ f"✓ TC-B13 图片构建(SVG)通过(服务端内层解析错误,SVG格式不被支持): {inner_msg[:80]}"+ )+ return++ root_uri = result.get("root_uri") if isinstance(result, dict) else None+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, ["image", "html", "markdown"])++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B13 图片构建(SVG)通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_audio_mp3(self, api_client):+ """TC-B14 音频构建(MP3):验证 .mp3 文件添加后产物路径含 /audio/ 且 source_format=audio"""+ import subprocess+ import uuid++ random_id = str(uuid.uuid4())[:8]+ temp_dir = tempfile.mkdtemp()+ mp3_path = os.path.join(temp_dir, f"test_{random_id}.mp3")++ try:+ result = subprocess.run(+ [+ "ffmpeg",+ "-f",+ "lavfi",+ "-i",+ "sine=frequency=440:duration=1",+ "-frames:a",+ "44100",+ "-y",+ mp3_path,+ ],+ capture_output=True,+ timeout=10,+ )+ if result.returncode != 0:+ pytest.skip("ffmpeg 不可用,跳过MP3音频构建测试")+ except (FileNotFoundError, subprocess.TimeoutExpired):+ pytest.skip("ffmpeg 不可用,跳过MP3音频构建测试")++ try:+ response = api_client.add_resource(path=mp3_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)+ assert "/audio/" in root_uri, f"音频 root_uri 应含 /audio/, 实际: {root_uri}"++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, "audio")++ print(f"✓ TC-B14 音频构建(MP3)通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_audio_wav(self, api_client):+ """TC-B14 音频构建(WAV):验证 .wav 文件添加后产物路径含 /audio/ 且 source_format=audio"""+ import subprocess++ random_id = str(uuid.uuid4())[:8]+ temp_dir = tempfile.mkdtemp()+ wav_path = os.path.join(temp_dir, f"test_{random_id}.wav")++ try:+ result = subprocess.run(+ [+ "ffmpeg",+ "-f",+ "lavfi",+ "-i",+ "sine=frequency=880:duration=1",+ "-frames:a",+ "44100",+ "-y",+ wav_path,+ ],+ capture_output=True,+ timeout=10,+ )+ if result.returncode != 0:+ pytest.skip("ffmpeg 不可用,跳过WAV音频构建测试")+ except (FileNotFoundError, subprocess.TimeoutExpired):+ pytest.skip("ffmpeg 不可用,跳过WAV音频构建测试")++ try:+ response = api_client.add_resource(path=wav_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)+ assert "/audio/" in root_uri, f"音频 root_uri 应含 /audio/, 实际: {root_uri}"++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, "audio")++ print(f"✓ TC-B14 音频构建(WAV)通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_image_jpg(self, api_client):+ """TC-B13 图片构建(JPG):验证 .jpg 文件添加后产物路径含 /images/ 且 source_format=image"""+ try:+ from PIL import Image+ except ImportError:+ pytest.skip("Pillow 未安装,跳过JPG图片构建测试")++ random_id = str(uuid.uuid4())[:8]+ temp_dir = tempfile.mkdtemp()+ img_path = os.path.join(temp_dir, f"test_{random_id}.jpg")++ img = Image.new("RGB", (100, 100), color=(73, 109, 137))+ img.save(img_path, format="JPEG")++ try:+ response = api_client.add_resource(path=img_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)+ assert "/images/" in root_uri, f"图片 root_uri 应含 /images/, 实际: {root_uri}"++ assert_source_format(api_client, root_uri, "image")++ print(f"✓ TC-B13 图片构建(JPG)通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_image_png(self, api_client):+ """TC-B13 图片构建(PNG):验证 .png 文件添加后产物路径含 /images/ 且 source_format=image"""+ try:+ from PIL import Image+ except ImportError:+ pytest.skip("Pillow 未安装,跳过PNG图片构建测试")++ random_id = str(uuid.uuid4())[:8]+ temp_dir = tempfile.mkdtemp()+ img_path = os.path.join(temp_dir, f"test_{random_id}.png")++ img = Image.new("RGBA", (100, 100), color=(73, 109, 137, 255))+ img.save(img_path, format="PNG")++ try:+ response = api_client.add_resource(path=img_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)+ assert "/images/" in root_uri, f"图片 root_uri 应含 /images/, 实际: {root_uri}"++ assert_source_format(api_client, root_uri, "image")++ print(f"✓ TC-B13 图片构建(PNG)通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_image_webp(self, api_client):+ """TC-B13 图片构建(WebP):验证 .webp 文件添加后产物路径含 /images/ 且 source_format=image"""+ try:+ from PIL import Image+ except ImportError:+ pytest.skip("Pillow 未安装,跳过WebP图片构建测试")++ random_id = str(uuid.uuid4())[:8]+ temp_dir = tempfile.mkdtemp()+ img_path = os.path.join(temp_dir, f"test_{random_id}.webp")++ img = Image.new("RGB", (100, 100), color=(73, 109, 137))+ img.save(img_path, format="WEBP")++ try:+ response = api_client.add_resource(path=img_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)+ assert "/images/" in root_uri, f"图片 root_uri 应含 /images/, 实际: {root_uri}"++ assert_source_format(api_client, root_uri, "image")++ print(f"✓ TC-B13 图片构建(WebP)通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)++ def test_build_video_mp4(self, api_client):+ """TC-B15 视频构建(MP4):验证 .mp4 文件添加后产物路径含 /video/ 且 source_format=video"""+ random_id = str(uuid.uuid4())[:8]+ temp_dir = tempfile.mkdtemp()+ mp4_path = os.path.join(temp_dir, f"test_{random_id}.mp4")++ try:+ import subprocess++ result = subprocess.run(+ [+ "ffmpeg",+ "-f",+ "lavfi",+ "-i",+ "color=c=blue:s=100x100:d=1",+ "-frames:v",+ "25",+ "-y",+ mp4_path,+ ],+ capture_output=True,+ timeout=10,+ )+ if result.returncode != 0:+ pytest.skip("ffmpeg 不可用,跳过MP4视频构建测试")+ except (FileNotFoundError, subprocess.TimeoutExpired):+ pytest.skip("ffmpeg 不可用,跳过MP4视频构建测试")++ try:+ response = api_client.add_resource(path=mp4_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)+ assert "/video/" in root_uri, f"视频 root_uri 应含 /video/, 实际: {root_uri}"++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, "video")++ print(f"✓ TC-B15 视频构建(MP4)通过, root_uri: {root_uri}")+ finally:+ shutil.rmtree(temp_dir, ignore_errors=True)diff --git a/tests/api_test/scenarios/resources_retrieval_slow/test_build_platform_arxiv.py b/tests/api_test/scenarios/resources_retrieval_slow/test_build_platform_arxiv.pynew file mode 100644index 000000000..ec0fe52a3--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval_slow/test_build_platform_arxiv.py@@ -0,0 +1,59 @@+from build_test_helpers import assert_resource_indexed, assert_root_uri_valid, assert_source_format+++class TestBuildPlatformArxiv:+ """TC-P06~P07 arXiv 平台 URL 构建测试"""++ def test_build_arxiv_pdf(self, api_client):+ """TC-P06 arXiv PDF构建:验证 arxiv.org/pdf/ URL 走 DOWNLOAD_PDF 路由且 source_format=pdf"""+ arxiv_pdf_url = "https://arxiv.org/pdf/2301.00234"++ response = api_client.add_resource(path=arxiv_pdf_url, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ meta = result.get("meta", {})+ assert meta.get("url_type") in ("download_pdf", "webpage", None), (+ f"meta.url_type 应为 download_pdf, 实际: {meta.get('url_type')}"+ )++ assert_source_format(api_client, root_uri, ["pdf", "markdown"])++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ print(f"✓ TC-P06 arXiv PDF构建通过, root_uri: {root_uri}")++ def test_build_arxiv_abstract_page(self, api_client):+ """TC-P07 arXiv HTML页面构建:验证 arxiv.org/abs/ URL 走 WEBPAGE 路由且摘要可检索"""+ arxiv_abs_url = "https://arxiv.org/abs/2301.00234"++ response = api_client.add_resource(path=arxiv_abs_url, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ meta = result.get("meta", {})+ assert meta.get("url_type") in ("webpage", None), (+ f"meta.url_type 应为 webpage, 实际: {meta.get('url_type')}"+ )++ assert_source_format(api_client, root_uri, ["html", "markdown"])++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_resource_indexed(api_client, root_uri, "arxiv")++ print(f"✓ TC-P07 arXiv HTML页面构建通过, root_uri: {root_uri}")diff --git a/tests/api_test/scenarios/resources_retrieval_slow/test_build_platform_general_web.py b/tests/api_test/scenarios/resources_retrieval_slow/test_build_platform_general_web.pynew file mode 100644index 000000000..6709eba89--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval_slow/test_build_platform_general_web.py@@ -0,0 +1,33 @@+from build_test_helpers import assert_resource_indexed, assert_root_uri_valid, assert_source_format+++class TestBuildPlatformGeneralWeb:+ """TC-P10 通用网页 URL 构建测试"""++ def test_build_general_webpage(self, api_client):+ """TC-P10 通用网页构建:验证任意 HTTP URL 走 WEBPAGE 路由且 source_format=html、内容可检索"""+ web_url = "https://httpbin.org/html"++ response = api_client.add_resource(path=web_url, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ meta = result.get("meta", {})+ assert meta.get("url_type") in ("webpage", None), (+ f"meta.url_type 应为 webpage, 实际: {meta.get('url_type')}"+ )++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, ["html", "markdown"])++ assert_resource_indexed(api_client, root_uri, "httpbin")++ print(f"✓ TC-P10 通用网页构建通过, root_uri: {root_uri}")diff --git a/tests/api_test/scenarios/resources_retrieval_slow/test_build_platform_github.py b/tests/api_test/scenarios/resources_retrieval_slow/test_build_platform_github.pynew file mode 100644index 000000000..d1e31d535--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval_slow/test_build_platform_github.py@@ -0,0 +1,125 @@+from build_test_helpers import assert_resource_indexed, assert_root_uri_valid, assert_source_format+++class TestBuildPlatformGithub:+ """TC-P01~P04 GitHub 平台 URL 构建测试"""++ def test_build_github_repo(self, api_client):+ """TC-P01 GitHub仓库构建:验证 github.com/org/repo 走 CodeRepositoryParser 且 root_uri 含 org/repo"""+ repo_url = "https://github.com/volcengine/OpenViking"++ response = api_client.add_resource(path=repo_url, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)+ assert "volcengine" in root_uri and "OpenViking" in root_uri, (+ f"GitHub仓库 root_uri 应含 volcengine/OpenViking, 实际: {root_uri}"+ )++ meta = result.get("meta", {})+ assert meta.get("url_type") in ("code_repository", None), (+ f"meta.url_type 应为 code_repository, 实际: {meta.get('url_type')}"+ )++ assert_source_format(api_client, root_uri, ["repository", "markdown"])++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ print(f"✓ TC-P01 GitHub仓库构建通过, root_uri: {root_uri}")++ def test_build_github_repo_with_branch(self, api_client):+ """TC-P02 GitHub指定分支构建:验证 github.com/org/repo/tree/branch 走 ZIP API 且 meta 含 repo_ref"""+ repo_url = "https://github.com/volcengine/OpenViking/tree/main"++ response = api_client.add_resource(path=repo_url, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)+ assert "volcengine" in root_uri and "OpenViking" in root_uri, (+ f"GitHub仓库 root_uri 应含 volcengine/OpenViking, 实际: {root_uri}"+ )++ meta = result.get("meta", {})+ if "repo_ref" in meta:+ assert meta["repo_ref"] == "main", f"meta.repo_ref 应为 main, 实际: {meta['repo_ref']}"++ assert_source_format(api_client, root_uri, ["repository", "markdown"])++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ print(f"✓ TC-P02 GitHub指定分支构建通过, root_uri: {root_uri}")++ def test_build_github_raw_file(self, api_client):+ """TC-P03 GitHub原始文件下载:验证 raw.githubusercontent.com URL 走 download_markdown 路由且内容可检索"""+ raw_url = "https://raw.githubusercontent.com/volcengine/OpenViking/main/README.md"++ response = api_client.add_resource(path=raw_url, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ meta = result.get("meta", {})+ assert meta.get("url_type") in (+ "download_md",+ "download_markdown",+ "download_txt",+ "webpage",+ None,+ ), (+ f"meta.url_type 应为 download_md/download_markdown/download_txt/webpage, 实际: {meta.get('url_type')}"+ )++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_resource_indexed(api_client, root_uri, "OpenViking")++ print(f"✓ TC-P03 GitHub原始文件下载通过, root_uri: {root_uri}")++ def test_build_github_blob_page(self, api_client):+ """TC-P04 GitHub Blob页面构建:验证 github.com/org/repo/blob/branch/file 被转为 raw URL 下载且内容可检索"""+ blob_url = "https://github.com/volcengine/OpenViking/blob/main/README.md"++ response = api_client.add_resource(path=blob_url, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ meta = result.get("meta", {})+ assert meta.get("url_type") in (+ "download_md",+ "download_markdown",+ "download_txt",+ "download_html",+ "webpage",+ None,+ ), f"meta.url_type 应为 download 类, 实际: {meta.get('url_type')}"++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_resource_indexed(api_client, root_uri, "OpenViking")++ print(f"✓ TC-P04 GitHub Blob页面构建通过, root_uri: {root_uri}")diff --git a/tests/api_test/scenarios/resources_retrieval_slow/test_build_platform_wikipedia.py b/tests/api_test/scenarios/resources_retrieval_slow/test_build_platform_wikipedia.pynew file mode 100644index 000000000..c339357ea--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval_slow/test_build_platform_wikipedia.py@@ -0,0 +1,36 @@+from build_test_helpers import assert_resource_indexed, assert_root_uri_valid, assert_source_format+++class TestBuildPlatformWikipedia:+ """TC-P05 Wikipedia 平台 URL 构建测试"""++ def test_build_wikipedia_page(self, api_client):+ """TC-P05 Wikipedia页面构建:验证 wikipedia.org URL 走 WEBPAGE 路由且内容可检索"""+ wiki_url = "https://en.wikipedia.org/wiki/Software_testing"++ response = api_client.add_resource(path=wiki_url, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok", (+ f"Wikipedia页面构建应返回ok, 实际: {data.get('status')}, error: {data.get('error')}"+ )++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert root_uri, "Wikipedia页面构建应返回root_uri, 实际为空"+ assert_root_uri_valid(root_uri)++ meta = result.get("meta", {})+ assert meta.get("url_type") in ("webpage", "download_text", "download_html", None), (+ f"meta.url_type 应为 webpage/download_text/download_html, 实际: {meta.get('url_type')}"+ )++ assert_source_format(api_client, root_uri, ["html", "markdown"])++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_resource_indexed(api_client, root_uri, "software testing")++ print(f"✓ TC-P05 Wikipedia页面构建通过, root_uri: {root_uri}")diff --git a/tests/api_test/scenarios/resources_retrieval_slow/test_build_text_resources_slow.py b/tests/api_test/scenarios/resources_retrieval_slow/test_build_text_resources_slow.pynew file mode 100644index 000000000..57985dd39--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval_slow/test_build_text_resources_slow.py@@ -0,0 +1,156 @@+import uuid++from build_test_helpers import (+ assert_resource_indexed,+ assert_root_uri_valid,+ assert_source_format,+ cleanup_temp_dir,+ create_test_file,+)+++class TestBuildTextResourcesSlow:+ """TC-B01, B02, B14, B15 文本类资源构建测试"""++ def test_build_txt_file(self, api_client):+ """TC-B01 纯文本文件构建:验证 .txt 文件添加后 source_format=text 且内容可检索"""+ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"txt_keyword_{random_id}"+ content = f"纯文本测试文件 {random_id}\n包含唯一关键词:{unique_keyword}\n用于验证txt文件构建产物。"++ test_file_path, temp_dir = create_test_file(content=content, suffix=".txt")+ try:+ response = api_client.add_resource(path=test_file_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, ["text", "markdown"])++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B01 纯文本文件构建通过, root_uri: {root_uri}")+ finally:+ cleanup_temp_dir(temp_dir)++ def test_build_markdown_file(self, api_client):+ """TC-B02 Markdown文件构建:验证 .md 文件添加后 heading 结构保留为子节点"""+ from build_test_helpers import assert_tree_has_child_nodes++ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"md_keyword_{random_id}"+ content = (+ f"# Markdown测试标题 {random_id}\n\n"+ f"包含唯一关键词:{unique_keyword}\n\n"+ f"## 第一节\n\n第一段内容。\n\n"+ f"## 第二节\n\n第二段内容。\n\n"+ f"### 子节\n\n子节内容。\n"+ )++ test_file_path, temp_dir = create_test_file(content=content, suffix=".md")+ try:+ response = api_client.add_resource(path=test_file_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, "markdown")++ assert_tree_has_child_nodes(api_client, root_uri, min_nodes=1)++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B02 Markdown文件构建通过, root_uri: {root_uri}")+ finally:+ cleanup_temp_dir(temp_dir)++ def test_build_empty_file(self, api_client):+ """TC-B15 空文件构建:验证空 .txt 文件添加后 root_uri 有效、fs_stat 可查、source_format 合理"""+ from build_test_helpers import assert_source_format++ test_file_path, temp_dir = create_test_file(content="", suffix=".txt")+ try:+ response = api_client.add_resource(path=test_file_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ if data.get("status") == "error":+ error_msg = str(data.get("error", ""))+ assert "empty" in error_msg.lower() or "error" in error_msg.lower(), (+ f"空文件错误信息应包含 empty/error, 实际: {error_msg}"+ )+ print(f"✓ TC-B15 空文件构建通过(服务端拒绝空文件): {error_msg[:80]}")+ return++ assert data.get("status") == "ok"++ result = data.get("result", {})+ if isinstance(result, dict) and result.get("status") == "error":+ inner_errors = result.get("errors", [])+ inner_msg = " ".join(str(e) for e in inner_errors)+ assert (+ "empty" in inner_msg.lower()+ or "error" in inner_msg.lower()+ or "parse" in inner_msg.lower()+ ), f"空文件内层错误应包含 empty/error/parse, 实际: {inner_msg}"+ print(f"✓ TC-B15 空文件构建通过(内层解析错误): {inner_msg[:80]}")+ return++ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200, f"空文件 fs_stat 应返回200, root_uri: {root_uri}"++ assert_source_format(api_client, root_uri, ["text", "markdown", ""])++ print(f"✓ TC-B15 空文件构建通过, root_uri: {root_uri}")+ finally:+ cleanup_temp_dir(temp_dir)++ def test_build_raw_content(self, api_client):+ """TC-B14 原始内容字符串构建:验证纯文本内容写入文件后添加可检索"""+ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"raw_keyword_{random_id}"+ raw_content = (+ f"原始内容测试 {random_id}\n包含唯一关键词:{unique_keyword}\n用于验证字符串输入构建。"+ )++ test_file_path, temp_dir = create_test_file(content=raw_content, suffix=".txt")+ try:+ response = api_client.add_resource(path=test_file_path, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert_root_uri_valid(root_uri)++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ assert_source_format(api_client, root_uri, ["text", "markdown"])++ assert_resource_indexed(api_client, root_uri, unique_keyword)++ print(f"✓ TC-B14 原始内容字符串构建通过, root_uri: {root_uri}")+ finally:+ cleanup_temp_dir(temp_dir)diff --git a/tests/api_test/scenarios/resources_retrieval_slow/test_build_uri_params_slow.py b/tests/api_test/scenarios/resources_retrieval_slow/test_build_uri_params_slow.pynew file mode 100644index 000000000..399ffdadc--- /dev/null+++ b/tests/api_test/scenarios/resources_retrieval_slow/test_build_uri_params_slow.py@@ -0,0 +1,117 @@+import uuid++from build_test_helpers import (+ _extract_error_message,+ assert_root_uri_valid,+ cleanup_temp_dir,+ create_test_file,+)+++class TestBuildUriParamsSlow:+ """TC-E11, E17, E18 URI参数与边界测试"""++ def test_build_with_to_param(self, api_client):+ """TC-E17 指定to参数构建:验证 root_uri == to"""+ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"to_keyword_{random_id}"+ target_uri = f"viking://resources/to_test_{random_id}"++ content = f"to参数测试 {random_id}\n包含唯一关键词:{unique_keyword}"+ test_file_path, temp_dir = create_test_file(content=content, suffix=".txt")+ try:+ response = api_client.add_resource(path=test_file_path, to=target_uri, wait=True)+ assert response.status_code == 200++ data = response.json()+ assert data.get("status") == "ok"++ result = data.get("result", {})+ root_uri = result.get("root_uri")+ assert root_uri == target_uri, (+ f"指定to时 root_uri 应等于 to, 期望: {target_uri}, 实际: {root_uri}"+ )++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ print(f"✓ TC-E17 指定to参数构建通过, root_uri: {root_uri}")+ finally:+ cleanup_temp_dir(temp_dir)++ def test_build_with_parent_param(self, api_client):+ """TC-E18 指定parent参数构建:验证 root_uri 以 parent 为前缀"""+ random_id = str(uuid.uuid4())[:8]+ unique_keyword = f"parent_keyword_{random_id}"+ parent_uri = f"viking://resources/parent_test_{random_id}"++ mkdir_resp = api_client.fs_mkdir(parent_uri)+ assert mkdir_resp.status_code == 200, (+ f"无法创建parent目录, fs_mkdir返回: {mkdir_resp.status_code}, body: {mkdir_resp.text}"+ )++ content = f"parent参数测试 {random_id}\n包含唯一关键词:{unique_keyword}"+ test_file_path, temp_dir = create_test_file(content=content, suffix=".txt")+ try:+ response = api_client.add_resource(path=test_file_path, parent=parent_uri, wait=True)+ assert response.status_code == 200++ data = response.json()+ if data.get("status") == "error":+ error_msg = _extract_error_message(data)+ raise AssertionError(f"parent参数构建失败, 服务端不支持parent参数: {error_msg}")++ result = data.get("result", {})+ if isinstance(result, dict) and result.get("status") == "error":+ inner_errors = result.get("errors", [])+ inner_msg = " ".join(str(e) for e in inner_errors)+ raise AssertionError(f"parent参数构建失败(内层错误): {inner_msg}")++ root_uri = result.get("root_uri") if isinstance(result, dict) else None+ assert_root_uri_valid(root_uri)+ assert root_uri.startswith(parent_uri), (+ f"指定parent时 root_uri 应以 parent 为前缀, parent: {parent_uri}, 实际: {root_uri}"+ )++ stat_resp = api_client.fs_stat(root_uri)+ assert stat_resp.status_code == 200++ print(f"✓ TC-E18 指定parent参数构建通过, root_uri: {root_uri}")+ finally:+ cleanup_temp_dir(temp_dir)++ def test_build_non_resources_scope_rejected(self, api_client):+ """TC-E11 非resources scope拒绝:验证 to=viking://sessions/xxx 返回错误"""+ random_id = str(uuid.uuid4())[:8]+ test_content = f"scope测试内容 {random_id}"+ test_file_path, temp_dir = create_test_file(content=test_content, suffix=".txt")+ try:+ response = api_client.add_resource(+ path=test_file_path,+ to="viking://sessions/test_session",+ wait=True,+ )++ data = response.json()+ if data.get("status") == "error":+ error_msg = _extract_error_message(data).lower()+ assert (+ "scope" in error_msg+ or "resources" in error_msg+ or "invalid" in error_msg+ or "permission" in error_msg+ or "internal" in error_msg+ ), f"scope拒绝应包含 scope/resources/invalid/permission/internal, 实际: {error_msg}"+ print("✓ TC-E11 非resources scope拒绝通过")+ return++ if data.get("status") == "ok":+ result = data.get("result", {})+ root_uri = result.get("root_uri", "")+ assert "sessions" not in root_uri, (+ f"非resources scope不应成功写入sessions, root_uri: {root_uri}"+ )+ print("✓ TC-E11 非resources scope处理通过(服务端重定向)")+ return+ finally:+ cleanup_temp_dir(temp_dir)diff --git a/tests/oc2ov_test/tests/base_cli_test.py b/tests/oc2ov_test/tests/base_cli_test.pyindex 4899411a2..5291a08f7 100644--- a/tests/oc2ov_test/tests/base_cli_test.py+++ b/tests/oc2ov_test/tests/base_cli_test.py@@ -220,6 +220,9 @@ class BaseOpenClawCLITest(unittest.TestCase):"did not produce a response","LLM idle timeout","timed out",+ "couldn't generate a response",+ "couldn't generate",+ "please try again",]return any(ind.lower() in text.lower() for ind in timeout_indicators)@@ -241,6 +244,22 @@ class BaseOpenClawCLITest(unittest.TestCase):]if any(text.startswith(p) for p in tool_result_prefixes):return True+ import re++ tool_result_pattern = r"^\[?\{[^}]*\"name\"\s*:\s*\"none\"[^}]*\}\]?[\s]*$"+ if re.match(tool_result_pattern, text):+ return True+ if text.startswith("[{") and text.endswith("}]"):+ try:+ import json++ parsed = json.loads(text)+ if isinstance(parsed, list) and all(+ isinstance(item, dict) and "name" in item for item in parsed+ ):+ return True+ except (json.JSONDecodeError, ValueError):+ passtool_result_patterns = ['"name":"none"',]diff --git a/tests/oc2ov_test/utils/assertions.py b/tests/oc2ov_test/utils/assertions.pyindex 69c24aedc..c1591b9e4 100644--- a/tests/oc2ov_test/utils/assertions.py+++ b/tests/oc2ov_test/utils/assertions.py@@ -15,6 +15,23 @@ class AssertionHelper:断言辅助类"""+ @staticmethod+ def _strip_tool_result_prefix(text: str) -> str:+ """+ 去除 LLM 响应中的工具调用结果前缀+ 例如: '[{"name":"none"}] 您的临时密码...' -> '您的临时密码...'+ """+ import re++ stripped = text.strip()+ tool_prefix_pattern = r"^\s*\[?\{[^}]*\}\]?\s*"+ while re.match(tool_prefix_pattern, stripped):+ remaining = re.sub(tool_prefix_pattern, "", stripped, count=1)+ if remaining == stripped:+ break+ stripped = remaining.strip()+ return stripped if stripped else text+@staticmethoddef extract_response_text(response: dict) -> str:"""@@ -22,17 +39,17 @@ class AssertionHelper:支持多种响应格式"""if isinstance(response, str):- return response+ return AssertionHelper._strip_tool_result_prefix(response)if isinstance(response, dict):if "output" in response:- return str(response["output"])+ return AssertionHelper._strip_tool_result_prefix(str(response["output"]))if "message" in response:- return str(response["message"])+ return AssertionHelper._strip_tool_result_prefix(str(response["message"]))if "content" in response:- return str(response["content"])+ return AssertionHelper._strip_tool_result_prefix(str(response["content"]))if "text" in response:- return str(response["text"])+ return AssertionHelper._strip_tool_result_prefix(str(response["text"]))if "result" in response and isinstance(response["result"], dict):result = response["result"]payloads = result.get("payloads")@@ -42,10 +59,10 @@ class AssertionHelper:if isinstance(p, dict) and "text" in p:texts.append(str(p["text"]))if texts:- return "\n".join(texts)+ return AssertionHelper._strip_tool_result_prefix("\n".join(texts))for key in ("output", "text", "content", "message", "response"):if key in result and result[key]:- return str(result[key])+ return AssertionHelper._strip_tool_result_prefix(str(result[key]))messages = result.get("messages")if isinstance(messages, list) and len(messages) > 0:for msg in reversed(messages):@@ -54,7 +71,7 @@ class AssertionHelper:if role == "assistant":c = msg.get("content", "")if c:- return str(c)+ return AssertionHelper._strip_tool_result_prefix(str(c))if "choices" in response and len(response["choices"]) > 0:choice = response["choices"][0]if isinstance(choice, dict):