Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/maxkb/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -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've provided appears to be only an empty diff line:

@@ -0,0 +1 @@
+

This is a unified‑diff hunk header (@@ -0,0 +1 @@) followed by a single added blank line. There is no actual source code to review.

Observations:

  • The hunk header indicates a file being created (from 0 lines to 1 line).
  • The single + line adds an empty/blank line.
  • No logic, syntax, imports, or structure is present, so there are no irregularities, bugs, or optimization opportunities to flag.

To give a meaningful review, please paste the actual code (e.g., the full file content, not just the diff header). If this is intentional, note that committing files with only a blank line is generally unnecessary and can be cleaned up.

20 changes: 20 additions & 0 deletions apps/maxkb/tests/test_locale_urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from django.test import SimpleTestCase

from maxkb.urls import pro


class LocaleUrlTests(SimpleTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
pro()

def test_admin_locale_index_is_served_from_static_path(self):
response = self.client.get("/static/admin/locales/index.json")

self.assertEqual(response.status_code, 200)

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.

Here are the issues and suggestions:

Issues:

  1. Calling pro() in setUpClass mutates global URL/state. pro() likely registers URLs or performs one-time setup. Calling it inside a test class affects global state for other tests in the same process, violating test isolation. It may also fail if called twice (e.g., across multiple test runs) due to duplicate URL registration.

  2. SimpleTestCase + self.client with real URL resolution. SimpleTestCase forbids DB queries but still goes through URL resolution. If pro() registers routes not present in ROOT_URLCONF, these tests will only pass because of the global mutation in step 1 — fragile ordering dependency.

  3. No negative assertions. The tests only check 200. A 200 could come from any handler. Consider asserting content type (application/json) or that the JSON parses correctly.

  4. Hardcoded paths. Should ideally be built from settings.STATIC_URL rather than literal /static/....

  5. pro() call placement. If its purpose is to expose static locale files, verify this is truly needed in tests, or isolate via override_settings / dedicated fixture rather than global invocation.

Suggestions:

  • Wrap setup with self.addCleanup() if pro() has a corresponding teardown.
  • Assert content:
    self.assertEqual(response.headers["Content-Type"], "application/json")
    json.loads(response.content)
  • Use settings.STATIC_URL to construct the path.
  • Add a test that the response body matches expectations (non-empty JSON).
  • Consider whether SimpleTestCase is appropriate; if pro() touches DB or app registry, preconditions may be violated.

No syntax irregularities; the diff itself is clean. The main concerns are global-state isolation and weak assertions.

17 changes: 17 additions & 0 deletions apps/maxkb/urls/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,23 @@ def pro():
name="doc_chat",
),
)
# 暴露运行时生成的 UI 语言包
urlpatterns.append(
re_path(
r"^static/admin/locales/(?P<path>.*)$",
static.serve,
{"document_root": os.path.join(settings.STATIC_ROOT, "admin", "locales")},
name="admin_locales",
),
)
urlpatterns.append(
re_path(
r"^static/chat/locales/(?P<path>.*)$",
static.serve,
{"document_root": os.path.join(settings.STATIC_ROOT, "chat", "locales")},
name="chat_locales",
),
)
# 暴露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.

Irregularities & Potential Issues

  1. Mismatch between URL path and document_root
    The route captures (?P<path>.*) and serves from STATIC_ROOT/admin/locales, but static.serve joins path onto document_root. That's fine, but note the re_path prefix ^static/admin/locales/ combined with document_root means effectively serving <STATIC_ROOT>/admin/locales/<path> at /static/admin/locales/<path> — consistent, OK. However, if STATIC_ROOT already ends in a trailing slash, os.path.join handles it; fine.

  2. Path traversal risk (low, but worth noting)
    static.serve uses django.views.static.serve, which sanitizes paths via posixpath.normpath and rejects .. — so traversal should be blocked. Still, capturing .* is permissive; using <path:path> converter or a more restrictive regex ([^/]+(\.[^/]+)?) narrows intent.

  3. static.serve is for DEBUG only
    Django docs explicitly state static.serve is not suitable for production (inefficient, no caching headers, no gzip). If these locale files must be served at runtime in production, use your web server / whitenoise / object storage instead. This whole if settings.DEBUG block (assuming it's inside one) should not gate required assets in prod.

  4. Redundant duplication
    Two near-identical urlpatterns.append(...) calls. Could be refactored into a loop over locale dirs to reduce repetition and make future additions easier.

  5. settings.STATIC_ROOT may need str()
    STATIC_ROOT is usually a str or Path. os.path.join accepts both, but mixing Path and str elsewhere can bite; consider str(settings.STATIC_ROOT).

  6. Ordering / shadowing
    These are appended after other patterns. Ensure a generic ^static/ handler earlier doesn't already catch these routes, making them dead code. Also verify they come before any catch-all that could intercept.

  7. Security header / range requests
    serve supports conditional responses but lacks security headers (e.g., X-Content-Type-Options). Minor.

  8. Caching for locales
    Locale JSON rarely changes; add Cache-Control via middleware or serve statically. Runtime serving defeats browser/CDN caching benefits.

Suggested Refactor

for sub in ("admin", "chat"):
    urlpatterns.append(
        re_path(
            rf"^static/{sub}/locales/(?P<path>[^/]+(\.[^/]+)?)$",
            static.serve,
            {"document_root": os.path.join(str(settings.STATIC_ROOT), sub, "locales")},
            name=f"{sub}_locales",
        ),
    )

And wrap the whole block in if settings.DEBUG: (or use a production-grade static file server).

Expand Down
Loading