Repository navigation
Feat: add new tests and tescases for restful api suite - #15038
Conversation
📝 WalkthroughWalkthroughThis PR adds comprehensive RESTful API test coverage across three test files: chunk CRUD endpoints, a Dify retrieval route unit test harness, and integration tests for the /retrieval endpoint. Together, these tests validate auth, parameter contracts, concurrency, ownership/authorization, pagination, and data-mutation behavior across multiple REST APIs. ChangesChunk Endpoint Contract Testing
Dify Retrieval Route Unit Testing
Retrieval Endpoint Integration Testing
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (1 warning, 2 inconclusive)
✅ Passed checks (2 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (6)
test/testcases/restful_api/test_dify_retrieval_routes_unit.py (1)
70-251: ⚡ Quick winAdd debug logging around dynamic module loading/stubbing flow.
This helper introduces a complex new flow (module injection + dynamic import) but has no trace logs, which makes CI diagnosis harder when import-time failures happen. Add lightweight debug logs at key steps (module path resolution, stub registration, module execution).
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_dify_retrieval_routes_unit.py` around lines 70 - 251, The helper _load_dify_retrieval_module() performs complex dynamic module creation and import but has no diagnostics; add lightweight debug logs using the standard logging module at key steps: after computing repo_root and module_path, after creating/registering major stubs (deepdoc/deepdoc.parser, api.db.services.tenant_llm_service, api.db.services.llm_service, api.db.joint_services.tenant_model_service), after setting module.manager = _DummyManager, and immediately before/after spec.loader.exec_module(module) to capture import-time errors; use logging.getLogger(__name__) and logger.debug calls referencing those symbols (repo_root, module_path, monkeypatch.setitem registrations, module.manager, spec.loader.exec_module) so CI can show where failures occur.test/testcases/restful_api/test_retrieval.py (2)
117-151: ⚡ Quick winAdd diagnostic logging to new polling helpers.
These are new retrying flows; without logs, timeout failures are hard to triage in CI (no status/payload context per attempt).
Proposed diff
+import logging @@ +logger = logging.getLogger(__name__) @@ def _retrieval_has_question(rest_client, dataset_id, question): res = rest_client.post("/retrieval", json={"question": question, "dataset_ids": [dataset_id]}) if res.status_code != 200: + logger.debug("retrieval_has_question: status=%s body=%s", res.status_code, res.text) return False payload = res.json() if payload["code"] != 0: + logger.debug("retrieval_has_question: code=%s payload=%s", payload.get("code"), payload) return False @@ def _retrieval_has_chunks(rest_client, dataset_id, question, chunk_ids): @@ if res.status_code != 200: + logger.debug("retrieval_has_chunks: status=%s body=%s", res.status_code, res.text) return False @@ if payload["code"] != 0: + logger.debug("retrieval_has_chunks: code=%s payload=%s", payload.get("code"), payload) return False @@ def _retrieval_lacks_chunks(rest_client, dataset_id, question, chunk_ids): @@ if res.status_code != 200: + logger.debug("retrieval_lacks_chunks: status=%s body=%s", res.status_code, res.text) return False @@ if payload["code"] != 0: + logger.debug("retrieval_lacks_chunks: code=%s payload=%s", payload.get("code"), payload) return FalseAs 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_retrieval.py` around lines 117 - 151, The three retry helpers (_retrieval_has_question, _retrieval_has_chunks, _retrieval_lacks_chunks) lack per-attempt diagnostic logs; update each to log the REST call outcome and key variables on every attempt (e.g., log res.status_code, any JSON payload or parse error, computed retrieved_ids and expected_ids, and a short message indicating which check is being evaluated) so CI timeouts include context. Use the project's logger (or Python logging) consistent with other tests, log at debug/info level for successful attempts and warn on non-200 or non-zero payload["code"], and include function name and the question/dataset_id in the message to make failures triageable.
313-318: ⚡ Quick winAdd explicit assertions to polling helper calls for test clarity.
The
@wait_fordecorator raisesAssertionErroron timeout, so these calls technically fail the test if expectations aren't met. However, ignoring theTruereturn value obscures intent and makes the test fragile to decorator changes. Add explicit assertions to make test expectations unambiguous.Suggested changes
- _retrieval_has_chunks(rest_client, dataset_id, content, [chunk_id]) + assert _retrieval_has_chunks(rest_client, dataset_id, content, [chunk_id]) - _retrieval_lacks_chunks(rest_client, dataset_id, content, [chunk_id]) + assert _retrieval_lacks_chunks(rest_client, dataset_id, content, [chunk_id]) - _retrieval_has_chunks(rest_client, dataset_id, "BATCH_DELETE_TEST_CHUNK", chunk_ids) + assert _retrieval_has_chunks(rest_client, dataset_id, "BATCH_DELETE_TEST_CHUNK", chunk_ids) - _retrieval_lacks_chunks(rest_client, dataset_id, "BATCH_DELETE_TEST_CHUNK", chunk_ids) + assert _retrieval_lacks_chunks(rest_client, dataset_id, "BATCH_DELETE_TEST_CHUNK", chunk_ids)Also applies to: 333-338
🤖 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_retrieval.py` around lines 313 - 318, The test calls to the polling helpers _retrieval_has_chunks and _retrieval_lacks_chunks rely on `@wait_for` raising on timeout but do not assert their return value; update the test to explicitly assert the helpers succeeded (e.g., assert _retrieval_has_chunks(...) and assert _retrieval_lacks_chunks(...)) so the intent is clear and resilient to decorator changes, and apply the same explicit-assert change for the other occurrence around lines 333-338 as well.test/testcases/restful_api/test_chunks.py (3)
33-66: ⚡ Quick winAdd lightweight logging in new reset/polling helpers.
These new orchestration flows are central to many tests; adding debug logs will significantly improve failure triage.
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 33 - 66, The new helpers _reset_chunk_batch and _chunk_count lack diagnostic logs; import and configure the module-level logger (e.g., import logging; logger = logging.getLogger(__name__)) and add lightweight debug/info logs in _reset_chunk_batch to record actions and responses (cleanup/delete start/result, baseline upload id, each chunk POST id and index, final expected vs actual counts) and in _chunk_count to log response status, payload code, and the computed totals so test failures surface useful context; instrument using logger.debug/info calls referencing the functions _reset_chunk_batch and _chunk_count.
180-247: ⚡ Quick winException message equality is too runtime-fragile for contract tests.
Several cases compare full Python exception text; these strings can vary by Python/runtime. Prefer substring checks for error-shape validation.
Proposed patch pattern
- assert body["message"] == expected_message, (scenario_name, body) + assert expected_message in body.get("message", ""), (scenario_name, body)Also applies to: 584-611, 648-714
🤖 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 180 - 247, The test test_chunk_add_keyword_question_and_tag_contract compares full Python exception text (body["message"] == expected_message), which is fragile; change the failure-path assertions so when expected_message is non-empty you assert that expected_message is a substring of body["message"] (e.g., expected_message in body["message"]) instead of exact equality, and keep exact equality only for empty/zero-message cases; update the checks around body["message"] in test_chunk_add_keyword_question_and_tag_contract (and the other similar tests mentioned) to use substring membership for runtime-generated exception texts like TypeError(...) or other dynamic messages.
131-165: ⚡ Quick winAvoid exact equality on framework-formatted unauthorized messages.
Asserting the full string representation is brittle across framework/version changes; assert a stable fragment instead.
Proposed patch
- assert payload["message"] == "<Unauthorized '401: Unauthorized'>", (scenario_name, payload) + assert "Unauthorized" in payload.get("message", ""), (scenario_name, payload)Also applies to: 637-646
🤖 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 131 - 165, The tests test_chunk_add_requires_auth, test_chunk_delete_requires_auth and test_chunk_list_requires_auth assert the full framework-formatted unauthorized string which is brittle; update each assertion that checks payload["message"] to assert a stable fragment instead (for example: assert "Unauthorized" in payload["message"] or assert "401" in payload["message"]) so the tests validate the intent without relying on exact framework formatting.
🤖 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_chunks.py`:
- Around line 488-492: After asserting the bulk delete response code, actually
verify the chunks were removed: iterate over the chunk ids in bulk_ids and for
each call the API to fetch that chunk (use rest_client.get with the appropriate
chunk retrieval endpoint used elsewhere in these tests, e.g., GET on base_path +
f"/{chunk_id}" or the existing single-chunk retrieval helper) and assert the
response indicates non-existence (404 or no result); update the test after the
bulk_payload["code"] == 0 assertion to perform these per-chunk retrieval checks
using rest_client.get and asserting failure/absence for each chunk_id from
bulk_ids.
- Line 64: The call to _chunk_count(rest_client, base_path, count + 1) is used
as a precondition but its return value is ignored; change the test to capture
and assert the return (e.g., result = _chunk_count(rest_client, base_path, count
+ 1); assert result) so the test fails clearly when the wait condition times
out—update the invocation in the test to assert the boolean/expected value
returned by _chunk_count using the existing rest_client and base_path
parameters.
---
Nitpick comments:
In `@test/testcases/restful_api/test_chunks.py`:
- Around line 33-66: The new helpers _reset_chunk_batch and _chunk_count lack
diagnostic logs; import and configure the module-level logger (e.g., import
logging; logger = logging.getLogger(__name__)) and add lightweight debug/info
logs in _reset_chunk_batch to record actions and responses (cleanup/delete
start/result, baseline upload id, each chunk POST id and index, final expected
vs actual counts) and in _chunk_count to log response status, payload code, and
the computed totals so test failures surface useful context; instrument using
logger.debug/info calls referencing the functions _reset_chunk_batch and
_chunk_count.
- Around line 180-247: The test test_chunk_add_keyword_question_and_tag_contract
compares full Python exception text (body["message"] == expected_message), which
is fragile; change the failure-path assertions so when expected_message is
non-empty you assert that expected_message is a substring of body["message"]
(e.g., expected_message in body["message"]) instead of exact equality, and keep
exact equality only for empty/zero-message cases; update the checks around
body["message"] in test_chunk_add_keyword_question_and_tag_contract (and the
other similar tests mentioned) to use substring membership for runtime-generated
exception texts like TypeError(...) or other dynamic messages.
- Around line 131-165: The tests test_chunk_add_requires_auth,
test_chunk_delete_requires_auth and test_chunk_list_requires_auth assert the
full framework-formatted unauthorized string which is brittle; update each
assertion that checks payload["message"] to assert a stable fragment instead
(for example: assert "Unauthorized" in payload["message"] or assert "401" in
payload["message"]) so the tests validate the intent without relying on exact
framework formatting.
In `@test/testcases/restful_api/test_dify_retrieval_routes_unit.py`:
- Around line 70-251: The helper _load_dify_retrieval_module() performs complex
dynamic module creation and import but has no diagnostics; add lightweight debug
logs using the standard logging module at key steps: after computing repo_root
and module_path, after creating/registering major stubs (deepdoc/deepdoc.parser,
api.db.services.tenant_llm_service, api.db.services.llm_service,
api.db.joint_services.tenant_model_service), after setting module.manager =
_DummyManager, and immediately before/after spec.loader.exec_module(module) to
capture import-time errors; use logging.getLogger(__name__) and logger.debug
calls referencing those symbols (repo_root, module_path, monkeypatch.setitem
registrations, module.manager, spec.loader.exec_module) so CI can show where
failures occur.
In `@test/testcases/restful_api/test_retrieval.py`:
- Around line 117-151: The three retry helpers (_retrieval_has_question,
_retrieval_has_chunks, _retrieval_lacks_chunks) lack per-attempt diagnostic
logs; update each to log the REST call outcome and key variables on every
attempt (e.g., log res.status_code, any JSON payload or parse error, computed
retrieved_ids and expected_ids, and a short message indicating which check is
being evaluated) so CI timeouts include context. Use the project's logger (or
Python logging) consistent with other tests, log at debug/info level for
successful attempts and warn on non-200 or non-zero payload["code"], and include
function name and the question/dataset_id in the message to make failures
triageable.
- Around line 313-318: The test calls to the polling helpers
_retrieval_has_chunks and _retrieval_lacks_chunks rely on `@wait_for` raising on
timeout but do not assert their return value; update the test to explicitly
assert the helpers succeeded (e.g., assert _retrieval_has_chunks(...) and assert
_retrieval_lacks_chunks(...)) so the intent is clear and resilient to decorator
changes, and apply the same explicit-assert change for the other occurrence
around lines 333-338 as well.
🪄 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: 52f546f9-4470-4170-b8db-8d7ebbcb2f26
📒 Files selected for processing (3)
test/testcases/restful_api/test_chunks.pytest/testcases/restful_api/test_dify_retrieval_routes_unit.pytest/testcases/restful_api/test_retrieval.py
| assert payload["code"] == 0, (index, payload) | ||
| chunk_ids.append(_assert_created_chunk_id(payload)) | ||
|
|
||
| _chunk_count(rest_client, base_path, count + 1) |
There was a problem hiding this comment.
Assert the chunk-count wait outcome explicitly.
_chunk_count(...) is called for precondition sync, but its return value is ignored. Making it explicit prevents silent continuation when the wait condition fails.
Proposed patch
- _chunk_count(rest_client, base_path, count + 1)
+ assert _chunk_count(rest_client, base_path, count + 1)📝 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.
| _chunk_count(rest_client, base_path, count + 1) | |
| assert _chunk_count(rest_client, base_path, count + 1) |
🤖 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` at line 64, The call to
_chunk_count(rest_client, base_path, count + 1) is used as a precondition but
its return value is ignored; change the test to capture and assert the return
(e.g., result = _chunk_count(rest_client, base_path, count + 1); assert result)
so the test fails clearly when the wait condition times out—update the
invocation in the test to assert the boolean/expected value returned by
_chunk_count using the existing rest_client and base_path parameters.
| bulk_res = rest_client.delete(base_path, json={"chunk_ids": bulk_ids}) | ||
| assert bulk_res.status_code == 200 | ||
| bulk_payload = bulk_res.json() | ||
| assert bulk_payload["code"] == 0, bulk_payload | ||
|
|
There was a problem hiding this comment.
Bulk-delete path should assert final state, not only response code.
The second bulk-delete scenario stops at code == 0 and doesn’t verify chunks are actually gone.
Proposed patch
bulk_res = rest_client.delete(base_path, json={"chunk_ids": bulk_ids})
assert bulk_res.status_code == 200
bulk_payload = bulk_res.json()
assert bulk_payload["code"] == 0, bulk_payload
+ after_bulk_payload = rest_client.get(base_path, params={"page_size": 200}).json()
+ assert after_bulk_payload["code"] == 0, after_bulk_payload
+ assert after_bulk_payload["data"]["total"] == 0, after_bulk_payload📝 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.
| bulk_res = rest_client.delete(base_path, json={"chunk_ids": bulk_ids}) | |
| assert bulk_res.status_code == 200 | |
| bulk_payload = bulk_res.json() | |
| assert bulk_payload["code"] == 0, bulk_payload | |
| bulk_res = rest_client.delete(base_path, json={"chunk_ids": bulk_ids}) | |
| assert bulk_res.status_code == 200 | |
| bulk_payload = bulk_res.json() | |
| assert bulk_payload["code"] == 0, bulk_payload | |
| after_bulk_payload = rest_client.get(base_path, params={"page_size": 200}).json() | |
| assert after_bulk_payload["code"] == 0, after_bulk_payload | |
| assert after_bulk_payload["data"]["total"] == 0, after_bulk_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_chunks.py` around lines 488 - 492, After
asserting the bulk delete response code, actually verify the chunks were
removed: iterate over the chunk ids in bulk_ids and for each call the API to
fetch that chunk (use rest_client.get with the appropriate chunk retrieval
endpoint used elsewhere in these tests, e.g., GET on base_path + f"/{chunk_id}"
or the existing single-chunk retrieval helper) and assert the response indicates
non-existence (404 or no result); update the test after the bulk_payload["code"]
== 0 assertion to perform these per-chunk retrieval checks using rest_client.get
and asserting failure/absence for each chunk_id from bulk_ids.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15038 +/- ##
=======================================
Coverage 93.12% 93.12%
=======================================
Files 10 10
Lines 713 713
Branches 116 116
=======================================
Hits 664 664
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
extend restful api suite
Type of change