first commit

This commit is contained in:
daniel committed 2026-10-14 16:16:58 +02:00
commit 9b2f5b023f
9 files changed
+919

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
__pycache__
*.exe
+75
View File
@@ -0,0 +1,75 @@
# AGENTS.md
Ein kleiner Texteditor für Windows, gebaut mit **Python 3 + Tkinter** (nur
Standardbibliothek, keine externen Abhängigkeiten). UI-Texte sind Deutsch.
## Start
```powershell
cd D:\AI\Projekte\texteditor
python app.py
```
## Projektlayout
| Datei | Zweck |
|---------------------------|----------------------------------------------------------------------------------------------------------|
| `app.py` | GUI: `TextEditorApp` (Fenster, Menüs, Textbereich, Statusleiste, Dialoge, Shortcuts; wendet die Highlighting-Tags aus `highlight.py` auf das Text-Widget an) |
| `file_io.py` | Reine Datei-Logik ohne Tkinter: `load_file()`, `save_file()` + `FileLoadError`, `FileSaveError` |
| `highlight.py` | Reine Highlighting-Logik ohne Tkinter: `detect_language()`, `tokenize_python()` + `SUFFIX_LANGUAGES`, `HIGHLIGHT_TAGS`, `TAG_COLORS` |
| `smoke_test.py` | Kurzer Test der I/O-Logik (GUI-frei) und der App-Logik mit verstecktem Tk-Fenster (ohne Dialoge), `python smoke_test.py` |
| `highlight_test.py` | Test der Highlighting-Logik in `highlight.py` (GUI-frei), `python highlight_test.py` |
| `regression_open.py` | Regressionstest für den `askyesnocancel`-Fehler: „Öffnen drücken bei ungespeicherten Änderungen“ mit gestubten Dialogen, `python regression_open.py` |
| `regression_highlight.py` | Regressionstest für Highlighting + `<<Modified>>`-Flag-Reset: „.py“ öffnen, Sprache wechseln, nach dem Speichern editieren, ohne Popups, `python regression_highlight.py` |
## Wichtige Konventionen
- **Schichtentrennung halten:** `file_io.py` und `highlight.py` dürfen
keine Tkinter-Referenzen erhalten. Fehler werden als eigene
Exceptions geworfen; das Anzeigen von Fehlerdialogen
(`messagebox.showerror`) gescheht ausschließlich in `app.py`.
- **Syntax-Highlighting (nur Python):** `highlight.py` tokenisiert die
Quelle und liefert nur Tag-Namen + Tokenize-Positionen
(Zeile 1-basiert, Spalte 0-basiert – kongruent mit Tk). Das Auftragen
auf das `tk.Text`-Widget liegt ausschließlich in `app.py`:
Farben einmalig per `tag_config` aus `TAG_COLORS` setzen; alte
Highlighting-Tags vor jeder Neu-Anwendung über `tag_remove(tag, "1.0", "end")`
entfernen (3-Argument-Form, Tag-Definition bleibt); Sprachwechsel über
Menü **Formatierung ▸ Syntax Highlighting…** oder automatisch beim
Öffnen via `detect_language()`. Neue Sprachen = neuer `tokenize_X()` in
`highlight.py` + Eintrag in `SUFFIX_LANGUAGES`/`HIGHLIGHT_TAGS`/`TAG_COLORS`.
- **Ungespeicherte Änderungen:** werden über das Tk-Ereignis
`<<Modified>>` + `text.edit_modified()` in `TextEditorApp._modified`
getrackt. Vor **Neu**, **Öffnen** und **Beenden** läuft
`_confirm_save()` („speichern/verwerfen/abbrechen“).
Wichtig: Nach jedem Programm-eingriff (`_set_content`) `text.edit_reset()`
und `edit_modified(False)` aufrufen, sonst zahlt eine
bloße Dateiladeung als „ungespeicherte“ Änderungen.
- **Titel-Anzeige:** Immer über `_build_title()` erzeugen
(`name – Texteditor`, bei offenem Dokument `*`-Präfix).
- **Fenster schließen:** Nur über `WM_DELETE_WINDOW`-Protocol mit
`_on_exit()`, damit der Abbruchdialog immer greift.
## Geplanter Ausbau (Phase 2, bewusst noch nicht umgesetzt)
- Tabs für mehrere Dateien (`ttk.Notebook`)
- Bearbeiten-Menü (Rückgängig/Wiederherstellen, Schneiden/Kopieren/Einfügen, Alles markieren)
- Suchen/Ersetzen-Dialog, Zeilennummern, Undo/Redo-Menü
- Weitere Highlighting-Sprachen (z. B. JSON, JavaScript)
## Tests / Verifikation
- `python -m py_compile app.py file_io.py highlight.py`
- `python smoke_test.py` → erwartet `OK` (I/O-Logik + App-Logik mit
verstecktem Tk-Fenster, ohne Dialoge)
- `python highlight_test.py` → erwartet `OK` (Tokenizer + Spracherkennung
in `highlight.py`, GUI-frei, inkl. unvollständiger/ungültiger Quellen)
- `python regression_open.py` → erwartet `OK` (Regression für den
`askyesnocancel`-Aufruf: „Öffnen“ bei ungespeicherten Änderungen,
Dialoge gestubbt)
- `python regression_highlight.py` → erwartet `OK` (Regression für
Highlighting und `<<Modified>>`-Flag-Reset: `.py` öffnen, Sprache
wechseln, nach Speichern editieren, ohne Popups)
- GUI-Verifikation manuell starten: jede Menüfunktion + die
„Änderungen speichern?“-Abfragen in **Neu**, **Öffnen** und **Beenden**
durchklicken.
+378
View File
@@ -0,0 +1,378 @@
"""Hauptprogramm: Ein kleiner Texteditor auf Basis von Tkinter.
Start:
python app.py
Die UI (Fenster, Menü, Textbereich, Statusleiste) und die Bedienung der
Dialoge liegen hier; die reine Datei-I/O-Logik liegt in file_io.py und die
Tokenizing for the Syntax-Highlighting in highlight.py.
"""
from __future__ import annotations
import tkinter as tk
from pathlib import Path
from tkinter import filedialog, messagebox
from file_io import FileLoadError, FileSaveError, load_file, save_file
from highlight import (
HIGHLIGHT_TAGS,
TAG_COLORS,
detect_language,
tokenize_python,
)
APP_TITLE = "Texteditor"
FILE_TYPES = [("Textdateien", "*.txt"), ("Alle Dateien", "*.*")]
class TextEditorApp:
"""Tkinter-Anwendung mit einem Texteditor für eine offene Datei."""
def __init__(self, root: tk.Tk) -> None:
self.root = root
self.file_path: Path | None = None
self._modified = False
self.language: str | None = None
self.root.title(self._build_title())
self.root.geometry("800x600")
self.root.minsize(400, 300)
self._build_menu()
self._build_text_area()
self._build_status_bar()
self.root.protocol("WM_DELETE_WINDOW", self._on_exit)
# ------------------------------------------------------------ UI-Aufbau --
def _build_menu(self) -> None:
menubar = tk.Menu(self.root)
file_menu = tk.Menu(menubar, tearoff=False)
file_menu.add_command(
label="Neu",
accelerator="Strg+N",
command=self.new_file,
)
file_menu.add_command(
label="Öffnen…",
accelerator="Strg+O",
command=self.open_file,
)
file_menu.add_command(
label="Speichern",
accelerator="Strg+S",
command=self.save_file,
)
file_menu.add_command(
label="Speichern unter…",
accelerator="Strg+Shift+S",
command=self.save_file_as,
)
file_menu.add_separator()
file_menu.add_command(
label="Beenden",
accelerator="Alt+F4",
command=self._on_exit,
)
menubar.add_cascade(label="Datei", menu=file_menu)
help_menu = tk.Menu(menubar, tearoff=False)
help_menu.add_command(label="Über Texteditor…", command=self._on_about)
menubar.add_cascade(label="Hilfe", menu=help_menu)
# No Shortcut: <Control-h> would collide with the built-in
# Backspace-Binding of the Text-Widget.
format_menu = tk.Menu(menubar, tearoff=False)
highlight_menu = tk.Menu(menubar, tearoff=False)
highlight_menu.add_command(label="Plain Text", command=self.use_plain_text)
highlight_menu.add_command(label="Python", command=self.use_python)
format_menu.add_cascade(
label="Syntax Highlighting…", menu=highlight_menu
)
menubar.add_cascade(label="Formatierung", menu=format_menu)
self.root.config(menu=menubar)
self._bind_shortcuts()
def _bind_shortcuts(self) -> None:
# Groß- und klein geschrieben: Tkinter bindet Großbuchstaben nur zu,
# wenn Shift gedrückt ist; beide Varianten garantieren die Zuordnung
# in jeder Shift-Kombination (außer bei Caps Lock).
self.root.bind("<Control-n>", self.new_file)
self.root.bind("<Control-N>", self.new_file)
self.root.bind("<Control-o>", self.open_file)
self.root.bind("<Control-O>", self.open_file)
self.root.bind("<Control-s>", self.save_file)
self.root.bind("<Control-S>", self.save_file)
self.root.bind("<Control-Shift-s>", self.save_file_as)
self.root.bind("<Control-Shift-S>", self.save_file_as)
def _build_text_area(self) -> None:
container = tk.Frame(self.root)
container.pack(fill="both", expand=True)
self.text = tk.Text(
container,
wrap="none",
undo=True,
font=("Consolas", 11),
relief="flat",
)
# Highlighting-Colors per Tag, configured once.
for tag, color in TAG_COLORS.items():
self.text.tag_config(tag, foreground=color)
v_scroll = tk.Scrollbar(
container, orient="vertical", command=self.text.yview
)
h_scroll = tk.Scrollbar(
container, orient="horizontal", command=self.text.xview
)
self.text.configure(
yscrollcommand=v_scroll.set, xscrollcommand=h_scroll.set
)
self.text.grid(row=0, column=0, sticky="nsew")
v_scroll.grid(row=0, column=1, sticky="ns")
h_scroll.grid(row=1, column=0, sticky="ew")
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
# Ereignisse, die bei jeder Änderung/Navigation neu ausgelöst werden:
self.text.bind("<<Modified>>", self._on_text_modified)
self.text.bind("<KeyRelease>", self._update_status)
self.text.bind("<ButtonRelease-1>", self._update_status)
def _build_status_bar(self) -> None:
status = tk.Frame(self.root, relief="sunken", borderwidth=1)
status.pack(side="bottom", fill="x")
self.lbl_cursor = tk.Label(status, text="Zeile 1, Spalte 1", padx=10)
self.lbl_chars = tk.Label(status, text="0 Zeichen", padx=10)
self.lbl_cursor.pack(side="left")
self.lbl_chars.pack(side="right")
# ---------------------------------------------------------- Titel & Status --
def _build_title(self) -> str:
name = self.file_path.name if self.file_path else "Ohne Titel"
title = f"{name} – {APP_TITLE}"
return f"*{title}" if self._modified else title
def _update_title(self) -> None:
self.root.title(self._build_title())
def _update_status(self, event=None) -> None:
line, col = self.text.index("insert").split(".")
self.lbl_cursor.config(
text=f"Zeile {int(line)}, Spalte {int(col) + 1}"
)
char_count = len(self.text.get("1.0", "end-1c"))
self.lbl_chars.config(text=f"{char_count} Zeichen")
def _on_text_modified(self, event=None) -> None:
"""Verfolgt ungespeicherte Änderungen über <<Modified>>.
Tk feuert für jede Änderung ZWEI <<Modified>>-Ereignisse: eines,
wenn der Dirty-Flag von 0→1 springt, und ein zweites (Echo), weil
das manuelle ``edit_modified(False)`` selbst den Rückfall 1→0
meldet. Das Ereignis wird also immer aktiv gelaufen:
ist der Flag gesetzt, wurde eingegeben → Dirty-Status setzen und
Flag consume. Der nachfolgende Echo-Ruf sieht dann Flag==False
und ändert nichts mehr. Abgespeichert (``_do_save``) und
Programm-Eingriffe (``_set_content``) setzen den Dirty-Status
selbst zurück.
"""
if self.text.edit_modified():
self.text.edit_modified(False)
if not self._modified:
self._modified = True
self._update_title()
self._apply_highlighting()
self._update_status()
def _set_content(self, content: str) -> None:
"""Ersetzt den Textinhalt und setzt die Änderungs- und Undo-Marker zurück."""
self.text.delete("1.0", "end")
self.text.insert("1.0", content)
self.text.edit_reset() # Undo-Verlauf des vorherigen Dokuments
self.text.edit_modified(False) # Programmänderung zählt nicht
self._modified = False
self._apply_highlighting()
self._update_title()
self._update_status()
# ------------------------------------------------------- Syntax-Highlighting --
def set_language(self, language: str | None) -> None:
"""Sets the Highlighting-Language and reapplies the Highlighting."""
self.language = language
self._apply_highlighting()
def use_plain_text(self, event=None) -> None:
self.set_language(None)
def use_python(self, event=None) -> None:
self.set_language("python")
def _apply_highlighting(self) -> None:
"""Applies the Tags of the current Language over the whole Document.
Old Tags are always deleted first: Tk-Tags accumulate and the Undo-
Mechanism does not restore them, therefore the complete Document is
always highlighted anew.
"""
# Tkinter wraps no single ``tag_remove`` of ALL Tags, but the
# no-op form (tag REMOVE over a RANGE) requires a TAG name as
# the first argument. So we clear each highlight-tag itself
# across the whole document; the tag DEFINITION (color) stays
# configured, only the ranges disappear.
for tag in HIGHLIGHT_TAGS:
self.text.tag_remove(tag, "1.0", "end")
if self.language != "python":
return
source = self.text.get("1.0", "end-1c")
for tag, (srow, scol), (erow, ecol) in tokenize_python(source):
self._tag_range(tag, srow, scol, erow, ecol)
def _tag_range(self, tag: str, srow: int, scol: int, erow: int, ecol: int) -> None:
"""Colors one Token-Range.
Tokenize- und Tk-Positionen sind hier kongruent: Zeile 1-basiert,
Spalte 0-basiert. Der Tk-Index-String nutzt daher einen Punkt
("1.1"), nicht einen Doppelpunkt, und benötigt kein +1 auf die
Spalte – der Token-Endpunkt ist (wie bei Tk) bereits exklusiv.
"""
try:
self.text.tag_add(tag, f"{srow}.{scol}", f"{erow}.{ecol}")
except tk.TclError: # Index outside the Document (Race-Condition)
pass
# -------------------------------------------------------------- Dateifunktionen --
def _confirm_save(self) -> bool:
"""Fragt, ob ungespeicherte Änderungen gespeichert werden sollen.
Returns:
True, wenn die Aktion (Neu/Öffnen/Beenden) fortgesetzt
werden darf, False, wenn sie abgebrochen werden soll.
"""
if not self._modified:
return True
answer = messagebox.askyesnocancel(
title="Änderungen speichern?",
message=(
"Die aktuellen Änderungen wurden noch nicht gespeichert.\n"
"Möchtest du die Änderungen speichern?"
),
icon="question",
default="no",
parent=self.root,
)
if answer is None: # Abbrechen
return False
if answer: # Ja → speichern
return self.save_file()
return True # Nein → Änderungen verwerfen
def new_file(self, event=None) -> None:
if not self._confirm_save():
return
self.file_path = None
self.language = None
self._set_content("")
def open_file(self, event=None) -> None:
if not self._confirm_save():
return
path = filedialog.askopenfilename(
parent=self.root,
title="Datei öffnen",
filetypes=FILE_TYPES,
)
if not path:
return
try:
content = load_file(path)
except FileLoadError as exc:
messagebox.showerror(APP_TITLE, str(exc), parent=self.root)
return
self.file_path = Path(path)
# Language guess from the Suffix; the Menu-Choice of the User wins
# again until the next File-Opening.
self.language = detect_language(path)
self._set_content(content)
def save_file(self, event=None) -> bool:
"""Speichert das aktuelle Dokument.
Returns:
True, wenn die Speicherung erfolgreich war oder nicht
nötig war, False, wenn sie fehlgeschlagen oder abgebrochen
wurde.
"""
if self.file_path is not None and not self._modified:
return True
if self.file_path is None:
return self.save_file_as()
return self._do_save()
def save_file_as(self, event=None) -> bool:
initial = self.file_path.name if self.file_path else "unbenannt.txt"
path = filedialog.asksaveasfilename(
parent=self.root,
title="Speichern unter",
defaultextension=".txt",
initialfile=initial,
filetypes=FILE_TYPES,
)
if not path: # Abbrechen
return False
self.file_path = Path(path)
return self._do_save()
def _do_save(self) -> bool:
assert self.file_path is not None
try:
save_file(self.file_path, self.text.get("1.0", "end-1c"))
except FileSaveError as exc:
messagebox.showerror(APP_TITLE, str(exc), parent=self.root)
return False
self._modified = False
self._update_title()
return True
# ------------------------------------------------------------------ Sonstiges --
def _on_exit(self, event=None) -> None:
if not self._confirm_save():
return
self.root.destroy()
def _on_about(self) -> None:
messagebox.showinfo(
"Über Texteditor",
"Texteditor\n\n"
"Ein kleiner Texteditor, gebaut mit Tkinter und Python.",
parent=self.root,
)
def main() -> None:
# Schärferes Rendering auf Windows bei hochauflösender Anzeige.
try:
import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
pass
root = tk.Tk()
TextEditorApp(root)
root.mainloop()
if __name__ == "__main__":
main()
+60
View File
@@ -0,0 +1,60 @@
"""Reine Datei-I/O-Logik für den Texteditor.
Dieses Modul enthält KEINE Tkinter-Referenzen, damit es isoliert getestet
werden kann. Fehler werden über dedizierte Ausnahmen signalisiert; die
Anzeige von Fehlerdialogen liegt bei app.py.
"""
from __future__ import annotations
from pathlib import Path
class FileLoadError(Exception):
"""Wird ausgelöst, wenn eine Datei nicht gelesen werden kann."""
class FileSaveError(Exception):
"""Wird ausgelöst, wenn eine Datei nicht geschrieben werden kann."""
def load_file(path: str | Path) -> str:
"""Liest eine Textdatei (UTF-8) und liefert deren Inhalt zurück.
Args:
path: Pfad zur Datei.
Returns:
Der komplette Textinhalt der Datei.
Raises:
FileLoadError: Wenn die Datei nicht existiert, nicht lesbar ist
oder kein gültiges UTF-8-Textformat enthält.
"""
p = Path(path)
try:
return p.read_text(encoding="utf-8")
except UnicodeDecodeError as exc:
raise FileLoadError(
f"Die Datei ist keine gültige UTF-8-Textdatei:\n{p}"
) from exc
except OSError as exc:
raise FileLoadError(f"Die Datei konnte nicht gelesen werden:\n{exc}") from exc
def save_file(path: str | Path, content: str) -> None:
"""Schreibt Textinhalt in eine Datei (UTF-8).
Args:
path: Ziel-Pfad der Datei.
content: Der zu speichernde Textinhalt.
Raises:
FileSaveError: Wenn die Datei nicht geschrieben werden kann
(z. B. keine Schreibrechte, Ordner existiert nicht).
"""
p = Path(path)
try:
p.write_text(content, encoding="utf-8")
except OSError as exc:
raise FileSaveError(f"Die Datei konnte nicht gespeichert werden:\n{exc}") from exc
+102
View File
@@ -0,0 +1,102 @@
"""Syntax-Highlighting-Logik for the Texteditor.
This module contains KEINE Tkinter-Referencers: it only tokenizes Source
and returns Tag-Ranges. The applying of the Tags on the Text-Widget lies
exclusively in app.py.
Only Python is implemented; other languages are planned for Phase 2.
"""
from __future__ import annotations
import builtins
import keyword
import tokenize
import token
from pathlib import Path
# Language detection per File-Suffix (lowercase).
SUFFIX_LANGUAGES = {".py": "python", ".pyw": "python"}
# Tag-Names which the Highlighter can generate. app.py deletes these Tags
# before a new Highlighting and configures the Colors from TAG_COLORS.
HIGHLIGHT_TAGS = (
"py_keyword",
"py_builtin",
"py_string",
"py_comment",
"py_number",
"py_operator",
)
# Colors for the light Tk-Background.
TAG_COLORS = {
"py_keyword": "#00008B",
"py_builtin": "#006400",
"py_string": "#8B0000",
"py_comment": "#595959",
"py_number": "#005C8A",
"py_operator": "#3F3F3F",
}
KEYWORDS = frozenset(keyword.kwlist)
BUILTINS = frozenset(n for n in dir(builtins) if not n.startswith("_"))
# Tokenize has no KEYWORD-Tokentype: Keywords arrive as NAME and must be
# classified with the keyword-Module. The Token-Type-NUMBERS differ between
# Python-Versions, therefore only the Constants from the token-Module are
# used.
_TOKEN_TAGS = {
token.NUMBER: "py_number",
token.STRING: "py_string",
token.COMMENT: "py_comment",
token.OP: "py_operator",
}
# f-Strings (Python 3.12+) arrive as three separate Token-Types.
for _fstring_type in ("FSTRING_START", "FSTRING_MIDDLE", "FSTRING_END"):
_TOKEN_TAGS[getattr(token, _fstring_type)] = "py_string"
def detect_language(path: str | Path) -> str | None:
"""Returns the Language for a File-Name or None, when unknown."""
return SUFFIX_LANGUAGES.get(Path(path).suffix.lower())
def _tag_for(tok: tokenize.TokenInfo) -> str | None:
"""Maps one Tokenize-Token on its Tag-Name (None = default Color)."""
if tok.type == token.NAME:
if tok.string in KEYWORDS:
return "py_keyword"
if tok.string in BUILTINS:
return "py_builtin"
return None
return _TOKEN_TAGS.get(tok.type)
def tokenize_python(source: str) -> list[tuple[str, tuple[int, int], tuple[int, int]]]:
"""Tokenizes Python-Source and returns (tag, start, end).
Positions are the Tokenize-Positions: row starts at 1, column at 0.
Incomplete or incorrect Source (the User types freely into the Editor)
does not raise: the Tokens until tokenize stops are returned, the rest
stays in the default Color.
Raises:
Never. tokenize.TokenError, SyntaxError and ValueError are caught.
"""
# tokenize.tokenize needs a readline over BYTE-LINES (it detects the
# Encoding); str-Lines would raise a TypeError.
lines = iter([line.encode("utf-8") for line in source.splitlines(keepends=True)])
def readline() -> bytes:
return next(lines, b"")
ranges: list[tuple[str, tuple[int, int], tuple[int, int]]] = []
try:
for tok in tokenize.tokenize(readline):
tag = _tag_for(tok)
if tag and tok.start != tok.end:
ranges.append((tag, tok.start, tok.end))
except (tokenize.TokenError, SyntaxError, ValueError):
pass
return ranges
+57
View File
@@ -0,0 +1,57 @@
"""GUI-freier Test of the Highlighting-Logic (highlight.py).
Start: python highlight_test.py
Expected Output: "OK"
"""
from pathlib import Path
from highlight import HIGHLIGHT_TAGS, detect_language, tokenize_python
SOURCE = 'def greet(name):\n # greeting\n msg = f"hi {name}"\n print(msg, 3.5)\n'
def test_detect_language() -> None:
assert detect_language(Path(r"C:\x\script.py")) == "python"
assert detect_language("note.PY") == "python"
assert detect_language("notes.txt") is None
assert detect_language("readme") is None
def test_tokenize_python() -> None:
ranges = tokenize_python(SOURCE)
# Only known Tags are generated
assert {tag for tag, _, _ in ranges} <= set(HIGHLIGHT_TAGS)
# 'def' is a Keyword, 'print' a Builtin (tokenize has no KEYWORD-Type)
assert ("py_keyword", (1, 0), (1, 3)) in ranges
assert ("py_builtin", (4, 4), (4, 9)) in ranges
assert ("py_comment", (2, 4), (2, 14)) in ranges
assert ("py_number", (4, 15), (4, 18)) in ranges
# f-Strings are highlighted as Strings (FSTRING_START/MIDDLE/END)
assert any(tag == "py_string" for tag, _, _ in ranges)
# Plain Identifiers keep the default Color
assert not any(tag in ("py_keyword", "py_builtin") and start == (3, 4) for tag, start, _ in ranges)
def test_incomplete_source() -> None:
"""The User types freely: broken Code must not raise, Tokens until
there are still highlighted."""
ranges = tokenize_python('x = (1,\ny = "abc\n')
assert ("py_operator", (1, 2), (1, 3)) in ranges
assert ("py_number", (1, 5), (1, 6)) in ranges
def test_garbage_never_raises() -> None:
for junk in ["Hello World", "C:\\temp\\file", "???", "def", "x = 1 \x0c\n", "a\x00b\n"]:
tokenize_python(junk)
if __name__ == "__main__":
test_detect_language()
test_tokenize_python()
test_incomplete_source()
test_garbage_never_raises()
print("OK")
+89
View File
@@ -0,0 +1,89 @@
"""Regressiontest for the Syntax-Highlighting and the <<Modified>>-Flag-Reset:
„Open“ of a .py-File, Language-Switch and Editing after a Save without Popups.
Start: python regression_highlight.py
Expected Output: "OK"
"""
import tkinter as tk
from pathlib import Path
import tempfile
import app as app_module
from app import TextEditorApp
from highlight import HIGHLIGHT_TAGS
SOURCE = "def greet(name):\n # greeting\n print(name, 3.5)\n"
def _highlighted_tags(text, probe: str) -> list[str]:
return [t for t in text.tag_names(probe) if t in HIGHLIGHT_TAGS]
def test_open_detects_language() -> None:
"""Opening a .py-File switches on the Highlighting automatically."""
with tempfile.TemporaryDirectory() as d:
target = Path(d) / "quelle.py"
target.write_text(SOURCE, encoding="utf-8")
# Dialog-Stub: the Filedialog of app.py gets replaced
app_module.filedialog.askopenfilename = lambda parent=None, **kwargs: str(target)
root = tk.Tk()
root.withdraw()
obj = TextEditorApp(root)
obj.open_file()
root.update()
assert obj.language == "python"
assert obj._modified is False
# 'def' at 1.1, '#' at 2.5, '3.5' at 3.16..3.19
assert "py_keyword" in _highlighted_tags(obj.text, "1.1")
assert "py_comment" in _highlighted_tags(obj.text, "2.6")
assert "py_number" in _highlighted_tags(obj.text, "3.17")
# Switch to Plain Text: all Highlighting-Tags must be gone
obj.use_plain_text()
for probe in ("1.1", "2.6", "3.12"):
assert _highlighted_tags(obj.text, probe) == []
# Switch back
obj.use_python()
assert "py_builtin" in _highlighted_tags(obj.text, "3.5")
root.destroy()
def test_dirty_flag_after_save() -> None:
"""Without the Flag-Reset in the Handler the Dirty-State is lost after
the first Save and the Highlighting stays outdated."""
root = tk.Tk()
root.withdraw()
obj = TextEditorApp(root)
with tempfile.TemporaryDirectory() as d:
target = Path(d) / "dok.py"
obj.file_path = target
obj.language = "python"
obj._set_content(SOURCE)
obj.text.insert("end-1c", "\nprint(1)")
root.update()
assert obj._modified is True
assert obj.save_file() is True
assert obj._modified is False
# A new Edit after the Save must become ungespeicherte again
obj.text.insert("end-1c", "\nprint(2)")
root.update()
assert obj._modified is True
assert root.title().startswith("*")
# and the Highlighting follows the new Input
assert "py_builtin" in _highlighted_tags(obj.text, "5.1")
root.destroy()
if __name__ == "__main__":
test_open_detects_language()
test_dirty_flag_after_save()
print("OK")
+71
View File
@@ -0,0 +1,71 @@
"""Regressionstest f"r askyesnocancel-Multiple-Values-Bug:
simuliert "Öffnen dr"cken bei ungespeicherten "Anderungen" ohne Popups.
Start: python regression_open.py
Erwarteter Output: "OK"
"""
import tkinter as tk
import tkinter.messagebox
import tkinter.filedialog
from pathlib import Path
import tempfile
from app import TextEditorApp, APP_TITLE # nur Import-Zeit-Kontrolle
# Dialoge stubben, damit der Test ohne Popups l"uft
askyes_calls = []
open_paths = [None] # [0] = gew"hlte Ziel-Datei oder None (abbrechen)
def fake_askyesnocancel(title=None, message=None, **options):
askyes_calls.append({"title": title, "message": message, **options})
# Standard-Antwort des Tests: "Ja" speichern
return True
def fake_askopenfilename(parent=None, **kwargs):
return open_paths[0] or ""
tkinter.messagebox.askyesnocancel = fake_askyesnocancel
tkinter.filedialog.askopenfilename = fake_askopenfilename
# app.py importiert "from tkinter import messagebox" – dort patchen:
import app
app.messagebox.askyesnocancel = fake_askyesnocancel
app.filedialog.askopenfilename = fake_askopenfilename
def test_open_with_unsaved_changes() -> None:
root = tk.Tk()
app_obj = TextEditorApp(root)
# ungespeicherte "Anderungen eingeben
app_obj.text.insert("1.0", "Wichtige Arbeit")
root.update()
assert app_obj._modified is True
# "Öffnen" triggern – m"uss ohne Crash die Abfrage zeigen und
# die Datei "offnen
with tempfile.TemporaryDirectory() as d:
target = Path(d) / "quelle.txt"
target.write_text("Inhalt der Quelldatei", encoding="utf-8")
open_paths[0] = str(target)
app_obj.open_file()
root.update()
# Abfrage wurde genau einmal korrekt aufgerufen
assert len(askyes_calls) == 1, askyes_calls
call = askyes_calls[0]
assert call["title"] == "Änderungen speichern?"
assert "noch nicht gespeichert" in call["message"]
assert call["parent"] is root
# und die Datei wurde "offnet
assert app_obj.file_path == target
assert app_obj.text.get("1.0", "end-1c") == "Inhalt der Quelldatei"
assert app_obj._modified is False
root.destroy()
if __name__ == "__main__":
test_open_with_unsaved_changes()
print("OK")
+85
View File
@@ -0,0 +1,85 @@
"""GUI-freier Smoke-Test: I/O-Logik + App-Logik (ohne Dialoge).
Start: python smoke_test.py
Erwarteter Output: "OK"
"""
import sys
import tempfile
from pathlib import Path
import tkinter as tk
import file_io
from file_io import FileLoadError, FileSaveError
from app import TextEditorApp
def test_file_io() -> None:
with tempfile.TemporaryDirectory() as d:
p = Path(d) / "test.txt"
file_io.save_file(p, "Hallo Welt\n2. Zeile")
assert Path(p).read_text(encoding="utf-8") == "Hallo Welt\n2. Zeile"
try:
file_io.load_file(Path(d) / "nicht_da.txt")
raise AssertionError("FileLoadError fehlte")
except FileLoadError:
pass
try:
file_io.save_file(Path(d) / "fehlender_pfad" / "x.txt", "x")
raise AssertionError("FileSaveError fehlte")
except FileSaveError:
pass
def test_app_logic() -> None:
root = tk.Tk()
app = TextEditorApp(root)
# Frischer Start: Titel, Status, keine Änderungen
assert app._modified is False
assert root.title().endswith("Texteditor")
assert "Ohne Titel" in root.title()
# Textingabe wird als ungespeicherte Änderung getrackt
# (root.update() ist nötig, damit das virtuelle <<Modified>>-Ereignis
# verarbeitet wird; the Handler resets the Tk-Flag afterwards, therefore
# only the Application-State is checked here)
app.text.insert("1.0", "Hallo")
root.update()
assert app._modified is True
assert root.title().startswith("*")
# Speichern (Datei-Pfad setzen, Speichern unter-Dialog überspringen)
with tempfile.TemporaryDirectory() as d:
target = Path(d) / "dokument.txt"
app.file_path = target
assert app.save_file() is True
saved = target.read_text(encoding="utf-8")
assert saved == "Hallo"
# Nach dem Speichern: keine ungespeicherten Änderungen, Titel ohne *
assert app._modified is False
assert not root.title().startswith("*")
assert app.file_path.name == "dokument.txt"
assert "dokument.txt" in root.title()
# After the Save a new Edit must become ungespeicherte again
# (only works because the Handler resets the <<Modified>>-Flag)
app.text.insert("end-1c", "!")
root.update()
assert app._modified is True
assert root.title().startswith("*")
# Inhalt setzen (Programm-Eingriff) zahlt nicht als unspeicherte Änderung
app._set_content("Neuer Inhalt")
assert app._modified is False
assert app.text.get("1.0", "end-1c") == "Neuer Inhalt"
root.destroy()
if __name__ == "__main__":
test_file_io()
test_app_logic()
print("OK")