Files
stimmwerk/src/ui/klicktest_view.rs
wlkns-dev 9f383f0374 Testfenster für die Klicktests (#1036): KLICKTESTS.md anzeigen, Berichte schreiben
Zweite Ansicht im Entwickler-Reiter (nur Debug-Builds, --tab klicktests). ✓/✗ mit Notiz schreibt einen
Bericht nach testberichte/; ✗ verlangt eine Notiz, nichts wird überschrieben. Test: Bericht besteht check-roadmap.py.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 09:36:37 +01:00

308 lines
10 KiB
Rust

//! Testfenster im Entwickler-Reiter: zeigt die Prozesse und Tests aus `KLICKTESTS.md`, das letzte Ergebnis aus
//! `testberichte/` und schreibt für manuelle Tests nach ✓ oder ✗ einen Bericht (Format siehe `KLICKTESTS.md`).
use super::gear::{AMBER, ENGRAVING, LED_GREEN, LED_RED, PLATE_BG, PLATE_EDGE, panel};
use crate::klicktests::{self, LastResult, Process, Test};
use eframe::egui::{self, RichText, Stroke};
use std::collections::HashMap;
use std::path::PathBuf;
pub(super) struct KlickState {
root: PathBuf,
loaded: bool,
error: Option<String>,
processes: Vec<Process>,
results: HashMap<String, LastResult>,
/// Notizfeld je Test-ID.
notes: HashMap<String, String>,
/// Letzte Rückmeldung nach dem Schreiben eines Berichts: (Erfolg, Text).
message: Option<(bool, String)>,
commit: String,
dirty: bool,
}
impl KlickState {
pub fn new() -> Self {
Self {
root: PathBuf::from("."),
loaded: false,
error: None,
processes: Vec::new(),
results: HashMap::new(),
notes: HashMap::new(),
message: None,
commit: String::new(),
dirty: false,
}
}
pub fn load(&mut self) {
self.loaded = true;
let path = self.root.join("KLICKTESTS.md");
match std::fs::read_to_string(&path) {
Ok(text) => {
self.processes = klicktests::parse_tests(&text);
self.error = None;
}
Err(e) => {
self.processes.clear();
self.error = Some(format!(
"{} nicht lesbar ({e}). Die App im Repository-Ordner starten (make run).",
path.display()
));
}
}
self.reload_results();
}
fn reload_results(&mut self) {
self.results = klicktests::last_results(&self.root.join("testberichte"));
(self.commit, self.dirty) = klicktests::git_state(&self.root);
}
/// Schreibt den Bericht für `test`; setzt die Rückmeldung und liest die Ergebnisse neu.
fn record(&mut self, test: &Test, ok: bool) {
let mut note = self.notes.get(&test.id).cloned().unwrap_or_default();
if self.dirty {
note.push_str(
"\n\nHinweis: Der Arbeitsordner hatte ungespeicherte Änderungen; die Commit-Kennung nennt nur den letzten Commit.",
);
}
let zeit = klicktests::now_stamp();
let dir = self.root.join("testberichte");
match klicktests::write_report(&dir, test, &zeit, &self.commit, ok, &note) {
Ok(path) => {
self.message = Some((true, format!("Bericht geschrieben: {}", path.display())));
self.notes.remove(&test.id);
self.reload_results();
}
Err(e) => self.message = Some((false, e)),
}
}
fn counts(&self) -> (usize, usize, usize, usize) {
let all: Vec<&Test> = self.processes.iter().flat_map(|p| &p.tests).collect();
let ok = all
.iter()
.filter(|t| self.results.get(&t.id).is_some_and(|r| r.ok))
.count();
let bad = all
.iter()
.filter(|t| self.results.get(&t.id).is_some_and(|r| !r.ok))
.count();
(all.len(), ok, bad, all.len() - ok - bad)
}
}
fn result_text(r: Option<&LastResult>) -> (String, egui::Color32) {
match r {
Some(r) if r.ok => (format!("✓ {} ({})", r.zeit, r.commit), LED_GREEN),
Some(r) => (format!("✗ {} ({})", r.zeit, r.commit), LED_RED),
None => ("noch nie geprüft".to_string(), ENGRAVING),
}
}
pub(super) fn klicktest_ui(ui: &mut egui::Ui, st: &mut KlickState) {
if !st.loaded {
st.load();
}
panel(ui, "Klicktests (nur Entwicklung)", |ui| {
ui.horizontal_wrapped(|ui| {
if ui.button("Neu laden").clicked() {
st.load();
}
ui.label(
RichText::new(st.root.join("KLICKTESTS.md").display().to_string()).color(ENGRAVING),
);
});
if let Some(e) = &st.error {
ui.colored_label(LED_RED, e);
return;
}
let (total, ok, bad, never) = st.counts();
ui.horizontal_wrapped(|ui| {
ui.label(
RichText::new(format!("{total} Tests in {} Prozessen", st.processes.len()))
.strong(),
);
ui.label(RichText::new(format!("✓ {ok}")).color(LED_GREEN));
ui.label(RichText::new(format!("✗ {bad}")).color(LED_RED));
ui.label(RichText::new(format!("noch nie geprüft {never}")).color(ENGRAVING));
ui.separator();
let state = if st.commit.is_empty() {
"?"
} else {
st.commit.as_str()
};
ui.label(format!(
"Commit {state}{}",
if st.dirty {
" (ungespeicherte Änderungen)"
} else {
""
}
));
});
match &st.message {
Some((true, m)) => ui.colored_label(LED_GREEN, m),
Some((false, m)) => ui.colored_label(LED_RED, m),
None => ui.label(""),
};
});
if st.error.is_some() {
return;
}
ui.add_space(6.0);
let processes = st.processes.clone();
for p in &processes {
let done = p
.tests
.iter()
.filter(|t| st.results.get(&t.id).is_some_and(|r| r.ok))
.count();
let title = format!("{} {done}/{} ✓", p.name, p.tests.len());
egui::CollapsingHeader::new(RichText::new(title).strong().color(AMBER))
.id_salt(&p.name)
.show(ui, |ui| {
ui.label(&p.purpose);
let covers: Vec<String> = p.covers.iter().map(|c| format!("#{c}")).collect();
ui.label(
RichText::new(format!("Deckt ab: {}", covers.join(", ")))
.small()
.color(ENGRAVING),
);
if !p.precondition.is_empty() {
ui.label(RichText::new(format!("Voraussetzung: {}", p.precondition)).small());
}
if !p.how.is_empty() {
ui.label(RichText::new(format!("So gehst du vor: {}", p.how)).small());
}
ui.add_space(4.0);
for t in &p.tests {
test_row(ui, st, t);
}
});
}
}
fn test_row(ui: &mut egui::Ui, st: &mut KlickState, t: &Test) {
let frame = egui::Frame::new()
.fill(PLATE_BG)
.stroke(Stroke::new(1.0, PLATE_EDGE))
.corner_radius(6.0)
.inner_margin(egui::Margin::symmetric(10, 6));
frame.show(ui, |ui| {
ui.set_width(ui.available_width());
let (text, color) = result_text(st.results.get(&t.id));
ui.horizontal_wrapped(|ui| {
ui.label(RichText::new(&t.id).monospace().strong().color(AMBER));
ui.label(RichText::new(&t.art).small().color(ENGRAVING));
ui.label(RichText::new(text).color(color));
});
ui.label(format!("Schritte: {}", t.steps));
ui.label(format!("Erwartet: {}", t.expected));
if t.is_manual() {
let note = st.notes.entry(t.id.clone()).or_default();
ui.add(
egui::TextEdit::singleline(note)
.desired_width(f32::INFINITY)
.hint_text("Notiz (bei ✗ Pflicht)"),
);
ui.horizontal(|ui| {
if ui.button("✓ bestanden").clicked() {
st.record(t, true);
}
if ui.button("✗ nicht bestanden").clicked() {
st.record(t, false);
}
});
} else {
ui.label(
RichText::new("läuft ohne Mensch (Befehl in den Schritten)")
.small()
.color(ENGRAVING),
);
}
});
ui.add_space(4.0);
}
#[cfg(test)]
mod tests {
use super::*;
fn state_in(dir: &std::path::Path) -> KlickState {
let mut st = KlickState::new();
st.root = dir.to_path_buf();
st
}
fn fixture(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!(
"singtrainer-klickview-{name}-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
std::fs::write(
d.join("KLICKTESTS.md"),
"## demo2test\n\n**Zweck:** Z.\n**Deckt ab:** #1001\n\n| Test | Schritte | Erwartet | Art |\n| --- | --- | --- | --- |\n| demo2test.1 | tun | geht | manuell |\n| demo2test.2 | `cargo test` | grün | auto |\n",
)
.unwrap();
d
}
#[test]
fn missing_file_gives_hint() {
let mut st = state_in(std::path::Path::new("/nonexistent-dir"));
st.load();
assert!(st.error.as_deref().is_some_and(|e| e.contains("make run")));
assert!(st.processes.is_empty());
}
#[test]
fn recording_writes_report_and_updates_counts() {
let d = fixture("record");
let mut st = state_in(&d);
st.load();
assert_eq!(st.counts(), (2, 0, 0, 2));
let t = st.processes[0].tests[0].clone();
st.record(&t, true);
assert!(
st.message.as_ref().is_some_and(|(ok, _)| *ok),
"{:?}",
st.message
);
assert_eq!(st.counts(), (2, 1, 0, 1));
let files: Vec<_> = std::fs::read_dir(d.join("testberichte"))
.unwrap()
.flatten()
.collect();
assert_eq!(files.len(), 1);
std::fs::remove_dir_all(&d).unwrap();
}
#[test]
fn failing_without_note_is_refused_and_writes_nothing() {
let d = fixture("fail");
let mut st = state_in(&d);
st.load();
let t = st.processes[0].tests[0].clone();
st.record(&t, false);
assert!(
st.message
.as_ref()
.is_some_and(|(ok, m)| !*ok && m.contains("notieren"))
);
assert!(
!d.join("testberichte").exists()
|| std::fs::read_dir(d.join("testberichte")).unwrap().count() == 0
);
st.notes.insert(t.id.clone(), "Pegel blieb stehen".into());
st.record(&t, false);
assert_eq!(st.counts(), (2, 0, 1, 1));
std::fs::remove_dir_all(&d).unwrap();
}
}