Repository navigation
feat: add locale URL routing for admin and chat static files with tests - #8296
Conversation
| def test_chat_locale_index_is_served_from_static_path(self): | ||
| response = self.client.get("/static/chat/locales/index.json") | ||
|
|
||
| self.assertEqual(response.status_code, 200) |
There was a problem hiding this comment.
Code Review
Potential Issues
-
Calling
pro()insidesetUpClassis unusual side effectpro()presumably modifies URL patterns / settings at runtime. Invoking it in the test class setup means the mutation happens once and persists across tests, which can cause:- Order-dependent test behavior (other test classes may see mutated URLs).
- Leaks between test runs when running the full suite.
- Consider using
override_settingsor resetting state intearDownClass, and/or callingpro()per-test.
-
self.clientonSimpleTestCaserequires static file serving to be enabledSimpleTestCase.clientwon't serve static files by default unless Django'sstaticfilestest machinery is active. Tests will likely return 404 unless you useStaticLiveServerTestCaseor ensureDEBUG=True+django.contrib.staticfileshandler is used.- Safer: use
from django.test import ClientwithStaticFilesHandler, or assert viafinders.find(...)instead of HTTP requests if the goal is "the file exists in the static path".
-
Hardcoded paths (
/static/admin/...,/static/chat/...) — brittle ifSTATIC_URLis configured differently. Usesettings.STATIC_URL. -
pro()called but never referenced again — unclear intent; add a comment explaining why. Ifpro()is idempotent, that should be documented. -
No assertion that the response body is actually the JSON locale index — only status code. A 200 could still be a directory listing or error page in some setups.
-
Test isolation —
setUpClassmutating global state without teardown is risky for a project-wide test suite. -
Imports — importing from
maxkb.urlscouples the test to URL module internals. Ifpro()is a view/router registration helper, prefer a public API or fixture. -
Naming —
LocaleUrlTeststests serving, not the URL configuration per se;StaticLocaleServingTestsmight be clearer. -
Diff header
@@ -0,0 +1,20 @@shows a new file with 20 lines but the snippet ends at line 17 — verify the diff was truncated and no partial content is being committed.
Optimization / Style Suggestions
- Cache
responseper test only where needed; currently fine. - Parametrize the two nearly identical tests:
def test_locale_index_is_served_from_static_path(self):
for path in ("admin/locales/index.json", "chat/locales/index.json"):
with self.subTest(path=path):
response = self.client.get(f"{settings.STATIC_URL}{path}")
self.assertEqual(response.status_code, 200)
self.assertIn("application/json", response["Content-Type"])- Add
assertJSONEqualonresponse.contentif you want to validate payload. - If the real intent is "the locale file ships in the package", replace HTTP test with:
from django.contrib.staticfiles import finders
self.assertIsNotNone(finders.find("admin/locales/index.json"))which is faster and doesn't depend on the static server handler.
Summary
The biggest risks are (a) pro() side effects leaking across tests without cleanup, (b) serving static files through SimpleTestCase.client may not work as written, and (c) hardcoded URL paths. Address these before merging.
| ) | ||
| # 暴露ui静态资源 | ||
| urlpatterns.append( | ||
| re_path( |
There was a problem hiding this comment.
Here's my review of the added code:
Issues
1. Using static.serve in production
django.views.static.serve is explicitly intended for development only. It is documented as inefficient and insecure. If these routes are registered unconditionally (not gated behind settings.DEBUG), they will be active in production, which is a security/performance concern. Use your web server (nginx/Apache) or a proper static-files solution instead.
2. Path traversal risk
Your regex r"^static/admin/locales/(?P<path>.*)$" captures everything after /locales/, including things like ../../../etc/passwd. Although Django's static.serve calls safe_join internally (which mitigates traversal when STATIC_ROOT is set correctly), relying on that plus exposing arbitrary paths is fragile. Prefer stricter patterns or avoid serving user-controllable path segments at all.
3. Overlapping/suboptimal routing
These re_path patterns with broad capture groups may shadow or conflict with other URL patterns (e.g., a catch-all static handler defined elsewhere). Ordering matters; make sure these don't unintentionally match more than intended.
4. Redundant os.path.join(settings.STATIC_ROOT, ...) vs actual location
If locales are generated at runtime, verify they truly live under STATIC_ROOT/admin/locales and STATIC_ROOT/chat/locales. If generation happens after collectstatic or outside STATIC_ROOT, these routes will 404 silently.
5. No caching / no conditional GET tuning
static.serve supports max_age but it's not set here. Consider passing {"document_root": ..., "show_indexes": False} and a cache header, or better, let the front-end server handle caching.
Optimization suggestions
- Gate the whole block behind
if settings.DEBUG:(or a dedicated setting likeSERVE_DYNAMIC_LOCALES). - Replace
.*with a more restrictive pattern, e.g.:re_path( r"^static/admin/locales/(?P<path>[-\w./]+\.js)$", static.serve, {"document_root": os.path.join(settings.STATIC_ROOT, "admin", "locales")}, name="admin_locales", )
- Consider using
django.conf.urls.static.static()helper orwhitenoisefor safer static serving. - Add a comment explaining why these files aren't served by the standard static pipeline (i.e., runtime-generated), so future maintainers don't remove them.
- Combine the two near-identical appends into a small loop to reduce duplication:
for app in ("admin", "chat"): urlpatterns.append(re_path( rf"^static/{app}/locales/(?P<path>[-\w./]+\.js)$", static.serve, {"document_root": os.path.join(settings.STATIC_ROOT, app, "locales")}, name=f"{app}_locales", ))
Minor
- The Chinese comment
# 暴露运行时生成的 UI 语言包is fine, but ensure comments are consistent with the rest of the file's language convention. - Confirm
osandstaticare imported earlier in the module (they appear to be, given surrounding usage).
| @@ -0,0 +1 @@ | |||
|
|
|||
There was a problem hiding this comment.
The code you provided doesn't contain any actual code — it's just a diff header (@@ -0,0 +1 @@) followed by an empty added line. There's nothing to review for irregularities, bugs, or optimizations.
If you intended to paste the code, please resend it in full (without diff markers, or with the complete diff including context lines), and I'll review it.
What this PR does / why we need it?
Summary of your change
Please indicate you've done the following: