Repository navigation
Feat: add new tests and tescases for restful api suite - #15347
Conversation
📝 WalkthroughWalkthroughAdds and extends unit and contract tests across REST API modules: file service tests (upload/move/delete/permissions), LLM routes (list/factories/add with factory-specific key handling), message/memory routes (add/get validation), session contracts (create/list/update/delete concurrency and validation), and a retrieval test fixture update. ChangesREST API Unit & Contract Testing
Sequence Diagram(s)(omitted — changes are test additions and isolated app/module loading; no multi-component runtime control flow added beyond import stubbing) Estimated Code Review Effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested Labels
Suggested Reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 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: 3
🧹 Nitpick comments (3)
test/testcases/restful_api/test_llm_routes_unit.py (2)
706-716: ⚡ Quick winExtract shared invalid-auth contract checks into a helper.
The invalid-auth matrix and assertions are duplicated across both live tests; a shared helper will reduce drift and future maintenance cost.
Refactor sketch
+def _assert_invalid_auth_cases(url: str): + invalid_auth_cases = [ + (None, 401, "Unauthorized"), + (RAGFlowWebApiAuth("invalid-token"), 401, "Unauthorized"), + ] + for auth_obj, expected_code, expected_fragment in invalid_auth_cases: + res = requests.get(url, auth=auth_obj, timeout=30) + assert res.status_code == 401 + payload = res.json() + assert payload["code"] == expected_code, payload + assert expected_fragment in payload["message"], payload + `@pytest.mark.p2` def test_llm_factories_live_auth_contract(): llm_url = f"{HOST_ADDRESS}/{VERSION}/llm/factories" - invalid_auth_cases = [...] - for auth_obj, expected_code, expected_message in invalid_auth_cases: - ... + _assert_invalid_auth_cases(llm_url)Also applies to: 727-737
🤖 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_llm_routes_unit.py` around lines 706 - 716, Extract the duplicated invalid-auth matrix and assertions into a shared helper function (e.g., assert_invalid_auth_contract) and replace both inline blocks that define invalid_auth_cases and perform the three assertions with calls to that helper; the helper should accept the target URL (llm_url), a requests auth object (or None), or iterate a provided list of (auth_obj, expected_code, expected_message) tuples, perform the GET (requests.get(..., timeout=30)), assert status_code == 401, and assert payload["code"] and payload["message"] match expected values; update the two occurrences around the loops (the block using invalid_auth_cases and the similar block at 727-737) to call this single helper to remove duplication.
122-257: ⚡ Quick winAdd logging for the newly introduced flows in this test module.
Please add lightweight logging around dynamic module load/setup and live contract request paths so failures are easier to triage in CI.
As per coding guidelines, "Add logging for new flows".
Also applies to: 703-743
🤖 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_llm_routes_unit.py` around lines 122 - 257, Add lightweight logging statements to trace dynamic module loading and request-path setup: import and use the logging module inside the test helpers and log at DEBUG/INFO in _load_llm_app (log when entering, after building stubs, before and after spec.loader.exec_module(module), and the resolved module_path and module.manager), and add brief logs in _set_request_json (when setting the fake get_request_json) and in _run (when running the coroutine and on completion/exception). Ensure logs reference the helper names (_load_llm_app, _set_request_json, _run) so CI failures show which step failed.test/testcases/restful_api/test_sessions.py (1)
426-433: ⚡ Quick winAvoid backend-specific exception text assertions in contract tests.
These cases assert DB/runtime exception strings (e.g.,
ProgrammingError(1064,AttributeError(...), fullValueError(...)). That makes tests flaky across database engines, driver versions, and Python runtime formatting. Assert stable API contract fields (code) and broad semantic message fragments instead of engine-specific internals.Proposed assertion hardening
- ("page negative", {"page": -1, "page_size": 2}, 100, 0, "ProgrammingError(1064"), - ("page alpha", {"page": "a", "page_size": 2}, 100, 0, "ValueError(\"invalid literal for int() with base 10: 'a'\")"), + ("page negative", {"page": -1, "page_size": 2}, 100, 0, "ProgrammingError"), + ("page alpha", {"page": "a", "page_size": 2}, 100, 0, "invalid literal for int()"), @@ - ("page_size alpha", {"page_size": "a"}, 100, 0, "ValueError(\"invalid literal for int() with base 10: 'a'\")"), + ("page_size alpha", {"page_size": "a"}, 100, 0, "invalid literal for int()"), @@ - ("orderby unknown", {"orderby": "unknown", "page_size": 30}, None, None, None, "AttributeError(\"type object 'Conversation' has no attribute 'unknown'\")"), + ("orderby unknown", {"orderby": "unknown", "page_size": 30}, None, None, None, "has no attribute"),Also applies to: 450-470
🤖 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_sessions.py` around lines 426 - 433, The test tuples in test_sessions.py that currently assert backend/runtime-specific exception text (examples: the entries "page negative", "page alpha", "page_size alpha" and similar around lines 450-470) should be hardened: stop matching DB/driver/Python formatted exception strings and instead assert the stable API contract fields (e.g., an error "code" value) and only check for broad, semantic message fragments (e.g., contains "invalid", "page", "page_size", or "must be a positive integer"). Update the affected test cases (the tuples used by the parametrized test) to expect the standard error code and a short semantic substring rather than the full backend exception text, and apply the same change to the other affected cases referenced in the comment.
🤖 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_file_routes_unit.py`:
- Around line 696-697: The create_folder test stub signature doesn't match the
real service's upload_file call and can raise TypeError; change the stub for
create_folder to accept the full parameter set used by upload_file (e.g., def
create_folder(file, parent_id, names, len_id, *args, **kwargs): return
SimpleNamespace(id=parent_id, name=str(parent_id))) or use *args, **kwargs to
swallow extra args so it mirrors the real service contract and prevents
signature mismatch errors during tests.
- Around line 638-750: The new test loader function _load_file_api_service lacks
logging; add lightweight logging calls (using the logging module) at key points:
on entry to _load_file_api_service, after key steps (e.g., after mocking major
modules like "api", "api.db.services.file_service" and after
spec.loader.exec_module(module)), and in an exception handler around
spec.loader.exec_module to log the full exception; reference the function name
_load_file_api_service and the call spec.loader.exec_module(module) when adding
these logs so failures in CI are easier to triage.
In `@test/testcases/restful_api/test_llm_routes_unit.py`:
- Around line 707-709: The test currently asserts exact framework-generated
message strings (e.g., "<Unauthorized '401: Unauthorized'>") which is brittle;
update the assertions in the failing test cases (the tuples containing (None,
401, "<Unauthorized '401: Unauthorized'>") and
(RAGFlowWebApiAuth("invalid-token"), 401, "<Unauthorized '401: Unauthorized'>")
and the similar block at 728-730) to only assert the HTTP status is 401 and that
the response message contains "Unauthorized" (e.g., use a contains/substring
check or regex) rather than an exact equality match so variations in framework
formatting won't break the test.
---
Nitpick comments:
In `@test/testcases/restful_api/test_llm_routes_unit.py`:
- Around line 706-716: Extract the duplicated invalid-auth matrix and assertions
into a shared helper function (e.g., assert_invalid_auth_contract) and replace
both inline blocks that define invalid_auth_cases and perform the three
assertions with calls to that helper; the helper should accept the target URL
(llm_url), a requests auth object (or None), or iterate a provided list of
(auth_obj, expected_code, expected_message) tuples, perform the GET
(requests.get(..., timeout=30)), assert status_code == 401, and assert
payload["code"] and payload["message"] match expected values; update the two
occurrences around the loops (the block using invalid_auth_cases and the similar
block at 727-737) to call this single helper to remove duplication.
- Around line 122-257: Add lightweight logging statements to trace dynamic
module loading and request-path setup: import and use the logging module inside
the test helpers and log at DEBUG/INFO in _load_llm_app (log when entering,
after building stubs, before and after spec.loader.exec_module(module), and the
resolved module_path and module.manager), and add brief logs in
_set_request_json (when setting the fake get_request_json) and in _run (when
running the coroutine and on completion/exception). Ensure logs reference the
helper names (_load_llm_app, _set_request_json, _run) so CI failures show which
step failed.
In `@test/testcases/restful_api/test_sessions.py`:
- Around line 426-433: The test tuples in test_sessions.py that currently assert
backend/runtime-specific exception text (examples: the entries "page negative",
"page alpha", "page_size alpha" and similar around lines 450-470) should be
hardened: stop matching DB/driver/Python formatted exception strings and instead
assert the stable API contract fields (e.g., an error "code" value) and only
check for broad, semantic message fragments (e.g., contains "invalid", "page",
"page_size", or "must be a positive integer"). Update the affected test cases
(the tuples used by the parametrized test) to expect the standard error code and
a short semantic substring rather than the full backend exception text, and
apply the same change to the other affected cases referenced in the comment.
🪄 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: fb93cdcb-f461-490d-9f4d-9502b8171735
📒 Files selected for processing (4)
test/testcases/restful_api/test_file_routes_unit.pytest/testcases/restful_api/test_llm_routes_unit.pytest/testcases/restful_api/test_message_routes_unit.pytest/testcases/restful_api/test_sessions.py
| create_folder=lambda _file, parent_id, _names, _len_id: SimpleNamespace(id=parent_id, name=str(parent_id)), | ||
| query=lambda **_kwargs: [], |
There was a problem hiding this comment.
Fix create_folder stub signature to match service call contract.
The stub currently accepts fewer args than upload_file passes in the real service path, which can trigger TypeError in non-overridden upload scenarios.
Proposed fix
- create_folder=lambda _file, parent_id, _names, _len_id: SimpleNamespace(id=parent_id, name=str(parent_id)),
+ create_folder=lambda _file, parent_id, _names, _len_id, *_args: SimpleNamespace(id=parent_id, name=str(parent_id)),📝 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.
| create_folder=lambda _file, parent_id, _names, _len_id: SimpleNamespace(id=parent_id, name=str(parent_id)), | |
| query=lambda **_kwargs: [], | |
| create_folder=lambda _file, parent_id, _names, _len_id, *_args: SimpleNamespace(id=parent_id, name=str(parent_id)), | |
| query=lambda **_kwargs: [], |
🤖 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_file_routes_unit.py` around lines 696 - 697,
The create_folder test stub signature doesn't match the real service's
upload_file call and can raise TypeError; change the stub for create_folder to
accept the full parameter set used by upload_file (e.g., def create_folder(file,
parent_id, names, len_id, *args, **kwargs): return SimpleNamespace(id=parent_id,
name=str(parent_id))) or use *args, **kwargs to swallow extra args so it mirrors
the real service contract and prevents signature mismatch errors during tests.
| (None, 401, "<Unauthorized '401: Unauthorized'>"), | ||
| (RAGFlowWebApiAuth("invalid-token"), 401, "<Unauthorized '401: Unauthorized'>"), | ||
| ] |
There was a problem hiding this comment.
Avoid exact-match assertions for framework-generated unauthorized messages.
These assertions are brittle and can fail on harmless framework/message formatting changes. Keep strict checks on HTTP status and payload code, and make message checks partial (e.g., contains "Unauthorized").
Also applies to: 728-730
🤖 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_llm_routes_unit.py` around lines 707 - 709,
The test currently asserts exact framework-generated message strings (e.g.,
"<Unauthorized '401: Unauthorized'>") which is brittle; update the assertions in
the failing test cases (the tuples containing (None, 401, "<Unauthorized '401:
Unauthorized'>") and (RAGFlowWebApiAuth("invalid-token"), 401, "<Unauthorized
'401: Unauthorized'>") and the similar block at 728-730) to only assert the HTTP
status is 401 and that the response message contains "Unauthorized" (e.g., use a
contains/substring check or regex) rather than an exact equality match so
variations in framework formatting won't break the test.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15347 +/- ##
=======================================
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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
test/testcases/restful_api/test_retrieval.py (1)
19-19:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRemove unused
HOST_ADDRESSimport to unblock RuffLine 19 imports
HOST_ADDRESSbut it is no longer used, and this is currently failing CI (ruff checkF401).Suggested fix
-from test.testcases.configs import HOST_ADDRESS, INVALID_API_TOKEN, VERSION +from test.testcases.configs import INVALID_API_TOKEN, VERSIONAs per coding guidelines,
**/*.py: Userufffor Python linting and formatting (ruff checkandruff format).🤖 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` at line 19, The import statement in test_retrieval.py currently includes an unused symbol HOST_ADDRESS which causes a Ruff F401 error; edit the import from test.testcases.configs (the line importing HOST_ADDRESS, INVALID_API_TOKEN, VERSION) and remove HOST_ADDRESS so only the used names (INVALID_API_TOKEN and VERSION) are imported to resolve the lint failure.
🤖 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.
Outside diff comments:
In `@test/testcases/restful_api/test_retrieval.py`:
- Line 19: The import statement in test_retrieval.py currently includes an
unused symbol HOST_ADDRESS which causes a Ruff F401 error; edit the import from
test.testcases.configs (the line importing HOST_ADDRESS, INVALID_API_TOKEN,
VERSION) and remove HOST_ADDRESS so only the used names (INVALID_API_TOKEN and
VERSION) are imported to resolve the lint failure.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 0aa87260-4266-48f4-89d0-c19228b192c5
📒 Files selected for processing (1)
test/testcases/restful_api/test_retrieval.py
|
Actionable comments posted: 0 |
There was a problem hiding this comment.
♻️ Duplicate comments (1)
test/testcases/restful_api/test_file_routes_unit.py (1)
702-702:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
create_folderstub signature still mismatches the service call contract.The default stub accepts only four positional args, while the real
upload_filepath passes more (the success test at Line 800 already works around this with*_args). Any non-overridden upload path hitting this stub will raiseTypeError.Proposed fix
- create_folder=lambda _file, parent_id, _names, _len_id: SimpleNamespace(id=parent_id, name=str(parent_id)), + create_folder=lambda _file, parent_id, _names, _len_id, *_args: SimpleNamespace(id=parent_id, name=str(parent_id)),🤖 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_file_routes_unit.py` at line 702, The create_folder test stub currently defines a signature of (lambda _file, parent_id, _names, _len_id: ...) which doesn't match how the real service is called from upload_file and causes TypeError when extra positional/keyword args are passed; update the stub used in test_file_routes_unit.py (the create_folder lambda) to accept a flexible signature (e.g., *args, **kwargs or at least include the extra parameters) and return the same SimpleNamespace(id=parent_id, name=str(parent_id)) so non-overridden upload paths don't raise when upload_file calls create_folder with additional arguments.
🤖 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.
Duplicate comments:
In `@test/testcases/restful_api/test_file_routes_unit.py`:
- Line 702: The create_folder test stub currently defines a signature of (lambda
_file, parent_id, _names, _len_id: ...) which doesn't match how the real service
is called from upload_file and causes TypeError when extra positional/keyword
args are passed; update the stub used in test_file_routes_unit.py (the
create_folder lambda) to accept a flexible signature (e.g., *args, **kwargs or
at least include the extra parameters) and return the same
SimpleNamespace(id=parent_id, name=str(parent_id)) so non-overridden upload
paths don't raise when upload_file calls create_folder with additional
arguments.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 7f32b3a8-9f70-4343-9b71-f78d1ca3377c
📒 Files selected for processing (1)
test/testcases/restful_api/test_file_routes_unit.py
What problem does this PR solve?
extend restful api suite
Type of change