Skip to content

feat: add locale URL routing for admin and chat static files with tests - #8296

Merged
wxg0103 merged 1 commit into
v3from
pr@v3@feat_add_local_url
Dec 4, 2026
Merged

wxg0103 merged 1 commit into
v3from
pr@v3@feat_add_local_url

Conversation

@wxg0103

@wxg0103 wxg0103 commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

What this PR does / why we need it?

Summary of your change

Please indicate you've done the following:

  • Made sure tests are passing and test coverage is added if needed.
  • Made sure commit message follow the rule of Conventional Commits specification.
  • Considered the docs impact and opened a new docs issue or PR with docs changes if needed.

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)

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.

Code Review

Potential Issues

  1. Calling pro() inside setUpClass is unusual side effect

    • pro() 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_settings or resetting state in tearDownClass, and/or calling pro() per-test.
  2. self.client on SimpleTestCase requires static file serving to be enabled

    • SimpleTestCase.client won't serve static files by default unless Django's staticfiles test machinery is active. Tests will likely return 404 unless you use StaticLiveServerTestCase or ensure DEBUG=True + django.contrib.staticfiles handler is used.
    • Safer: use from django.test import Client with StaticFilesHandler, or assert via finders.find(...) instead of HTTP requests if the goal is "the file exists in the static path".
  3. Hardcoded paths (/static/admin/..., /static/chat/...) — brittle if STATIC_URL is configured differently. Use settings.STATIC_URL.

  4. pro() called but never referenced again — unclear intent; add a comment explaining why. If pro() is idempotent, that should be documented.

  5. 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.

  6. Test isolation — setUpClass mutating global state without teardown is risky for a project-wide test suite.

  7. Imports — importing from maxkb.urls couples the test to URL module internals. If pro() is a view/router registration helper, prefer a public API or fixture.

  8. Naming — LocaleUrlTests tests serving, not the URL configuration per se; StaticLocaleServingTests might be clearer.

  9. 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 response per 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 assertJSONEqual on response.content if 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.

Comment thread apps/maxkb/urls/web.py
)
# 暴露ui静态资源
urlpatterns.append(
re_path(

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.

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 like SERVE_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 or whitenoise for 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 os and static are imported earlier in the module (they appear to be, given surrounding usage).

@@ -0,0 +1 @@

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.

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.

@wxg0103
wxg0103 merged commit aa8b458 into v3 Dec 4, 2026
2 of 4 checks passed
@wxg0103
wxg0103 deleted the pr@v3@feat_add_local_url branch December 4, 2026 01:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants