Skip to content

Feat: add new tests and tescases for restful api suite - #15277

Merged
asiroliu merged 3 commits into
infiniflow:mainfrom
6ba3i:restful4
May 27, 2026
Merged

asiroliu merged 3 commits into
infiniflow:mainfrom
6ba3i:restful4

Conversation

@6ba3i

@6ba3i 6ba3i commented May 27, 2026

Copy link
Copy Markdown
Collaborator

What problem does this PR solve?

extend restful api suite

Type of change

  • New Feature (non-breaking change which adds functionality)
  • Other (please describe): test

@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label May 27, 2026
@coderabbitai

coderabbitai Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR extends REST API contract test coverage across three test modules by introducing runtime engine detection, adding comprehensive endpoint validation, and expanding document listing and upload test matrices with auth, filtering, sorting, and error-case assertions.

Changes

REST API Contract Test Expansion

Layer / File(s) Summary
Engine detection and skip migration
test/testcases/restful_api/test_chunks.py, test/testcases/restful_api/test_datasets.py
Introduces _is_infinity_doc_engine helper that queries /system/status or checks DOC_ENGINE env var, replacing env-var-only decorator-based skipping with runtime status detection in chunk list and dataset update tests.
Dataset endpoint contracts
test/testcases/restful_api/test_datasets.py
Adds contract tests for dataset search with parameter validation (page size, similarity threshold, vector weight, top_k), tags list/delete with invalid-id error cases, ingestion log filtering with empty-result handling, index operations across types (raptor, graph, mindmap) with trace/delete and task_id validation.
Document imports and helpers
test/testcases/restful_api/test_documents.py
Updates imports for concurrency, multipart uploads, filename handling, and constants, then introduces _upload_files, _seed_documents, _assert_docs_sorted, run-waiting, download helper, and Excel creation helpers used by document tests.
Document listing contracts
test/testcases/restful_api/test_documents.py
Adds document list endpoint validation for auth requirements (missing/invalid token), concurrent default listing, comprehensive filter matrix (time ranges, name, id, keyword, run), error handling for invalid parameters and pagination, and sort/order direction verification.
Document upload contracts
test/testcases/restful_api/test_documents.py
Adds upload matrix validating file extensions, empty files, duplicate filename renaming (within batch and across uploads with suffixes), maximum filename length, illegal character sanitization, and concurrent multi-file uploads; plus error cases for invalid dataset IDs, unsupported types, missing file part, and empty filenames.
Document delete, parse, stop, download, table-parser chat
test/testcases/restful_api/test_documents.py
Adds delete contract matrix and auth/ownership checks, parse/stop contract matrices with concurrency and duplicate-id cases, download binary integrity and concurrency tests, and an end-to-end table-parser chat test using Excel uploads.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#15223: Modifies test_datasets.py to handle infinity/DOC_ENGINE engine-dependent behavior with pagerank conditional skipping.
  • infiniflow/ragflow#15038: Modifies test_chunks.py chunk list tests to handle infinity doc engine runtime skip logic.

Suggested labels

🌈 python, 🧪 test

Poem

🐇 In test-land I hop and prance,

checking engines at a glance,
uploads, lists, and parses too,
contracts sing — assertions true,
a rabbit cheers this testing dance.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: adding new tests and test cases for the RESTful API suite, which aligns with all file changes.
Description check ✅ Passed The description covers the required sections from the template, including what problem the PR solves and the type of change, though both are brief.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@6ba3i 6ba3i added the ci Continue Integration label May 27, 2026
@6ba3i
6ba3i marked this pull request as draft May 27, 2026 03:07
@6ba3i
6ba3i marked this pull request as ready for review May 27, 2026 03:07

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

🧹 Nitpick comments (4)
test/testcases/restful_api/test_chunks.py (1)

25-39: ⚡ Quick win

Add debug logging in the engine-detection fallback path.

The new flow catches all exceptions and silently returns False, which makes CI/environment failures hard to diagnose.

♻️ Suggested patch
+import logging
 from concurrent.futures import ThreadPoolExecutor
 import os
 import pytest
@@
+logger = logging.getLogger(__name__)
+
 def _is_infinity_doc_engine(rest_client: RestClient) -> bool:
@@
-    except Exception:
+    except Exception:
+        logger.debug("Failed to detect doc engine from /system/status", exc_info=True)
         return False

As per coding guidelines, "**/*.py: Add logging for new flows".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/restful_api/test_chunks.py` around lines 25 - 39, The function
_is_infinity_doc_engine currently swallows errors and non-OK responses silently;
update it to log debug/error details so CI failures are diagnosable: inside
_is_infinity_doc_engine (around the rest_client.get("/system/status") call and
the subsequent checks for res.status_code and payload.get("code")), add logging
that records the HTTP status, response body/json (or parsing error), and
exception stacktrace in the except block (use the project's logger or Python
logging at debug/error level) before returning False so callers see why
detection failed.
test/testcases/restful_api/test_datasets.py (1)

29-43: ⚡ Quick win

Log detection failures in _is_infinity_doc_engine.

This new helper suppresses all exceptions without trace, which makes engine-detection failures opaque in CI.

♻️ Suggested patch
+import logging
 from concurrent.futures import ThreadPoolExecutor, as_completed
 import os
 import uuid
@@
+logger = logging.getLogger(__name__)
+
 def _is_infinity_doc_engine(rest_client: RestClient) -> bool:
@@
-    except Exception:
+    except Exception:
+        logger.debug("Failed to detect doc engine from /system/status", exc_info=True)
         return False

As per coding guidelines, "**/*.py: Add logging for new flows".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/restful_api/test_datasets.py` around lines 29 - 43, The helper
_is_infinity_doc_engine currently swallows all exceptions making failures
opaque; update it to catch exceptions but log the error and context before
returning False so CI can diagnose issues—use the module logger (or the
project's test logger) to log the exception and relevant response/URL in the
except block, and include try/except around rest_client.get and payload parsing
in _is_infinity_doc_engine so failures in rest_client.get, res.json(), or
missing fields are logged with the exception details and then return False.
test/testcases/restful_api/test_documents.py (2)

68-70: ⚡ Quick win

Consider validating key existence in documents.

The helper extracts values without checking if the key exists. If a document is missing the expected key, doc.get(key) returns None, which might pass sorting assertions unexpectedly.

🛡️ Proposed enhancement
 def _assert_docs_sorted(docs, key, reverse):
     values = [doc.get(key) for doc in docs]
+    assert all(v is not None for v in values), f"Key '{key}' missing in some documents"
     assert values == sorted(values, reverse=reverse)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/restful_api/test_documents.py` around lines 68 - 70, The
helper _assert_docs_sorted currently uses doc.get(key) which can return None if
a document lacks the key; update _assert_docs_sorted to first validate that
every document contains the expected key (e.g., assert key in doc for each doc,
including the index or a clear message identifying the offending document)
before collecting values, then proceed to compare values == sorted(values,
reverse=reverse); reference the helper name _assert_docs_sorted and the
parameter key when adding this explicit presence check so missing-key cases fail
loudly instead of silently passing due to None values.

113-117: Consider the concurrent request load in test environments.

Submitting 30 concurrent requests might overwhelm resource-constrained test environments or trigger rate limiting. If you observe flakiness, consider reducing the count or making it configurable via environment variables.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/restful_api/test_documents.py` around lines 113 - 117, The
test spawns 30 concurrent requests which can overwhelm CI/test environments;
update the test to use a configurable concurrency count instead of the hardcoded
30 by reading an environment variable (e.g., CONCURRENT_REQUESTS) with a
sensible default (e.g., 5 or 10), adjust ThreadPoolExecutor(max_workers=...) and
the range(...) to use that variable, and keep using rest_client.get, futures,
dataset_id and as_completed so behavior is unchanged when the env var is high
but safe in constrained runs.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/testcases/restful_api/test_documents.py`:
- Around line 100-143: The test function
test_documents_list_default_concurrent_and_filters_contract lacks logging for
its major phases; add structured logging calls (e.g., using the test module's
logger or Python's logging) at the start and after each phase: after the default
listing (log dataset_id, total and first_id/name), before/after the concurrent
requests block (log number of concurrent requests and any failures), and
before/after the filter matrix loop (log each params set and its expected vs
actual result); reference the test function name
test_documents_list_default_concurrent_and_filters_contract and the local
variables dataset_id, first_id, first_name, default_payload, futures, and
payload to place the log messages so reviewers can trace flow without changing
assertions.
- Around line 391-431: In test_documents_upload_error_contract, add logging
calls to record each error scenario before assertions: obtain a module logger
(e.g., logger = logging.getLogger(__name__)), then log the responses and
payloads for the invalid dataset case (invalid_dataset_res /
invalid_dataset_payload), each unsupported file type loop iteration (res /
payload and the file_type), the missing file case (missing_res /
missing_payload), and the empty filename case (filename_empty_res /
filename_empty_payload); use logger.info or logger.debug with descriptive
messages so the test output shows the request target and returned payloads for
debugging while keeping assertions unchanged.
- Around line 51-54: The helper _upload_files is missing logging; add a logger
(module-level logger = logging.getLogger(__name__)) and insert a log call in
_upload_files that logs the dataset_id and the count of file_paths (e.g.,
logger.info or debug) before calling rest_client.post; keep the existing file
handling and return value intact and ensure the logging import and logger
variable are added to the module if not already present.
- Around line 315-388: The test test_documents_upload_contract_matrix needs
logging added for its major scenarios; update the test function to emit
debug/info logs at key steps (after valid_res success, inside the file-type loop
for each ext, after empty_res, for duplicate_res and each repeat_res iteration,
after max_name_res, after special_res, after multi_res, and for concurrent
upload results) using the project logger (or pytest's caplog) so failures
include context; locate the function test_documents_upload_contract_matrix and
insert concise log statements referencing the response objects (valid_res, res,
empty_res, duplicate_res, repeat_res, max_name_res, special_res, multi_res) and
the filename variables (fp, duplicate_fp, max_name_fp, special_fp) to record
status_code and payload summaries.
- Around line 73-81: Add logging statements to the
test_documents_list_requires_auth flow so each scenario logs the dataset_id,
scenario_name, request path, response status_code and the parsed payload for
traceability; import and use Python's logging (getLogger(__name__)) or pytest's
logger at the top of the module, then inside test_documents_list_requires_auth
log before/after the client.get call using the existing variables dataset_id,
scenario_name, client, res and payload so failures include these details.
- Around line 84-97: The test_documents_upload_requires_auth test lacks logging;
add structured debug logs using logging.getLogger(__name__) inside the test to
record key values (dataset_id from create_dataset, fp path, scenario_name)
before the request and to log the response status and payload after the request
(res.status_code and res.text / res.json()). Place logs inside the for loop
around the client.post call in test_documents_upload_requires_auth and ensure
the token value is masked or described (e.g., "missing" vs "invalid") rather
than printing secrets; also import logging if not present.
- Around line 146-302: The test test_documents_list_error_and_sorting_contract
lacks logging for its three phases (error cases, pagination checks, sorting
checks); add concise debug/info logs at the start of each phase using the test
function name to identify context—log when entering the "error_cases" loop
(include case_name and path), when starting pagination assertions (include
params and expected_total), and when starting sorting assertions (include
params, expected_key, expected_desc); place logs immediately before the
respective for-loops that iterate over error_cases, the pagination tuple, and
the ordering tuple so when test failures occur the logs show which sub-flow and
parameters were exercised.
- Around line 57-65: In _seed_documents, avoid the hard-coded dataset name by
generating a unique name (e.g., append tmp_path.name or a short UUID) when
calling create_dataset so parallel runs won't collide, and add logging
statements (using the module logger) to record the created dataset name, number
of files, and the upload response; update the _seed_documents function to call
logger.debug/info before and after _upload_files and include references to
dataset_id, file_paths, and payload in the logs so failures are easier to trace.
- Around line 364-372: The test builds a "safe" filename instead of uploading
one containing illegal characters (variables: illegal_chars, safe_filename,
special_fp), so change the test to create an actual filename containing the
illegal characters (e.g., unsafe_name = f"file{illegal_chars}.txt" -> special_fp
= tmp_path / unsafe_name), upload via _upload_files(rest_client, dataset_id,
[special_fp]) and then assert the API returned a sanitized name (compute
expected_sanitized by replacing each char in illegal_chars with '_' and compare
to special_payload["data"][0]["name"]); alternatively, if the intent was to test
accepting safe punctuation, rename illegal_chars to safe_punctuation to avoid
confusion.

---

Nitpick comments:
In `@test/testcases/restful_api/test_chunks.py`:
- Around line 25-39: The function _is_infinity_doc_engine currently swallows
errors and non-OK responses silently; update it to log debug/error details so CI
failures are diagnosable: inside _is_infinity_doc_engine (around the
rest_client.get("/system/status") call and the subsequent checks for
res.status_code and payload.get("code")), add logging that records the HTTP
status, response body/json (or parsing error), and exception stacktrace in the
except block (use the project's logger or Python logging at debug/error level)
before returning False so callers see why detection failed.

In `@test/testcases/restful_api/test_datasets.py`:
- Around line 29-43: The helper _is_infinity_doc_engine currently swallows all
exceptions making failures opaque; update it to catch exceptions but log the
error and context before returning False so CI can diagnose issues—use the
module logger (or the project's test logger) to log the exception and relevant
response/URL in the except block, and include try/except around rest_client.get
and payload parsing in _is_infinity_doc_engine so failures in rest_client.get,
res.json(), or missing fields are logged with the exception details and then
return False.

In `@test/testcases/restful_api/test_documents.py`:
- Around line 68-70: The helper _assert_docs_sorted currently uses doc.get(key)
which can return None if a document lacks the key; update _assert_docs_sorted to
first validate that every document contains the expected key (e.g., assert key
in doc for each doc, including the index or a clear message identifying the
offending document) before collecting values, then proceed to compare values ==
sorted(values, reverse=reverse); reference the helper name _assert_docs_sorted
and the parameter key when adding this explicit presence check so missing-key
cases fail loudly instead of silently passing due to None values.
- Around line 113-117: The test spawns 30 concurrent requests which can
overwhelm CI/test environments; update the test to use a configurable
concurrency count instead of the hardcoded 30 by reading an environment variable
(e.g., CONCURRENT_REQUESTS) with a sensible default (e.g., 5 or 10), adjust
ThreadPoolExecutor(max_workers=...) and the range(...) to use that variable, and
keep using rest_client.get, futures, dataset_id and as_completed so behavior is
unchanged when the env var is high but safe in constrained runs.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1e1a0a07-717b-494e-b4c1-7a3e850a41be

📥 Commits

Reviewing files that changed from the base of the PR and between 8f0632c and 102923c.

📒 Files selected for processing (3)
  • test/testcases/restful_api/test_chunks.py
  • test/testcases/restful_api/test_datasets.py
  • test/testcases/restful_api/test_documents.py

Comment on lines +51 to +54
def _upload_files(rest_client, dataset_id, file_paths):
with ExitStack() as stack:
files = [("file", (fp.name, stack.enter_context(fp.open("rb")))) for fp in file_paths]
return rest_client.post(f"/datasets/{dataset_id}/documents", files=files)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add logging for the upload helper flow.

Per coding guidelines, new flows should include logging. Consider adding a log statement to track the number of files being uploaded and the dataset ID.

As per coding guidelines: "Add logging for new flows" for files matching **/*.py.

📝 Proposed fix
+import logging
+
+logger = logging.getLogger(__name__)
+
 def _upload_files(rest_client, dataset_id, file_paths):
+    logger.info(f"Uploading {len(file_paths)} files to dataset {dataset_id}")
     with ExitStack() as stack:
         files = [("file", (fp.name, stack.enter_context(fp.open("rb")))) for fp in file_paths]
         return rest_client.post(f"/datasets/{dataset_id}/documents", files=files)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/restful_api/test_documents.py` around lines 51 - 54, The
helper _upload_files is missing logging; add a logger (module-level logger =
logging.getLogger(__name__)) and insert a log call in _upload_files that logs
the dataset_id and the count of file_paths (e.g., logger.info or debug) before
calling rest_client.post; keep the existing file handling and return value
intact and ensure the logging import and logger variable are added to the module
if not already present.

Comment on lines +57 to +65
def _seed_documents(rest_client, create_dataset, tmp_path, count=5):
dataset_id = create_dataset("dataset_list_contract")
file_paths = [create_txt_file(tmp_path / f"ragflow_test_upload_{i}.txt") for i in range(count)]
res = _upload_files(rest_client, dataset_id, file_paths)
assert res.status_code == 200
payload = res.json()
assert payload["code"] == 0, payload
assert len(payload["data"]) == count, payload
return dataset_id, payload["data"]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add logging and ensure unique dataset names.

Two improvements needed:

  1. The hard-coded dataset name "dataset_list_contract" is not unique per call, which could cause conflicts if tests run in parallel or if the helper is reused.
  2. Per coding guidelines, new flows should include logging.

As per coding guidelines: "Add logging for new flows" for files matching **/*.py.

📝 Proposed fix
+import logging
+import uuid
+
+logger = logging.getLogger(__name__)
+
-def _seed_documents(rest_client, create_dataset, tmp_path, count=5):
-    dataset_id = create_dataset("dataset_list_contract")
+def _seed_documents(rest_client, create_dataset, tmp_path, count=5, dataset_name=None):
+    unique_name = dataset_name or f"dataset_seed_{uuid.uuid4().hex[:8]}"
+    dataset_id = create_dataset(unique_name)
+    logger.info(f"Seeding {count} documents in dataset {dataset_id}")
     file_paths = [create_txt_file(tmp_path / f"ragflow_test_upload_{i}.txt") for i in range(count)]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/restful_api/test_documents.py` around lines 57 - 65, In
_seed_documents, avoid the hard-coded dataset name by generating a unique name
(e.g., append tmp_path.name or a short UUID) when calling create_dataset so
parallel runs won't collide, and add logging statements (using the module
logger) to record the created dataset name, number of files, and the upload
response; update the _seed_documents function to call logger.debug/info before
and after _upload_files and include references to dataset_id, file_paths, and
payload in the logs so failures are easier to trace.

Comment on lines +73 to +81
@pytest.mark.p1
def test_documents_list_requires_auth(create_dataset):
dataset_id = create_dataset("dataset_list_auth")
for scenario_name, client in (("missing token", RestClient(token=None)), ("invalid token", RestClient(token=INVALID_API_TOKEN))):
res = client.get(f"/datasets/{dataset_id}/documents")
assert res.status_code == 401, (scenario_name, res.text)
payload = res.json()
assert payload["code"] == 401, (scenario_name, payload)
assert payload["message"] == "<Unauthorized '401: Unauthorized'>", (scenario_name, payload)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add logging for the auth test flow.

Per coding guidelines, new test flows should include logging to aid in debugging and test traceability.

As per coding guidelines: "Add logging for new flows" for files matching **/*.py.

📝 Proposed fix
+import logging
+
+logger = logging.getLogger(__name__)
+
 `@pytest.mark.p1`
 def test_documents_list_requires_auth(create_dataset):
     dataset_id = create_dataset("dataset_list_auth")
+    logger.info(f"Testing list auth requirements for dataset {dataset_id}")
     for scenario_name, client in (("missing token", RestClient(token=None)), ("invalid token", RestClient(token=INVALID_API_TOKEN))):
+        logger.debug(f"Testing scenario: {scenario_name}")
         res = client.get(f"/datasets/{dataset_id}/documents")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@pytest.mark.p1
def test_documents_list_requires_auth(create_dataset):
dataset_id = create_dataset("dataset_list_auth")
for scenario_name, client in (("missing token", RestClient(token=None)), ("invalid token", RestClient(token=INVALID_API_TOKEN))):
res = client.get(f"/datasets/{dataset_id}/documents")
assert res.status_code == 401, (scenario_name, res.text)
payload = res.json()
assert payload["code"] == 401, (scenario_name, payload)
assert payload["message"] == "<Unauthorized '401: Unauthorized'>", (scenario_name, payload)
import logging
logger = logging.getLogger(__name__)
`@pytest.mark.p1`
def test_documents_list_requires_auth(create_dataset):
dataset_id = create_dataset("dataset_list_auth")
logger.info(f"Testing list auth requirements for dataset {dataset_id}")
for scenario_name, client in (("missing token", RestClient(token=None)), ("invalid token", RestClient(token=INVALID_API_TOKEN))):
logger.debug(f"Testing scenario: {scenario_name}")
res = client.get(f"/datasets/{dataset_id}/documents")
assert res.status_code == 401, (scenario_name, res.text)
payload = res.json()
assert payload["code"] == 401, (scenario_name, payload)
assert payload["message"] == "<Unauthorized '401: Unauthorized'>", (scenario_name, payload)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/restful_api/test_documents.py` around lines 73 - 81, Add
logging statements to the test_documents_list_requires_auth flow so each
scenario logs the dataset_id, scenario_name, request path, response status_code
and the parsed payload for traceability; import and use Python's logging
(getLogger(__name__)) or pytest's logger at the top of the module, then inside
test_documents_list_requires_auth log before/after the client.get call using the
existing variables dataset_id, scenario_name, client, res and payload so
failures include these details.

Comment on lines +84 to +97
@pytest.mark.p1
def test_documents_upload_requires_auth(create_dataset, tmp_path):
dataset_id = create_dataset("dataset_upload_auth")
fp = create_txt_file(tmp_path / "upload_auth.txt")
for scenario_name, client in (("missing token", RestClient(token=None)), ("invalid token", RestClient(token=INVALID_API_TOKEN))):
with fp.open("rb") as file_obj:
res = client.post(
f"/datasets/{dataset_id}/documents",
files=[("file", (fp.name, file_obj))],
)
assert res.status_code == 401, (scenario_name, res.text)
payload = res.json()
assert payload["code"] == 401, (scenario_name, payload)
assert payload["message"] == "<Unauthorized '401: Unauthorized'>", (scenario_name, payload)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add logging for the upload auth test flow.

Per coding guidelines, new test flows should include logging to aid in debugging and test traceability.

As per coding guidelines: "Add logging for new flows" for files matching **/*.py.

📝 Proposed fix
 `@pytest.mark.p1`
 def test_documents_upload_requires_auth(create_dataset, tmp_path):
     dataset_id = create_dataset("dataset_upload_auth")
     fp = create_txt_file(tmp_path / "upload_auth.txt")
+    logger.info(f"Testing upload auth requirements for dataset {dataset_id}")
     for scenario_name, client in (("missing token", RestClient(token=None)), ("invalid token", RestClient(token=INVALID_API_TOKEN))):
+        logger.debug(f"Testing scenario: {scenario_name}")
         with fp.open("rb") as file_obj:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/restful_api/test_documents.py` around lines 84 - 97, The
test_documents_upload_requires_auth test lacks logging; add structured debug
logs using logging.getLogger(__name__) inside the test to record key values
(dataset_id from create_dataset, fp path, scenario_name) before the request and
to log the response status and payload after the request (res.status_code and
res.text / res.json()). Place logs inside the for loop around the client.post
call in test_documents_upload_requires_auth and ensure the token value is masked
or described (e.g., "missing" vs "invalid") rather than printing secrets; also
import logging if not present.

Comment on lines +100 to +143
@pytest.mark.p2
def test_documents_list_default_concurrent_and_filters_contract(rest_client, create_dataset, tmp_path):
dataset_id, uploaded_docs = _seed_documents(rest_client, create_dataset, tmp_path)
first_id = uploaded_docs[0]["id"]
first_name = uploaded_docs[0]["name"]

default_res = rest_client.get(f"/datasets/{dataset_id}/documents")
assert default_res.status_code == 200
default_payload = default_res.json()
assert default_payload["code"] == 0, default_payload
assert default_payload["data"]["total"] == 5, default_payload
assert len(default_payload["data"]["docs"]) == 5, default_payload

with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(rest_client.get, f"/datasets/{dataset_id}/documents") for _ in range(30)]
responses = list(as_completed(futures))
assert len(responses) == 30, responses
assert all(f.result().json()["code"] == 0 for f in futures)

for params, expected_code, expected_docs, expected_total in (
({"create_time_from": "9999999999000"}, 0, 0, 5),
({"create_time_to": "1"}, 0, 0, 5),
({"create_time_from": "0", "create_time_to": "9999999999000"}, 0, 5, 5),
({"keywords": None}, 0, 5, 5),
({"keywords": ""}, 0, 5, 5),
({"keywords": "0"}, 0, 1, 1),
({"keywords": "ragflow_test_upload"}, 0, 5, 5),
({"keywords": "unknown"}, 0, 0, 0),
({"name": None}, 0, 5, 5),
({"name": ""}, 0, 5, 5),
({"name": first_name}, 0, 1, 1),
({"id": None}, 0, 5, 5),
({"id": ""}, 0, 5, 5),
({"id": first_id}, 0, 1, 1),
({"id": first_id, "name": first_name}, 0, 1, 1),
({"id": first_id, "name": "ragflow_test_upload_1.txt"}, 0, 0, 0),
({"run": ["UNSTART"]}, 0, 5, 5),
):
res = rest_client.get(f"/datasets/{dataset_id}/documents", params=params)
assert res.status_code == 200, (params, res.text)
payload = res.json()
assert payload["code"] == expected_code, (params, payload)
assert payload["data"]["total"] == expected_total, (params, payload)
assert len(payload["data"]["docs"]) == expected_docs, (params, payload)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add logging for the contract test flow.

Per coding guidelines, new test flows should include logging. Consider adding log statements for the different test phases (default listing, concurrent testing, filter matrix).

As per coding guidelines: "Add logging for new flows" for files matching **/*.py.

📝 Proposed fix
 `@pytest.mark.p2`
 def test_documents_list_default_concurrent_and_filters_contract(rest_client, create_dataset, tmp_path):
+    logger.info("Testing documents list default, concurrent, and filters contract")
     dataset_id, uploaded_docs = _seed_documents(rest_client, create_dataset, tmp_path)
     first_id = uploaded_docs[0]["id"]
     first_name = uploaded_docs[0]["name"]
 
     default_res = rest_client.get(f"/datasets/{dataset_id}/documents")
+    logger.debug("Testing default listing")
     assert default_res.status_code == 200
     default_payload = default_res.json()
     assert default_payload["code"] == 0, default_payload
     assert default_payload["data"]["total"] == 5, default_payload
     assert len(default_payload["data"]["docs"]) == 5, default_payload
 
+    logger.debug("Testing concurrent requests")
     with ThreadPoolExecutor(max_workers=5) as executor:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/restful_api/test_documents.py` around lines 100 - 143, The
test function test_documents_list_default_concurrent_and_filters_contract lacks
logging for its major phases; add structured logging calls (e.g., using the test
module's logger or Python's logging) at the start and after each phase: after
the default listing (log dataset_id, total and first_id/name), before/after the
concurrent requests block (log number of concurrent requests and any failures),
and before/after the filter matrix loop (log each params set and its expected vs
actual result); reference the test function name
test_documents_list_default_concurrent_and_filters_contract and the local
variables dataset_id, first_id, first_name, default_payload, futures, and
payload to place the log messages so reviewers can trace flow without changing
assertions.

Comment on lines +146 to +302
@pytest.mark.p2
def test_documents_list_error_and_sorting_contract(rest_client, create_dataset, tmp_path):
dataset_id, uploaded_docs = _seed_documents(rest_client, create_dataset, tmp_path)
first_id = uploaded_docs[0]["id"]

error_cases = [
(
"invalid dataset empty",
"/datasets//documents",
None,
102,
"lacks permission for dataset 'documents'",
),
(
"invalid dataset id",
"/datasets/invalid_dataset_id/documents",
None,
102,
"You don't own the dataset invalid_dataset_id.",
),
(
"invalid params ignored",
f"/datasets/{dataset_id}/documents",
{"a": "b"},
0,
"",
),
(
"metadata json invalid",
f"/datasets/{dataset_id}/documents",
{"metadata_condition": "{bad json"},
102,
"metadata_condition must be valid JSON",
),
(
"metadata json non-object",
f"/datasets/{dataset_id}/documents",
{"metadata_condition": "[1]"},
102,
"metadata_condition must be an object",
),
(
"name unknown",
f"/datasets/{dataset_id}/documents",
{"name": "unknown.txt"},
102,
"You don't own the document unknown.txt.",
),
(
"id unknown",
f"/datasets/{dataset_id}/documents",
{"id": "unknown.txt"},
102,
"You don't own the document unknown.txt.",
),
(
"name+id unknown name",
f"/datasets/{dataset_id}/documents",
{"id": first_id, "name": "unknown"},
102,
"You don't own the document unknown.",
),
(
"name+id unknown id",
f"/datasets/{dataset_id}/documents",
{"id": "id", "name": "ragflow_test_upload_0.txt"},
102,
"You don't own the document id.",
),
(
"run invalid",
f"/datasets/{dataset_id}/documents",
{"run": ["INVALID_STATUS"]},
102,
"Invalid filter run status conditions: INVALID_STATUS",
),
(
"orderby invalid",
f"/datasets/{dataset_id}/documents",
{"orderby": "unknown"},
100,
"Document' has no attribute 'unknown'",
),
(
"page invalid number",
f"/datasets/{dataset_id}/documents",
{"page": -1, "page_size": 2},
100,
"1064",
),
(
"page invalid type",
f"/datasets/{dataset_id}/documents",
{"page": "a", "page_size": 2},
100,
"invalid literal for int()",
),
(
"page_size invalid number",
f"/datasets/{dataset_id}/documents",
{"page_size": -1},
100,
"1064",
),
(
"page_size invalid type",
f"/datasets/{dataset_id}/documents",
{"page_size": "a"},
100,
"invalid literal for int()",
),
]
for case_name, path, params, expected_code, expected_message in error_cases:
res = rest_client.get(path, params=params)
assert res.status_code == 200, (case_name, res.text)
payload = res.json()
assert payload["code"] == expected_code, (case_name, payload)
assert expected_message in payload["message"], (case_name, payload)

for params, expected_total in (
({"page": None, "page_size": 2}, 2),
({"page": 1, "page_size": 2}, 2),
({"page": 2, "page_size": 2}, 2),
({"page": 3, "page_size": 2}, 1),
({"page": "3", "page_size": 2}, 1),
({"page_size": None}, 5),
({"page_size": 1}, 1),
({"page_size": 6}, 5),
({"page_size": "1"}, 1),
):
res = rest_client.get(f"/datasets/{dataset_id}/documents", params=params)
assert res.status_code == 200, (params, res.text)
payload = res.json()
assert payload["code"] == 0, (params, payload)
assert len(payload["data"]["docs"]) == expected_total, (params, payload)
assert payload["data"]["total"] == 5, (params, payload)

for params, expected_key, expected_desc in (
({"orderby": None}, "create_time", True),
({"orderby": "create_time"}, "create_time", True),
({"orderby": "update_time"}, "update_time", True),
({"orderby": "name", "desc": "False"}, "name", False),
({"desc": None}, "create_time", True),
({"desc": "true"}, "create_time", True),
({"desc": "True"}, "create_time", True),
({"desc": True}, "create_time", True),
({"desc": "false"}, "create_time", False),
({"desc": "False"}, "create_time", False),
({"desc": False}, "create_time", False),
({"desc": "False", "orderby": "update_time"}, "update_time", False),
({"desc": "unknown"}, "create_time", True),
):
res = rest_client.get(f"/datasets/{dataset_id}/documents", params=params)
assert res.status_code == 200, (params, res.text)
payload = res.json()
assert payload["code"] == 0, (params, payload)
_assert_docs_sorted(payload["data"]["docs"], expected_key, expected_desc)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add logging for the error and sorting contract test.

Per coding guidelines, new test flows should include logging. Consider adding log statements for the different test phases (error cases, pagination, sorting).

As per coding guidelines: "Add logging for new flows" for files matching **/*.py.

📝 Proposed fix
 `@pytest.mark.p2`
 def test_documents_list_error_and_sorting_contract(rest_client, create_dataset, tmp_path):
+    logger.info("Testing documents list error and sorting contract")
     dataset_id, uploaded_docs = _seed_documents(rest_client, create_dataset, tmp_path)
     first_id = uploaded_docs[0]["id"]
 
+    logger.debug("Testing error cases")
     error_cases = [
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/restful_api/test_documents.py` around lines 146 - 302, The
test test_documents_list_error_and_sorting_contract lacks logging for its three
phases (error cases, pagination checks, sorting checks); add concise debug/info
logs at the start of each phase using the test function name to identify
context—log when entering the "error_cases" loop (include case_name and path),
when starting pagination assertions (include params and expected_total), and
when starting sorting assertions (include params, expected_key, expected_desc);
place logs immediately before the respective for-loops that iterate over
error_cases, the pagination tuple, and the ordering tuple so when test failures
occur the logs show which sub-flow and parameters were exercised.

Comment on lines +315 to +388
@pytest.mark.p2
def test_documents_upload_contract_matrix(rest_client, create_dataset, tmp_path):
dataset_id = create_dataset("dataset_upload_contract")

valid_res = _upload_files(rest_client, dataset_id, [create_txt_file(tmp_path / "ragflow_test.txt")])
assert valid_res.status_code == 200
valid_payload = valid_res.json()
assert valid_payload["code"] == 0, valid_payload
assert valid_payload["data"][0]["dataset_id"] == dataset_id, valid_payload
assert valid_payload["data"][0]["name"] == "ragflow_test.txt", valid_payload

for ext in ("docx", "xlsx", "pptx", "jpg", "pdf", "txt", "md", "json", "eml", "html"):
fp = create_txt_file(tmp_path / f"ragflow_test_file_type.{ext}")
res = _upload_files(rest_client, dataset_id, [fp])
assert res.status_code == 200, (ext, res.text)
payload = res.json()
assert payload["code"] == 0, (ext, payload)
assert payload["data"][0]["name"] == fp.name, (ext, payload)

empty_fp = tmp_path / "empty.txt"
empty_fp.touch()
empty_res = _upload_files(rest_client, dataset_id, [empty_fp])
assert empty_res.status_code == 200
empty_payload = empty_res.json()
assert empty_payload["code"] == 0, empty_payload
assert empty_payload["data"][0]["size"] == 0, empty_payload

duplicate_fp = create_txt_file(tmp_path / "duplicate.txt")
duplicate_res = _upload_files(rest_client, dataset_id, [duplicate_fp, duplicate_fp])
assert duplicate_res.status_code == 200
duplicate_payload = duplicate_res.json()
assert duplicate_payload["code"] == 0, duplicate_payload
assert [x["name"] for x in duplicate_payload["data"]] == ["duplicate.txt", "duplicate(1).txt"], duplicate_payload

for index in range(3):
repeat_res = _upload_files(rest_client, dataset_id, [duplicate_fp])
assert repeat_res.status_code == 200
repeat_payload = repeat_res.json()
assert repeat_payload["code"] == 0, (index, repeat_payload)
expected_name = f"duplicate({index + 2}).txt"
assert repeat_payload["data"][0]["name"] == expected_name, (index, repeat_payload)

max_name_fp = create_txt_file(tmp_path / f"{'a' * (DOCUMENT_NAME_LIMIT - 4)}.txt")
max_name_res = _upload_files(rest_client, dataset_id, [max_name_fp])
assert max_name_res.status_code == 200
max_name_payload = max_name_res.json()
assert max_name_payload["code"] == 0, max_name_payload
assert max_name_payload["data"][0]["name"] == max_name_fp.name, max_name_payload

illegal_chars = '<>:"/\\|?*'
safe_filename = string.punctuation.translate(str.maketrans({char: "_" for char in illegal_chars}))
special_fp = tmp_path / f"{safe_filename}.txt"
special_fp.write_text("Sample text content")
special_res = _upload_files(rest_client, dataset_id, [special_fp])
assert special_res.status_code == 200
special_payload = special_res.json()
assert special_payload["code"] == 0, special_payload
assert special_payload["data"][0]["name"] == special_fp.name, special_payload

multi_paths = [create_txt_file(tmp_path / f"ragflow_test_multi_{i}.txt") for i in range(20)]
multi_res = _upload_files(rest_client, dataset_id, multi_paths)
assert multi_res.status_code == 200
multi_payload = multi_res.json()
assert multi_payload["code"] == 0, multi_payload
assert len(multi_payload["data"]) == 20, multi_payload

with ThreadPoolExecutor(max_workers=5) as executor:
futures = [
executor.submit(_upload_files, rest_client, dataset_id, [create_txt_file(tmp_path / f"parallel_upload_{i}.txt")])
for i in range(20)
]
responses = list(as_completed(futures))
assert len(responses) == 20, responses
assert all(f.result().json()["code"] == 0 for f in futures)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add logging for the upload contract matrix test.

Per coding guidelines, new test flows should include logging. Consider adding log statements for the different test scenarios (file types, duplicates, max length, concurrent uploads).

As per coding guidelines: "Add logging for new flows" for files matching **/*.py.

📝 Proposed fix
 `@pytest.mark.p2`
 def test_documents_upload_contract_matrix(rest_client, create_dataset, tmp_path):
+    logger.info("Testing documents upload contract matrix")
     dataset_id = create_dataset("dataset_upload_contract")
 
+    logger.debug("Testing valid upload")
     valid_res = _upload_files(rest_client, dataset_id, [create_txt_file(tmp_path / "ragflow_test.txt")])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/restful_api/test_documents.py` around lines 315 - 388, The
test test_documents_upload_contract_matrix needs logging added for its major
scenarios; update the test function to emit debug/info logs at key steps (after
valid_res success, inside the file-type loop for each ext, after empty_res, for
duplicate_res and each repeat_res iteration, after max_name_res, after
special_res, after multi_res, and for concurrent upload results) using the
project logger (or pytest's caplog) so failures include context; locate the
function test_documents_upload_contract_matrix and insert concise log statements
referencing the response objects (valid_res, res, empty_res, duplicate_res,
repeat_res, max_name_res, special_res, multi_res) and the filename variables
(fp, duplicate_fp, max_name_fp, special_fp) to record status_code and payload
summaries.

Comment on lines +364 to +372
illegal_chars = '<>:"/\\|?*'
safe_filename = string.punctuation.translate(str.maketrans({char: "_" for char in illegal_chars}))
special_fp = tmp_path / f"{safe_filename}.txt"
special_fp.write_text("Sample text content")
special_res = _upload_files(rest_client, dataset_id, [special_fp])
assert special_res.status_code == 200
special_payload = special_res.json()
assert special_payload["code"] == 0, special_payload
assert special_payload["data"][0]["name"] == special_fp.name, special_payload

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Incorrect test logic for illegal character handling.

The current test creates a filename with illegal characters already replaced by underscores (line 365), then uploads that safe filename. This does not test how the API handles filenames with actual illegal characters.

If the intent is to verify that the API sanitizes illegal characters, the test should upload a file with illegal characters in the filename and verify they are replaced. If the intent is to verify that safe special characters are accepted, the variable naming (illegal_chars) is misleading.

🐛 Proposed fix to test actual illegal character handling

If you want to test illegal character sanitization:

-    illegal_chars = '<>:"/\\|?*'
-    safe_filename = string.punctuation.translate(str.maketrans({char: "_" for char in illegal_chars}))
-    special_fp = tmp_path / f"{safe_filename}.txt"
+    # Test that server sanitizes illegal filename characters
+    # Note: OS may prevent creating files with these chars, so we test via upload API with constructed filename
+    illegal_filename = "test<file>name.txt"
+    safe_content_fp = create_txt_file(tmp_path / "temp_for_illegal_test.txt")
+    with safe_content_fp.open("rb") as file_obj:
+        res = rest_client.post(
+            f"/datasets/{dataset_id}/documents",
+            files=[("file", (illegal_filename, file_obj))],
+        )
+    assert res.status_code == 200
+    payload = res.json()
+    assert payload["code"] == 0, payload
+    # Verify server replaced illegal chars with safe ones
+    uploaded_name = payload["data"][0]["name"]
+    assert "<" not in uploaded_name and ">" not in uploaded_name, payload

Or if testing safe punctuation acceptance:

-    illegal_chars = '<>:"/\\|?*'
-    safe_filename = string.punctuation.translate(str.maketrans({char: "_" for char in illegal_chars}))
+    # Test that server accepts safe punctuation characters
+    safe_punctuation = "!#$%&'()+,-.;=@[]^_`{}~"
+    safe_filename = f"test_{safe_punctuation}_file"
     special_fp = tmp_path / f"{safe_filename}.txt"
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/restful_api/test_documents.py` around lines 364 - 372, The
test builds a "safe" filename instead of uploading one containing illegal
characters (variables: illegal_chars, safe_filename, special_fp), so change the
test to create an actual filename containing the illegal characters (e.g.,
unsafe_name = f"file{illegal_chars}.txt" -> special_fp = tmp_path /
unsafe_name), upload via _upload_files(rest_client, dataset_id, [special_fp])
and then assert the API returned a sanitized name (compute expected_sanitized by
replacing each char in illegal_chars with '_' and compare to
special_payload["data"][0]["name"]); alternatively, if the intent was to test
accepting safe punctuation, rename illegal_chars to safe_punctuation to avoid
confusion.

Comment on lines +391 to +431
@pytest.mark.p2
def test_documents_upload_error_contract(rest_client, create_dataset, tmp_path):
invalid_dataset_res = _upload_files(
rest_client,
"invalid_dataset_id",
[create_txt_file(tmp_path / "invalid_dataset.txt")],
)
assert invalid_dataset_res.status_code == 200
invalid_dataset_payload = invalid_dataset_res.json()
assert invalid_dataset_payload["code"] == 102, invalid_dataset_payload
assert invalid_dataset_payload["message"] == "Can't find the dataset with ID invalid_dataset_id!", invalid_dataset_payload

for file_type in ("exe", "unknown"):
bad_file = tmp_path / f"ragflow_test.{file_type}"
bad_file.touch()
res = _upload_files(rest_client, create_dataset(f"dataset_upload_unsupported_{file_type}"), [bad_file])
assert res.status_code == 200, (file_type, res.text)
payload = res.json()
assert payload["code"] == 500, (file_type, payload)
assert payload["message"] == f"ragflow_test.{file_type}: This type of file has not been supported yet!", (file_type, payload)

dataset_id = create_dataset("dataset_upload_missing_empty")
missing_res = rest_client.post(f"/datasets/{dataset_id}/documents")
assert missing_res.status_code == 200
missing_payload = missing_res.json()
assert missing_payload["code"] == 101, missing_payload
assert missing_payload["message"] == "No file part!", missing_payload

fp = create_txt_file(tmp_path / "filename_empty.txt")
with fp.open("rb") as file_obj:
m = MultipartEncoder(fields=(("file", ("", file_obj)),))
filename_empty_res = requests.post(
url=f"{HOST_ADDRESS}/api/{VERSION}/datasets/{dataset_id}/documents",
headers={"Content-Type": m.content_type, "Authorization": f"Bearer {rest_client.token}"},
data=m,
timeout=30,
)
assert filename_empty_res.status_code == 200
filename_empty_payload = filename_empty_res.json()
assert filename_empty_payload["code"] == 101, filename_empty_payload
assert filename_empty_payload["message"] == "No file selected!", filename_empty_payload

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add logging for the upload error contract test.

Per coding guidelines, new test flows should include logging. Consider adding log statements for the different error scenarios (invalid dataset, unsupported types, missing file, empty filename).

As per coding guidelines: "Add logging for new flows" for files matching **/*.py.

📝 Proposed fix
 `@pytest.mark.p2`
 def test_documents_upload_error_contract(rest_client, create_dataset, tmp_path):
+    logger.info("Testing documents upload error contract")
+    logger.debug("Testing invalid dataset ID")
     invalid_dataset_res = _upload_files(
         rest_client,
         "invalid_dataset_id",
         [create_txt_file(tmp_path / "invalid_dataset.txt")],
     )
     assert invalid_dataset_res.status_code == 200
     invalid_dataset_payload = invalid_dataset_res.json()
     assert invalid_dataset_payload["code"] == 102, invalid_dataset_payload
     assert invalid_dataset_payload["message"] == "Can't find the dataset with ID invalid_dataset_id!", invalid_dataset_payload
 
+    logger.debug("Testing unsupported file types")
     for file_type in ("exe", "unknown"):
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/restful_api/test_documents.py` around lines 391 - 431, In
test_documents_upload_error_contract, add logging calls to record each error
scenario before assertions: obtain a module logger (e.g., logger =
logging.getLogger(__name__)), then log the responses and payloads for the
invalid dataset case (invalid_dataset_res / invalid_dataset_payload), each
unsupported file type loop iteration (res / payload and the file_type), the
missing file case (missing_res / missing_payload), and the empty filename case
(filename_empty_res / filename_empty_payload); use logger.info or logger.debug
with descriptive messages so the test output shows the request target and
returned payloads for debugging while keeping assertions unchanged.

@codecov

codecov Bot commented May 27, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (3619cec) to head (8de35ff).
⚠️ Report is 8 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15277   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
test/testcases/restful_api/test_documents.py (1)

576-578: 💤 Low value

Imprecise assertion for deleted count.

The assertion body["data"]["deleted"] in (len(document_ids), len(document_ids[:1])) evaluates to in (3, 1) for all success scenarios, but doesn't distinguish between "delete one" (expecting 1) and "delete all" (expecting 3). Consider making this more explicit per scenario.

♻️ Suggested improvement

Add an expected_deleted field to each scenario tuple:

     scenarios = [
-        ("empty object", lambda ids: {}, 102, "should either provide doc ids or set delete_all(true)", 3),
-        ("empty ids", lambda ids: {"ids": []}, 102, "should either provide doc ids or set delete_all(true)", 3),
-        ("invalid id only", lambda ids: {"ids": ["invalid_id"]}, 102, "These documents do not belong to dataset", 3),
-        ("not json object", lambda ids: "not json", 101, "Invalid request payload: expected object, got str", 3),
-        ("delete one", lambda ids: {"ids": ids[:1]}, 0, "", 2),
-        ("delete all by ids", lambda ids: {"ids": ids}, 0, "", 0),
-        ("delete_all flag", lambda ids: {"delete_all": True}, 0, "", 0),
+        ("empty object", lambda ids: {}, 102, "should either provide doc ids or set delete_all(true)", 3, None),
+        ("empty ids", lambda ids: {"ids": []}, 102, "should either provide doc ids or set delete_all(true)", 3, None),
+        ("invalid id only", lambda ids: {"ids": ["invalid_id"]}, 102, "These documents do not belong to dataset", 3, None),
+        ("not json object", lambda ids: "not json", 101, "Invalid request payload: expected object, got str", 3, None),
+        ("delete one", lambda ids: {"ids": ids[:1]}, 0, "", 2, 1),
+        ("delete all by ids", lambda ids: {"ids": ids}, 0, "", 0, 3),
+        ("delete_all flag", lambda ids: {"delete_all": True}, 0, "", 0, 3),
     ]
-    for scenario_name, payload_builder, expected_code, expected_message, expected_total in scenarios:
+    for scenario_name, payload_builder, expected_code, expected_message, expected_total, expected_deleted in scenarios:
         ...
         if expected_code != 0:
             assert expected_message in body["message"], (scenario_name, body)
         else:
-            assert body["data"]["deleted"] in (len(document_ids), len(document_ids[:1])), (scenario_name, body)
+            assert body["data"]["deleted"] == expected_deleted, (scenario_name, body)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/restful_api/test_documents.py` around lines 576 - 578, The
current assertion for deleted count is too permissive; update the test scenarios
to include an explicit expected_deleted value per scenario and assert equality
against body["data"]["deleted"] instead of membership in (len(document_ids),
len(document_ids[:1])); locate where scenario tuples are defined for the tests
that set scenario_name/document_ids and add an expected_deleted element, then
change the assertion in test_documents.py (the branch using document_ids,
scenario_name, body) to assert body["data"]["deleted"] == expected_deleted so
"delete one" and "delete all" are unambiguous.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/testcases/restful_api/test_documents.py`:
- Around line 963-966: The concurrent stop assertions are flaky because a stop
may race with parsing and return code 102 ("already completed"); update the
assertion that checks stop responses so it accepts either success or
already-completed instead of only 0. Locate the block where `responses =
[future.result() for future in futures]` and replace the `assert
all(res.json()["code"] == 0 for res in responses)` check with an assertion that
each `res.json()["code"]` is in the allowed set (e.g., {0, 102}), mirroring the
handling in `test_documents_stop_parse_contract_matrix`, so concurrent stop
requests don't intermittently fail.

---

Nitpick comments:
In `@test/testcases/restful_api/test_documents.py`:
- Around line 576-578: The current assertion for deleted count is too
permissive; update the test scenarios to include an explicit expected_deleted
value per scenario and assert equality against body["data"]["deleted"] instead
of membership in (len(document_ids), len(document_ids[:1])); locate where
scenario tuples are defined for the tests that set scenario_name/document_ids
and add an expected_deleted element, then change the assertion in
test_documents.py (the branch using document_ids, scenario_name, body) to assert
body["data"]["deleted"] == expected_deleted so "delete one" and "delete all" are
unambiguous.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e71f8afc-94c7-44db-854e-189db97b159c

📥 Commits

Reviewing files that changed from the base of the PR and between 102923c and 8de35ff.

📒 Files selected for processing (1)
  • test/testcases/restful_api/test_documents.py

Comment on lines +963 to +966
responses = [future.result() for future in futures]
assert len(responses) == len(doc_ids), responses
assert all(res.status_code == 200 for res in responses)
assert all(res.json()["code"] == 0 for res in responses)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Potential test flakiness in concurrent stop assertions.

The assertion assert all(res.json()["code"] == 0 for res in responses) assumes all stop requests succeed. However, if document parsing completes before the stop request arrives (a race condition), the API may return code 102 with "already completed" message, as handled in test_documents_stop_parse_contract_matrix (line 916-918). This could cause intermittent test failures.

🐛 Proposed fix
-    assert all(res.json()["code"] == 0 for res in responses)
+    for res in responses:
+        body = res.json()
+        assert body["code"] in (0, 102), body
+        if body["code"] == 102:
+            assert "already completed" in body["message"], body
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/restful_api/test_documents.py` around lines 963 - 966, The
concurrent stop assertions are flaky because a stop may race with parsing and
return code 102 ("already completed"); update the assertion that checks stop
responses so it accepts either success or already-completed instead of only 0.
Locate the block where `responses = [future.result() for future in futures]` and
replace the `assert all(res.json()["code"] == 0 for res in responses)` check
with an assertion that each `res.json()["code"]` is in the allowed set (e.g.,
{0, 102}), mirroring the handling in
`test_documents_stop_parse_contract_matrix`, so concurrent stop requests don't
intermittently fail.

@asiroliu
asiroliu merged commit 1f34a18 into infiniflow:main May 27, 2026
1 check passed
@6ba3i
6ba3i deleted the restful4 branch May 27, 2026 05:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants