Files
mizan/desktop/app.py
Ryth Azhur 4451ec24a1 Full test infrastructure, code audit fixes, and real E2E integration tests
Test infrastructure:
- Django standalone test runner (pytest-django, test settings, EmailUser model)
- React unit tests via Vitest with jsdom, jest compat layer, path aliases
- Playwright E2E tests using generated hooks in a real Chromium browser
- Docker Compose test backend (Django + Redis) for integration testing
- Desktop integration test app (PyWebView + Django + uvicorn)
- Makefile with test/test-django/test-react/test-integration targets

Library bugs found and fixed:
- hasJWT truthiness: undefined !== null was true, skipping session init
- process.env crash: CSR client referenced process.env in non-Node browsers
- baseUrl not forwarded: DjareaProvider didn't pass baseUrl to CSR client
- Relative URL handling: new URL() failed with relative base paths
- call() race condition: HTTP requests fired before CSRF cookie was set
- Session init await: added sessionRef promise so call() waits for session
- path_prefix on schema export: both export commands failed with URL reverse
- NullBooleanField removed: referenced field doesn't exist in Django 5.0+
- lru_cache on JWT settings: get_settings() now cached as intended
- Channel message routing: broadcasts now include channel name and params
- httpFunctionCall: fixed URL and request body format

Generator fixes:
- Removed 1,100 lines of REST/OpenAPI client generation (not part of Djarea)
- Generator now works for djarea-only projects without django-ninja REST APIs
- Generated DjangoContext now includes ChannelProvider when channels exist
- Fixed env var passthrough for schema export commands
- Deduplicated fetch logic into single runDjangoCommand helper

Test quality:
- Fixed 33 tautological Django tests with real assertions
- Found hidden bug: benchmark functions were never registered
- Found hidden bug: unicode lookalike test used plain ASCII
- Deleted worthless React unit tests (duplicates, shape checks, Zod-tests-Zod)
- Replaced jsdom integration tests with Playwright browser tests

Example apps:
- example/: Integration test backend with 33 server functions, 5 forms,
  4 channels covering auth variations, contexts, class-based ServerFunction,
  error codes, DjareaFormMixin, formsets, and JWT
- desktop/: PyWebView desktop app with file system access, SQLite CRUD,
  system introspection, and 39 real HTTP integration tests

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 01:17:48 -04:00

97 lines
2.3 KiB
Python

#!/usr/bin/env python
"""
Djarea Desktop — PyWebView + Django local RPC.
Starts a local Django ASGI server and opens a native desktop window.
All communication between the UI and backend uses Djarea server functions.
"""
import os
import sys
import threading
import time
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")
# Work around Qt WebEngine GPU crashes on some systems
os.environ.setdefault("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu")
def start_server(host: str, port: int):
"""Start the Django ASGI server in a background thread."""
import django
django.setup()
# Run migrations on first launch
from django.core.management import call_command
call_command("migrate", "--run-syncdb", verbosity=0)
import uvicorn
uvicorn.run(
"backend.asgi:application",
host=host,
port=port,
log_level="warning",
)
def wait_for_server(url: str, timeout: float = 10.0):
"""Poll until the server responds."""
from urllib.request import urlopen
from urllib.error import URLError
deadline = time.time() + timeout
while time.time() < deadline:
try:
urlopen(url, timeout=1)
return True
except (URLError, OSError):
time.sleep(0.1)
return False
def main():
host = "127.0.0.1"
port = 8765
# Start Django in a daemon thread
server = threading.Thread(target=start_server, args=(host, port), daemon=True)
server.start()
base_url = f"http://{host}:{port}"
if not wait_for_server(f"{base_url}/api/djarea/session/"):
print("ERROR: Django server failed to start", file=sys.stderr)
sys.exit(1)
print(f"Backend running at {base_url}")
# Check if --headless flag is passed (for testing)
if "--headless" in sys.argv:
print("Headless mode — server running. Press Ctrl+C to stop.")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
return
# Open native window
import webview
window = webview.create_window(
title="Djarea Desktop",
url=base_url,
width=1024,
height=768,
min_size=(640, 480),
)
webview.start()
if __name__ == "__main__":
main()