Phase 4: project I/O (project_io.py) + build/run flow (build.py) with filling, scrolling console
This commit is contained in:
1 parent
45037b23a3
commit
12ac32272c
4 files changed
+741
No files matched your search
@@ -0,0 +1,240 @@
|
||||
"""Build / Run flow for generated Python apps.
|
||||
|
||||
There is no CMake build for Python apps (see docs/architecture.md):
|
||||
"Build" is a syntax check (``python3 -m py_compile``) and "Run"
|
||||
executes the generated script with ``python3``. Both show the exact
|
||||
command run, like the C console does, and stream their output into a
|
||||
build console window whose output area FILLS the dialog and scrolls
|
||||
to the end (to the failure on error) — the C cb95f5f fix, built in
|
||||
from the start: the ScrolledWindow is packed expanding, and scrolling
|
||||
happens in an idle callback after allocation, not right after show.
|
||||
|
||||
The generated script needs the LightGUI package on PYTHONPATH; the
|
||||
Run flow sets it to the repo root (the parent of this package).
|
||||
"""
|
||||
|
||||
import os
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import gi
|
||||
|
||||
gi.require_version("Gtk", "3.0")
|
||||
|
||||
from gi.repository import GLib, Gtk # noqa: E402
|
||||
|
||||
|
||||
def repo_root():
|
||||
"""Directory holding the ``lightgui`` package (this file's parent's
|
||||
parent)."""
|
||||
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def run_env(extra=None):
|
||||
"""Environment for running a generated script: PYTHONPATH gains
|
||||
the repo root so ``import lightgui`` resolves."""
|
||||
env = dict(os.environ)
|
||||
root = repo_root()
|
||||
path = env.get("PYTHONPATH", "")
|
||||
parts = [p for p in path.split(os.pathsep) if p] if path else []
|
||||
if root not in parts:
|
||||
parts.insert(0, root)
|
||||
env["PYTHONPATH"] = os.pathsep.join(parts)
|
||||
if extra:
|
||||
env.update(extra)
|
||||
return env
|
||||
|
||||
|
||||
def command_str(argv):
|
||||
"""Shell display form of *argv* (what the console shows after $)."""
|
||||
return shlex.join(str(arg) for arg in argv)
|
||||
|
||||
|
||||
class BuildResult:
|
||||
"""Outcome of one build/run step: ok, the exact command, its
|
||||
combined output, and its exit code (None when never started)."""
|
||||
|
||||
def __init__(self, ok, output, command, returncode=None,
|
||||
script_path=None):
|
||||
self.ok = ok
|
||||
self.output = output
|
||||
self.command = command
|
||||
self.returncode = returncode
|
||||
self.script_path = script_path
|
||||
|
||||
def __bool__(self):
|
||||
return self.ok
|
||||
|
||||
|
||||
def syntax_check(script_path, python=sys.executable):
|
||||
"""'Build': py_compile the generated script. Returns a
|
||||
BuildResult whose output starts with the exact command run."""
|
||||
argv = [python, "-m", "py_compile", str(script_path)]
|
||||
command = command_str(argv)
|
||||
try:
|
||||
proc = subprocess.run(argv, capture_output=True, text=True,
|
||||
timeout=60)
|
||||
except subprocess.TimeoutExpired:
|
||||
return BuildResult(False, "$ %s\ntimed out after 60s\n" % command,
|
||||
command, None, script_path)
|
||||
except OSError as exc:
|
||||
return BuildResult(False, "$ %s\ncannot run: %s\n" % (command, exc),
|
||||
command, None, script_path)
|
||||
output = "$ %s\n%s%s" % (command, proc.stdout, proc.stderr)
|
||||
return BuildResult(proc.returncode == 0, output, command,
|
||||
proc.returncode, script_path)
|
||||
|
||||
|
||||
def run_capture(script_path, timeout=30, python=sys.executable,
|
||||
extra_env=None):
|
||||
"""Run the generated script synchronously and capture its combined
|
||||
stdout+stderr (for tests and for the Build console). A timeout
|
||||
kills the script and reports it; the exit code is preserved."""
|
||||
argv = [python, str(script_path)]
|
||||
command = command_str(argv)
|
||||
try:
|
||||
proc = subprocess.run(argv, capture_output=True, text=True,
|
||||
timeout=timeout, env=run_env(extra_env))
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
output = "$ %s\n%s%s\n[timed out after %ss — killed]\n" % (
|
||||
command, exc.stdout or "", exc.stderr or "", timeout)
|
||||
return BuildResult(False, output, command, None, script_path)
|
||||
except OSError as exc:
|
||||
return BuildResult(False, "$ %s\ncannot run: %s\n" % (command, exc),
|
||||
command, None, script_path)
|
||||
output = "$ %s\n%s%s" % (command, proc.stdout, proc.stderr)
|
||||
return BuildResult(proc.returncode == 0, output, command,
|
||||
proc.returncode, script_path)
|
||||
|
||||
|
||||
# --- build console window -----------------------------------------------------
|
||||
|
||||
|
||||
class BuildConsole(Gtk.Dialog):
|
||||
"""Scrollable log dialog for build/run output. The log TextView
|
||||
fills the dialog (packed expanding — the cb95f5f fix) and the view
|
||||
starts scrolled to the end of the log, so a failure is visible
|
||||
immediately. Run output streams in live via io watches; a Stop
|
||||
button kills the running script.
|
||||
"""
|
||||
|
||||
def __init__(self, title="Build", parent=None):
|
||||
super().__init__(title=title, parent=parent,
|
||||
flags=Gtk.DialogFlags.DESTROY_WITH_PARENT)
|
||||
self.set_default_size(700, 420)
|
||||
self.proc = None
|
||||
self._stdout_watch = None
|
||||
self._child_watch = None
|
||||
|
||||
self.view = Gtk.TextView()
|
||||
self.view.set_editable(False)
|
||||
self.view.set_monospace(True)
|
||||
self.view.set_wrap_mode(Gtk.WrapMode.CHAR)
|
||||
self.buffer = self.view.get_buffer()
|
||||
|
||||
scroll = Gtk.ScrolledWindow()
|
||||
scroll.set_policy(Gtk.PolicyType.AUTOMATIC,
|
||||
Gtk.PolicyType.AUTOMATIC)
|
||||
scroll.add(self.view)
|
||||
# Pack expanding so the log fills the dialog (cb95f5f): the
|
||||
# dialog content box's default add() packs expand=FALSE, which
|
||||
# left the log at ~2 lines pinned to the top.
|
||||
content = self.get_content_area()
|
||||
content.pack_start(scroll, True, True, 0)
|
||||
content.show_all()
|
||||
|
||||
self.stop_button = self.add_button("Stop",
|
||||
Gtk.ResponseType.CANCEL)
|
||||
self.stop_button.set_sensitive(False)
|
||||
self.add_button("Close", Gtk.ResponseType.CLOSE)
|
||||
self.connect("response", self._on_response)
|
||||
|
||||
# --- text ---------------------------------------------------------------
|
||||
def get_text(self):
|
||||
start, end = self.buffer.get_bounds()
|
||||
return self.buffer.get_text(start, end, True)
|
||||
|
||||
def set_text(self, text):
|
||||
self.buffer.set_text(text or "")
|
||||
self.scroll_to_end()
|
||||
|
||||
def append(self, text):
|
||||
if not text:
|
||||
return
|
||||
end = self.buffer.get_end_iter()
|
||||
self.buffer.insert(end, text)
|
||||
self.scroll_to_end()
|
||||
|
||||
def scroll_to_end(self):
|
||||
"""Scroll to the end of the log. Deferred to idle: scrolling
|
||||
before the dialog is realized/allocated computes against the
|
||||
not-yet-final size and lands short of the true end (C fix)."""
|
||||
GLib.idle_add(self._scroll_to_end_idle)
|
||||
|
||||
def _scroll_to_end_idle(self):
|
||||
end = self.buffer.get_end_iter()
|
||||
self.view.scroll_to_iter(end, 0.0, False, 0.0, 0.0)
|
||||
return False
|
||||
|
||||
# --- running ------------------------------------------------------------
|
||||
def run_command(self, argv, cwd=None, extra_env=None):
|
||||
"""Start *argv* async, streaming combined output into the log.
|
||||
Shows the exact command first, like the C console."""
|
||||
command = command_str(argv)
|
||||
self.set_text("$ %s\n" % command)
|
||||
self.stop_button.set_sensitive(True)
|
||||
try:
|
||||
self.proc = subprocess.Popen(
|
||||
[str(arg) for arg in argv],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
text=True, bufsize=1, cwd=cwd, env=run_env(extra_env))
|
||||
except OSError as exc:
|
||||
self.append("cannot run: %s\n" % exc)
|
||||
self.stop_button.set_sensitive(False)
|
||||
return False
|
||||
self._stdout_watch = GLib.io_add_watch(
|
||||
self.proc.stdout, GLib.IO_IN | GLib.IO_HUP,
|
||||
self._on_stdout)
|
||||
self._child_watch = GLib.child_watch_add(
|
||||
self.proc.pid, self._on_child_exit)
|
||||
return True
|
||||
|
||||
def _on_stdout(self, source, _condition):
|
||||
chunk = source.readline()
|
||||
if chunk:
|
||||
self.append(chunk)
|
||||
return True
|
||||
return False
|
||||
|
||||
def _on_child_exit(self, _pid, status):
|
||||
code = os.waitstatus_to_exitcode(status) \
|
||||
if hasattr(os, "waitstatus_to_exitcode") else status
|
||||
self.append("\n[exited with code %s]\n" % code)
|
||||
self.stop_button.set_sensitive(False)
|
||||
self.proc = None
|
||||
return False
|
||||
|
||||
def stop(self):
|
||||
"""Kill the running script, if any."""
|
||||
if self.proc is not None and self.proc.poll() is None:
|
||||
self.proc.kill()
|
||||
self.append("\n[stopped]\n")
|
||||
self.stop_button.set_sensitive(False)
|
||||
|
||||
def _on_response(self, _dialog, response):
|
||||
if response == Gtk.ResponseType.CANCEL:
|
||||
self.stop()
|
||||
elif response == Gtk.ResponseType.CLOSE:
|
||||
self.hide()
|
||||
|
||||
|
||||
def show_result_dialog(parent, result, title="Build"):
|
||||
"""Modal console showing a finished BuildResult (syntax check).
|
||||
The log fills the dialog and starts scrolled to the end."""
|
||||
console = BuildConsole(title=title, parent=parent)
|
||||
head = "Build succeeded.\n\n" if result.ok else "Build FAILED.\n\n"
|
||||
console.set_text(head + result.output)
|
||||
console.run()
|
||||
console.destroy()
|
||||
return result.ok
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Project file handling: New / Open / Save / Save As for .fdj files.
|
||||
|
||||
Builds on lightgui.model.Project (whose save_text/load_text reproduce
|
||||
the C writer's .fdj layout byte for byte). This module adds the IDE
|
||||
side: the current path, dirty tracking, file dialogs, and the
|
||||
confirm-before-discard check. The wrapped Project object is replaced
|
||||
in place on New/Open so the canvas and Inspector keep their reference
|
||||
to the same object.
|
||||
"""
|
||||
|
||||
import gi
|
||||
|
||||
gi.require_version("Gtk", "3.0")
|
||||
|
||||
from gi.repository import Gtk # noqa: E402
|
||||
|
||||
from lightgui.model import Project # noqa: E402
|
||||
|
||||
FDJ_FILTER_NAME = "LightGUI project (*.fdj)"
|
||||
FDJ_EXTENSION = ".fdj"
|
||||
|
||||
|
||||
def is_fdj_path(path):
|
||||
return bool(path) and str(path).lower().endswith(FDJ_EXTENSION)
|
||||
|
||||
|
||||
def ensure_fdj_path(path):
|
||||
path = str(path)
|
||||
if not path.lower().endswith(FDJ_EXTENSION):
|
||||
path += FDJ_EXTENSION
|
||||
return path
|
||||
|
||||
|
||||
def _replace_contents(target, source):
|
||||
"""Copy *source* Project state into *target* in place (same
|
||||
object identity, so canvas/Inspector references stay valid)."""
|
||||
target.__dict__.clear()
|
||||
target.__dict__.update(source.__dict__)
|
||||
|
||||
|
||||
class ProjectFile:
|
||||
"""One open project file: the Project, its path, and its dirty
|
||||
flag. Dirty is set by the app whenever the canvas, Inspector or
|
||||
project itself changes; loading/saving clears it.
|
||||
"""
|
||||
|
||||
def __init__(self, project=None):
|
||||
self.project = project if project is not None else Project()
|
||||
self.path = None
|
||||
self.dirty = False
|
||||
|
||||
# --- state ------------------------------------------------------------
|
||||
@property
|
||||
def title(self):
|
||||
"""Display title: the file basename, or 'Untitled'."""
|
||||
if self.path:
|
||||
return self.path.rsplit("/", 1)[-1]
|
||||
return "Untitled"
|
||||
|
||||
def mark_dirty(self):
|
||||
self.dirty = True
|
||||
|
||||
def mark_clean(self):
|
||||
self.dirty = False
|
||||
|
||||
# --- New / Open / Save --------------------------------------------------
|
||||
def new(self):
|
||||
"""Replace the project with a fresh empty one (in place)."""
|
||||
_replace_contents(self.project, Project())
|
||||
self.path = None
|
||||
self.dirty = False
|
||||
return self.project
|
||||
|
||||
def open_path(self, path):
|
||||
"""Load the .fdj file at *path* (in place). Raises ValueError
|
||||
from the model loader on a bad file; the old project is left
|
||||
untouched when loading fails."""
|
||||
project = Project.load_file(path)
|
||||
_replace_contents(self.project, project)
|
||||
self.path = path
|
||||
self.dirty = False
|
||||
return self.project
|
||||
|
||||
def save(self):
|
||||
"""Save to the current path. Raises ValueError when there is
|
||||
no path yet (the caller then runs save_as)."""
|
||||
if not self.path:
|
||||
raise ValueError("no file name — use Save As")
|
||||
self.project.save_file(self.path)
|
||||
self.dirty = False
|
||||
return self.path
|
||||
|
||||
def save_as(self, path):
|
||||
path = ensure_fdj_path(path)
|
||||
self.project.save_file(path)
|
||||
self.path = path
|
||||
self.dirty = False
|
||||
return path
|
||||
|
||||
# --- dialogs ---------------------------------------------------------------
|
||||
def confirm_discard(self, parent=None):
|
||||
"""True when it is OK to throw the current project away
|
||||
(not dirty, or the user confirmed)."""
|
||||
if not self.dirty:
|
||||
return True
|
||||
dialog = Gtk.MessageDialog(
|
||||
parent=parent, flags=Gtk.DialogFlags.MODAL,
|
||||
type=Gtk.MessageType.QUESTION,
|
||||
buttons=Gtk.ButtonsType.YES_NO,
|
||||
message_format="Discard unsaved changes to %s?"
|
||||
% self.title)
|
||||
response = dialog.run()
|
||||
dialog.destroy()
|
||||
return response == Gtk.ResponseType.YES
|
||||
|
||||
def open_dialog(self, parent=None):
|
||||
"""File -> Open: pick a .fdj file and load it. Returns True
|
||||
on a successful load, False on cancel or a bad file (the
|
||||
error is reported on *parent* via a message dialog when the
|
||||
file was picked but failed to load)."""
|
||||
dialog = Gtk.FileChooserDialog(
|
||||
title="Open Project", parent=parent,
|
||||
action=Gtk.FileChooserAction.OPEN,
|
||||
buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
|
||||
Gtk.STOCK_OPEN, Gtk.ResponseType.ACCEPT))
|
||||
self._add_fdj_filter(dialog)
|
||||
if self.path:
|
||||
dialog.set_filename(self.path)
|
||||
response = dialog.run()
|
||||
path = dialog.get_filename() if response == Gtk.ResponseType.ACCEPT \
|
||||
else None
|
||||
dialog.destroy()
|
||||
if path is None:
|
||||
return False
|
||||
try:
|
||||
self.open_path(path)
|
||||
except ValueError as exc:
|
||||
self._show_error(parent, "Could not open %s:\n%s"
|
||||
% (path, exc))
|
||||
return False
|
||||
return True
|
||||
|
||||
def save_dialog(self, parent=None):
|
||||
"""File -> Save As: pick a path and save there. Returns True
|
||||
on success, False on cancel."""
|
||||
dialog = Gtk.FileChooserDialog(
|
||||
title="Save Project As", parent=parent,
|
||||
action=Gtk.FileChooserAction.SAVE,
|
||||
buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
|
||||
Gtk.STOCK_SAVE, Gtk.ResponseType.ACCEPT))
|
||||
self._add_fdj_filter(dialog)
|
||||
dialog.set_do_overwrite_confirmation(True)
|
||||
if self.path:
|
||||
dialog.set_filename(self.path)
|
||||
else:
|
||||
dialog.set_current_name("Untitled.fdj")
|
||||
response = dialog.run()
|
||||
path = dialog.get_filename() if response == Gtk.ResponseType.ACCEPT \
|
||||
else None
|
||||
dialog.destroy()
|
||||
if path is None:
|
||||
return False
|
||||
self.save_as(path)
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _add_fdj_filter(dialog):
|
||||
file_filter = Gtk.FileFilter()
|
||||
file_filter.set_name(FDJ_FILTER_NAME)
|
||||
file_filter.add_pattern("*.fdj")
|
||||
dialog.add_filter(file_filter)
|
||||
all_filter = Gtk.FileFilter()
|
||||
all_filter.set_name("All files")
|
||||
all_filter.add_pattern("*")
|
||||
dialog.add_filter(all_filter)
|
||||
|
||||
@staticmethod
|
||||
def _show_error(parent, message):
|
||||
dialog = Gtk.MessageDialog(
|
||||
parent=parent, flags=Gtk.DialogFlags.MODAL,
|
||||
type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK,
|
||||
message_format="%s" % message)
|
||||
dialog.run()
|
||||
dialog.destroy()
|
||||
@@ -0,0 +1,163 @@
|
||||
"""Tests for lightgui.build (Phase 4): syntax check, run capture,
|
||||
and the build console window.
|
||||
|
||||
Logic tests run anywhere. BuildConsole widget tests need a display
|
||||
and are skipped when Gtk cannot initialise (run under Xvfb, :99).
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from lightgui.build import (
|
||||
BuildConsole, BuildResult, command_str, repo_root, run_capture,
|
||||
run_env, syntax_check)
|
||||
|
||||
try:
|
||||
import gi
|
||||
gi.require_version("Gtk", "3.0")
|
||||
from gi.repository import Gtk
|
||||
_GTK_OK = Gtk.init_check()[0]
|
||||
except Exception:
|
||||
Gtk = None
|
||||
_GTK_OK = False
|
||||
|
||||
GOOD_SCRIPT = """import sys
|
||||
print("hello from generated app")
|
||||
print("second line")
|
||||
"""
|
||||
|
||||
BAD_SCRIPT = """def broken(
|
||||
print("never reached")
|
||||
"""
|
||||
|
||||
FAILING_SCRIPT = """import sys
|
||||
print("before the failure")
|
||||
raise RuntimeError("boom at runtime")
|
||||
"""
|
||||
|
||||
|
||||
def _write_script(folder, name, text):
|
||||
path = os.path.join(folder, name)
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
handle.write(text)
|
||||
return path
|
||||
|
||||
|
||||
class BuildLogicTests(unittest.TestCase):
|
||||
def test_command_str(self):
|
||||
self.assertEqual(command_str(["python3", "-m", "py_compile",
|
||||
"/tmp/a b.py"]),
|
||||
"python3 -m py_compile '/tmp/a b.py'")
|
||||
|
||||
def test_repo_root_has_package(self):
|
||||
self.assertTrue(os.path.isdir(os.path.join(repo_root(),
|
||||
"lightgui")))
|
||||
|
||||
def test_run_env_adds_repo_root(self):
|
||||
env = run_env()
|
||||
self.assertIn(repo_root(), env["PYTHONPATH"].split(os.pathsep))
|
||||
|
||||
def test_syntax_check_good_script(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = _write_script(folder, "good.py", GOOD_SCRIPT)
|
||||
result = syntax_check(path)
|
||||
self.assertTrue(result.ok)
|
||||
self.assertEqual(result.returncode, 0)
|
||||
self.assertIn("py_compile", result.command)
|
||||
self.assertIn(path, result.command)
|
||||
self.assertTrue(result.output.startswith("$ "))
|
||||
|
||||
def test_syntax_check_bad_script_reports_error(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = _write_script(folder, "bad.py", BAD_SCRIPT)
|
||||
result = syntax_check(path)
|
||||
self.assertFalse(result.ok)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("SyntaxError", result.output)
|
||||
|
||||
def test_run_capture_good_script(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = _write_script(folder, "good.py", GOOD_SCRIPT)
|
||||
result = run_capture(path)
|
||||
self.assertTrue(result.ok)
|
||||
self.assertIn("hello from generated app", result.output)
|
||||
self.assertIn("second line", result.output)
|
||||
# The console shows the exact command run.
|
||||
self.assertIn("$ %s %s" % (sys.executable, path),
|
||||
result.output)
|
||||
|
||||
def test_run_capture_failing_script_captures_stderr(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = _write_script(folder, "fail.py", FAILING_SCRIPT)
|
||||
result = run_capture(path)
|
||||
self.assertFalse(result.ok)
|
||||
self.assertIn("before the failure", result.output)
|
||||
self.assertIn("RuntimeError: boom at runtime", result.output)
|
||||
self.assertIn("Traceback", result.output)
|
||||
self.assertEqual(result.returncode, 1)
|
||||
|
||||
def test_run_capture_timeout(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = _write_script(folder, "slow.py",
|
||||
"import time\ntime.sleep(30)\n")
|
||||
result = run_capture(path, timeout=1)
|
||||
self.assertFalse(result.ok)
|
||||
self.assertIn("timed out", result.output)
|
||||
|
||||
|
||||
class BuildConsoleTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
if not _GTK_OK:
|
||||
self.skipTest("needs a display (run under Xvfb)")
|
||||
|
||||
def test_log_area_fills_the_dialog(self):
|
||||
"""The cb95f5f fix: the scrolled log area is packed expanding
|
||||
(expand + fill), so it fills the dialog instead of sitting at
|
||||
~2 lines pinned to the top."""
|
||||
console = BuildConsole(title="Build")
|
||||
content = console.get_content_area()
|
||||
children = content.get_children()
|
||||
scrolled = [c for c in children
|
||||
if isinstance(c, Gtk.ScrolledWindow)]
|
||||
self.assertEqual(len(scrolled), 1)
|
||||
pack = content.query_child_packing(scrolled[0])
|
||||
self.assertTrue(pack[0], "log area must expand")
|
||||
self.assertTrue(pack[1], "log area must fill")
|
||||
console.destroy()
|
||||
|
||||
def test_append_and_text(self):
|
||||
console = BuildConsole(title="Build")
|
||||
console.set_text("$ python3 app.py\n")
|
||||
console.append("hello\n")
|
||||
console.append("world\n")
|
||||
self.assertEqual(console.get_text(),
|
||||
"$ python3 app.py\nhello\nworld\n")
|
||||
console.destroy()
|
||||
|
||||
def test_run_command_streams_output(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = _write_script(folder, "good.py", GOOD_SCRIPT)
|
||||
console = BuildConsole(title="Run")
|
||||
console.show()
|
||||
self.assertTrue(
|
||||
console.run_command([sys.executable, path]))
|
||||
while Gtk.events_pending():
|
||||
Gtk.main_iteration()
|
||||
# Wait for the child to exit (bounded spin).
|
||||
for _ in range(200):
|
||||
if console.proc is None:
|
||||
break
|
||||
while Gtk.events_pending():
|
||||
Gtk.main_iteration()
|
||||
import time
|
||||
time.sleep(0.01)
|
||||
text = console.get_text()
|
||||
self.assertIn("hello from generated app", text)
|
||||
self.assertIn("[exited with code 0]", text)
|
||||
console.destroy()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Tests for lightgui.project_io (Phase 4): New / Open / Save /
|
||||
Save As, dirty tracking, and the .fdj round-trip against the C
|
||||
writer's layout (checked against the Rust fixtures, which the C and
|
||||
Rust loaders share).
|
||||
|
||||
The legacy-type fixtures (control.fdj, hostile.fdj) carry pre-XFrame
|
||||
types (Canvas, Button, Label, Entry): the XFrame-only loader drops
|
||||
them by design, so those tests assert the drop + the surviving
|
||||
window fields, not a byte-identical round-trip.
|
||||
"""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from lightgui.model import Project
|
||||
from lightgui.project_io import (
|
||||
ProjectFile, ensure_fdj_path, is_fdj_path)
|
||||
|
||||
FIXTURES = "/opt/lightgui_rust/crates/lightgui-core/tests/fixtures"
|
||||
|
||||
|
||||
class ProjectFileTests(unittest.TestCase):
|
||||
def test_new_resets_in_place(self):
|
||||
project = Project()
|
||||
project.add_widget("GtkButton", 10, 10)
|
||||
holder = ProjectFile(project)
|
||||
holder.new()
|
||||
self.assertIs(holder.project, project)
|
||||
self.assertEqual(project.widgets, [])
|
||||
self.assertEqual(project.title, "Main Window")
|
||||
self.assertIsNone(holder.path)
|
||||
self.assertFalse(holder.dirty)
|
||||
|
||||
def test_save_as_and_open_round_trip(self):
|
||||
project = Project(title="Round Trip", class_name="RoundTrip")
|
||||
button = project.add_widget("GtkButton", 10, 20, 150, 36)
|
||||
button.set_prop("background", "#336699")
|
||||
button.set_prop("hint", "tip")
|
||||
from lightgui.inspector import set_event_handler
|
||||
set_event_handler(button, "OnClick", "on_click")
|
||||
project.add_widget("GtkLabel", 30, 40, 200, 30)
|
||||
holder = ProjectFile(project)
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = os.path.join(folder, "roundtrip.fdj")
|
||||
holder.save_as(path)
|
||||
self.assertEqual(holder.path, path)
|
||||
self.assertFalse(holder.dirty)
|
||||
self.assertTrue(os.path.isfile(path))
|
||||
|
||||
other = ProjectFile()
|
||||
other.open_path(path)
|
||||
self.assertEqual(other.project.title, "Round Trip")
|
||||
self.assertEqual(len(other.project.widgets), 2)
|
||||
loaded = other.project.widgets[0]
|
||||
self.assertEqual(loaded.name, "GtkButton_001")
|
||||
self.assertEqual(loaded.kind, "GtkButton")
|
||||
self.assertEqual((loaded.x, loaded.y), (10, 20))
|
||||
self.assertEqual(loaded.get_prop("background"), "#336699")
|
||||
self.assertEqual(loaded.get_prop("hint"), "tip")
|
||||
self.assertEqual(loaded.signals, ["OnClick=on_click"])
|
||||
# Save -> load -> save is byte-identical (C writer layout).
|
||||
self.assertEqual(other.project.save_text(),
|
||||
project.save_text())
|
||||
|
||||
def test_save_without_path_raises(self):
|
||||
holder = ProjectFile()
|
||||
with self.assertRaises(ValueError):
|
||||
holder.save()
|
||||
|
||||
def test_open_missing_file_raises(self):
|
||||
holder = ProjectFile()
|
||||
with self.assertRaises(ValueError):
|
||||
holder.open_path("/nonexistent/nope.fdj")
|
||||
self.assertEqual(holder.project.widgets, [])
|
||||
|
||||
def test_open_bad_file_leaves_project_untouched(self):
|
||||
holder = ProjectFile()
|
||||
holder.project.add_widget("GtkButton", 10, 10)
|
||||
with tempfile.NamedTemporaryFile(
|
||||
"w", suffix=".fdj", delete=False) as handle:
|
||||
handle.write("{not json")
|
||||
path = handle.name
|
||||
try:
|
||||
with self.assertRaises(ValueError):
|
||||
holder.open_path(path)
|
||||
finally:
|
||||
os.unlink(path)
|
||||
self.assertEqual(len(holder.project.widgets), 1)
|
||||
|
||||
def test_dirty_flag(self):
|
||||
holder = ProjectFile()
|
||||
self.assertFalse(holder.dirty)
|
||||
holder.mark_dirty()
|
||||
self.assertTrue(holder.dirty)
|
||||
holder.mark_clean()
|
||||
self.assertFalse(holder.dirty)
|
||||
|
||||
def test_title(self):
|
||||
holder = ProjectFile()
|
||||
self.assertEqual(holder.title, "Untitled")
|
||||
holder.path = "/some/dir/my_app.fdj"
|
||||
self.assertEqual(holder.title, "my_app.fdj")
|
||||
|
||||
def test_fdj_path_helpers(self):
|
||||
self.assertTrue(is_fdj_path("a.fdj"))
|
||||
self.assertTrue(is_fdj_path("A.FDJ"))
|
||||
self.assertFalse(is_fdj_path("a.py"))
|
||||
self.assertFalse(is_fdj_path(None))
|
||||
self.assertEqual(ensure_fdj_path("a"), "a.fdj")
|
||||
self.assertEqual(ensure_fdj_path("a.fdj"), "a.fdj")
|
||||
|
||||
@unittest.skipUnless(os.path.isdir(FIXTURES), "Rust fixtures absent")
|
||||
def test_empty_fixture_round_trips_byte_identical(self):
|
||||
"""empty.fdj: the C writer's layout, reproduced exactly."""
|
||||
path = os.path.join(FIXTURES, "empty.fdj")
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
original = handle.read()
|
||||
project = Project.load_file(path)
|
||||
self.assertEqual(project.save_text(), original)
|
||||
|
||||
@unittest.skipUnless(os.path.isdir(FIXTURES), "Rust fixtures absent")
|
||||
def test_control_fixture_window_fields_survive(self):
|
||||
"""control.fdj: title with control chars + a legacy Canvas
|
||||
widget (dropped by the XFrame-only loader, by design)."""
|
||||
path = os.path.join(FIXTURES, "control.fdj")
|
||||
project = Project.load_file(path)
|
||||
self.assertEqual(project.title, "ctrl\x01\x08\x0c\x1f")
|
||||
self.assertEqual(project.skipped, ["Canvas"])
|
||||
self.assertEqual(project.widgets, [])
|
||||
# The window block re-serialises exactly.
|
||||
saved = project.save_text()
|
||||
self.assertIn('"title": "ctrl\\u0001\\u0008\\u000c\\u001f"',
|
||||
saved)
|
||||
|
||||
@unittest.skipUnless(os.path.isdir(FIXTURES), "Rust fixtures absent")
|
||||
def test_hostile_fixture_window_fields_survive(self):
|
||||
"""hostile.fdj: quotes/backslashes/newlines in strings,
|
||||
menubar spec, background colour; legacy widgets dropped."""
|
||||
path = os.path.join(FIXTURES, "hostile.fdj")
|
||||
project = Project.load_file(path)
|
||||
self.assertEqual(project.title, 'My "Quoted" \\ App\nSecond line')
|
||||
self.assertEqual(project.class_name, "my cool app!")
|
||||
self.assertEqual((project.win_width, project.win_height),
|
||||
(1024, 768))
|
||||
self.assertEqual(project.background, "#102030")
|
||||
self.assertEqual(project.menubar,
|
||||
"File: New | Open | - | Quit\nHelp: About")
|
||||
self.assertEqual(project.skipped, ["Button", "Label", "Entry"])
|
||||
self.assertEqual(project.widgets, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user