Files
stimmwerk/src/autorun.rs
wlkns-dev 188269375d Auto-Tests im Testfenster ausführen und als auto-lauf-Bericht speichern (#1037)
Schaltfläche „Auto-Tests ausführen“: führt die auto-Tests aus KLICKTESTS.md nacheinander im Hintergrund aus.
Ausgeführt werden nur cargo test <Filter> und python3 -m unittest tools/<datei>.py, ohne Shell und mit geprüften
Teilen; ein Lauf gilt nur als bestanden, wenn mindestens ein Test lief. Der Bericht hat die Art auto-lauf.

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

446 lines
15 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Führt die `auto`-Tests aus `KLICKTESTS.md` aus (Testfenster im Entwickler-Reiter).
//!
//! Aus einer Markdown-Datei wird nie beliebiger Text ausgeführt: Erkannt werden nur zwei feste Formen im ersten
//! Code-Abschnitt der Schritte, und die Teile werden einzeln geprüft und ohne Shell gestartet:
//! - `cargo test <Filter>` (Filter nur aus Buchstaben, Ziffern, `_` und `::`)
//! - `python3 -m unittest tools/<datei>.py` (Pfad nur unter `tools/`, ohne `..`)
//!
//! Ein Lauf gilt nur als bestanden, wenn der Befehl erfolgreich endet **und** mindestens ein Test lief; ein Filter, der
//! nichts trifft, wäre sonst ein falsches ✓.
use std::io::Read;
use std::path::Path;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::{Duration, Instant};
/// Längste Laufzeit eines einzelnen Befehls (ein erster `cargo test` baut die Testprogramme).
const TIMEOUT: Duration = Duration::from_secs(20 * 60);
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AutoCommand {
Cargo { filter: String },
Unittest { path: String },
}
impl AutoCommand {
/// Erkennt den Befehl im ersten Code-Abschnitt (`…`) der Schritte; alles andere ist nicht freigegeben.
pub fn parse(steps: &str) -> Option<AutoCommand> {
let code = steps.split('`').nth(1)?;
let parts: Vec<&str> = code.split_whitespace().collect();
match parts.as_slice() {
["cargo", "test", filter] if valid_filter(filter) => Some(AutoCommand::Cargo {
filter: (*filter).to_string(),
}),
["python3", "-m", "unittest", path] if valid_path(path) => {
Some(AutoCommand::Unittest {
path: (*path).to_string(),
})
}
_ => None,
}
}
/// Befehlszeile zur Anzeige.
pub fn display(&self) -> String {
match self {
AutoCommand::Cargo { filter } => format!("cargo test {filter}"),
AutoCommand::Unittest { path } => format!("python3 -m unittest {path}"),
}
}
fn to_process(&self, root: &Path) -> std::process::Command {
let mut c;
match self {
AutoCommand::Cargo { filter } => {
c = std::process::Command::new("cargo");
c.args(["test", "--locked", filter]);
}
AutoCommand::Unittest { path } => {
c = std::process::Command::new("python3");
c.args(["-m", "unittest", path]);
}
}
c.current_dir(root);
c
}
}
fn valid_filter(f: &str) -> bool {
!f.is_empty()
&& !f.starts_with('-')
&& f.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == ':')
}
fn valid_path(p: &str) -> bool {
p.starts_with("tools/")
&& p.ends_with(".py")
&& !p.contains("..")
&& !p.contains("//")
&& p.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/'))
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CmdResult {
pub ok: bool,
/// Eine Zeile für den Bericht.
pub note: String,
}
/// Letzte Zeilen der Ausgabe, auf eine Zeile gekürzt.
fn tail(output: &str) -> String {
let lines: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect();
let from = lines.len().saturating_sub(4);
let joined = lines[from..].join(" / ");
let mut s: String = joined.chars().take(400).collect();
if joined.chars().count() > 400 {
s.push('…');
}
s
}
/// Summe der bestandenen Tests aus `test result: ok. N passed; …` (mehrere Testprogramme).
fn cargo_passed(output: &str) -> u32 {
output
.lines()
.filter_map(|l| l.trim().strip_prefix("test result: ok. "))
.filter_map(|r| r.split(" passed").next()?.trim().parse::<u32>().ok())
.sum()
}
/// Anzahl der Tests aus `Ran N tests in …` (python unittest).
fn unittest_ran(output: &str) -> u32 {
output
.lines()
.find_map(|l| l.trim().strip_prefix("Ran "))
.and_then(|r| r.split(' ').next()?.parse::<u32>().ok())
.unwrap_or(0)
}
/// Bewertet das Ergebnis eines Befehls: Erfolg des Prozesses und mindestens ein gelaufener Test.
pub fn evaluate(cmd: &AutoCommand, success: bool, output: &str) -> CmdResult {
let count = match cmd {
AutoCommand::Cargo { .. } => cargo_passed(output),
AutoCommand::Unittest { .. } => unittest_ran(output),
};
if !success {
return CmdResult {
ok: false,
note: format!("fehlgeschlagen: {}", tail(output)),
};
}
if count == 0 {
return CmdResult {
ok: false,
note: "Befehl endete ohne Fehler, aber es lief kein Test (Filter trifft nichts?)"
.to_string(),
};
}
CmdResult {
ok: true,
note: format!("{} – {count} Tests bestanden", cmd.display()),
}
}
/// Startet den Befehl wirklich (ohne Shell) und wartet bis zum Ende oder bis [`TIMEOUT`].
pub fn run_real(cmd: &AutoCommand, root: &Path) -> CmdResult {
let mut process = cmd.to_process(root);
process
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
let mut child = match process.spawn() {
Ok(c) => c,
Err(e) => {
return CmdResult {
ok: false,
note: format!("{} nicht startbar: {e}", cmd.display()),
};
}
};
// Beide Ströme in eigenen Fäden lesen, damit der Prozess bei voller Pipe nicht hängt.
let read = |mut s: Box<dyn Read + Send>| {
std::thread::spawn(move || {
let mut buf = String::new();
let mut bytes = Vec::new();
let _ = s.read_to_end(&mut bytes);
buf.push_str(&String::from_utf8_lossy(&bytes));
buf
})
};
let out = child.stdout.take().map(|s| read(Box::new(s)));
let err = child.stderr.take().map(|s| read(Box::new(s)));
let start = Instant::now();
let status = loop {
match child.try_wait() {
Ok(Some(st)) => break Some(st),
Ok(None) if start.elapsed() > TIMEOUT => {
let _ = child.kill();
let _ = child.wait();
break None;
}
Ok(None) => std::thread::sleep(Duration::from_millis(100)),
Err(_) => break None,
}
};
let mut output = String::new();
for h in [out, err].into_iter().flatten() {
output.push_str(&h.join().unwrap_or_default());
output.push('\n');
}
match status {
Some(st) => evaluate(cmd, st.success(), &output),
None => CmdResult {
ok: false,
note: format!("abgebrochen nach {} Minuten", TIMEOUT.as_secs() / 60),
},
}
}
/// Führt einen Befehl aus (in Tests durch eine Attrappe ersetzbar).
pub type Runner = fn(&AutoCommand, &Path) -> CmdResult;
enum Msg {
Started(String),
Done(String, CmdResult),
Finished,
}
/// Ein laufender Satz von Auto-Tests im Hintergrund; der Aufrufer fragt mit [`AutoJob::poll`] den Stand ab.
pub struct AutoJob {
rx: Receiver<Msg>,
pub total: usize,
pub current: Option<String>,
pub results: Vec<(String, CmdResult)>,
pub finished: bool,
}
impl AutoJob {
/// Startet die Befehle nacheinander in einem Hintergrundfaden (nacheinander, damit sich `cargo` nicht selbst sperrt).
pub fn spawn(
commands: Vec<(String, AutoCommand)>,
root: std::path::PathBuf,
runner: Runner,
) -> AutoJob {
let (tx, rx): (Sender<Msg>, Receiver<Msg>) = channel();
let total = commands.len();
std::thread::spawn(move || {
for (id, cmd) in commands {
if tx.send(Msg::Started(id.clone())).is_err() {
return;
}
let r = runner(&cmd, &root);
if tx.send(Msg::Done(id, r)).is_err() {
return;
}
}
let _ = tx.send(Msg::Finished);
});
AutoJob {
rx,
total,
current: None,
results: Vec::new(),
finished: false,
}
}
/// Übernimmt alle bisher eingetroffenen Meldungen.
pub fn poll(&mut self) {
while let Ok(m) = self.rx.try_recv() {
match m {
Msg::Started(id) => self.current = Some(id),
Msg::Done(id, r) => {
self.current = None;
self.results.push((id, r));
}
Msg::Finished => self.finished = true,
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn cargo(f: &str) -> AutoCommand {
AutoCommand::Cargo { filter: f.into() }
}
#[test]
fn parses_the_two_allowed_forms_from_the_first_code_span() {
assert_eq!(
AutoCommand::parse("`cargo test pitch::` ausführen"),
Some(cargo("pitch::"))
);
assert_eq!(
AutoCommand::parse("`cargo test audio::shift` ausführen"),
Some(cargo("audio::shift"))
);
assert_eq!(
AutoCommand::parse("`python3 -m unittest tools/test_songs_import.py` ausführen"),
Some(AutoCommand::Unittest {
path: "tools/test_songs_import.py".into()
})
);
}
#[test]
fn refuses_everything_else() {
for bad in [
"kein Code hier",
"`cargo test`",
"`cargo test a b`",
"`cargo test --release`",
"`cargo test x; rm -rf /`",
"`cargo test $(id)`",
"`cargo run`",
"`sh -c cargo test x`",
"`python3 -m unittest ../x.py`",
"`python3 -m unittest /etc/x.py`",
"`python3 -m unittest tools/../x.py`",
"`python3 -m unittest tools/x.sh`",
"`python3 tools/x.py`",
"`python3 -m pytest tools/x.py`",
] {
assert_eq!(AutoCommand::parse(bad), None, "{bad}");
}
}
#[test]
fn only_the_first_code_span_counts() {
let cmd = AutoCommand::parse("`python3 -m unittest tools/a.py` und danach `rm x`");
assert_eq!(
cmd,
Some(AutoCommand::Unittest {
path: "tools/a.py".into()
})
);
assert_eq!(
AutoCommand::parse("erst `echo x` dann `cargo test a::`"),
None
);
}
#[test]
fn cargo_needs_success_and_at_least_one_passed_test() {
let ok = "running 3 tests\ntest result: ok. 3 passed; 0 failed; 0 ignored\n\nrunning 2 tests\ntest result: ok. 2 passed; 0 failed\n";
let r = evaluate(&cargo("pitch::"), true, ok);
assert!(r.ok && r.note.contains("5 Tests bestanden"), "{r:?}");
let none = "running 0 tests\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 12 filtered out\n";
let r = evaluate(&cargo("tippfehler::"), true, none);
assert!(!r.ok && r.note.contains("lief kein Test"), "{r:?}");
let failed =
"test a ... FAILED\ntest result: FAILED. 1 passed; 1 failed\nerror: test failed";
let r = evaluate(&cargo("x::"), false, failed);
assert!(
!r.ok && r.note.starts_with("fehlgeschlagen:") && r.note.contains("error: test failed"),
"{r:?}"
);
}
#[test]
fn unittest_counts_ran_tests() {
let cmd = AutoCommand::Unittest {
path: "tools/a.py".into(),
};
let ok = "..........\n----------------------------------------------------------------------\nRan 10 tests in 0.2s\n\nOK\n";
assert!(evaluate(&cmd, true, ok).ok);
let zero = "\n----------------------------------------------------------------------\nRan 0 tests in 0.0s\n\nNO TESTS RAN\n";
assert!(!evaluate(&cmd, true, zero).ok);
assert!(!evaluate(&cmd, false, "Ran 3 tests\nFAILED (failures=1)").ok);
}
#[test]
fn long_output_is_cut_to_one_short_line() {
let long = (0..50)
.map(|i| format!("zeile {i} {}", "x".repeat(200)))
.collect::<Vec<_>>()
.join("\n");
let r = evaluate(&cargo("a::"), false, &long);
assert!(
!r.note.contains('\n') && r.note.chars().count() < 450,
"{}",
r.note.len()
);
}
fn fake_runner(cmd: &AutoCommand, _root: &Path) -> CmdResult {
let ok = !matches!(cmd, AutoCommand::Cargo { filter } if filter == "rot::");
CmdResult {
ok,
note: cmd.display(),
}
}
fn wait(job: &mut AutoJob) {
for _ in 0..200 {
job.poll();
if job.finished {
return;
}
std::thread::sleep(Duration::from_millis(25));
}
panic!("Auto-Lauf wurde nicht fertig");
}
#[test]
fn job_runs_commands_in_order_and_reports_each_result() {
let cmds = vec![
("a2b.1".to_string(), cargo("gruen::")),
("a2b.2".to_string(), cargo("rot::")),
];
let mut job = AutoJob::spawn(cmds, std::path::PathBuf::from("."), fake_runner);
assert_eq!(job.total, 2);
wait(&mut job);
let ids: Vec<(&str, bool)> = job
.results
.iter()
.map(|(i, r)| (i.as_str(), r.ok))
.collect();
assert_eq!(ids, vec![("a2b.1", true), ("a2b.2", false)]);
assert!(job.current.is_none());
}
#[test]
fn real_runner_runs_a_python_unittest_of_this_repository() {
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let cmd = AutoCommand::Unittest {
path: "tools/test_forced_align.py".into(),
};
let r = run_real(&cmd, root);
assert!(r.ok, "{r:?}");
assert!(r.note.contains("Tests bestanden"));
}
/// Ruft wirklich `cargo test` auf (verschachtelt, baut ggf. die Testprogramme); deshalb nicht im normalen Lauf:
/// `cargo test real_runner_runs_a_cargo_filter -- --ignored`.
#[test]
#[ignore = "startet ein verschachteltes cargo test"]
fn real_runner_runs_a_cargo_filter() {
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let cmd = AutoCommand::Cargo {
filter: "autorun::tests::only_the_first_code_span_counts".into(),
};
let r = run_real(&cmd, root);
assert!(r.ok, "{r:?}");
assert!(r.note.contains("1 Tests bestanden"), "{r:?}");
let none = AutoCommand::Cargo {
filter: "autorun::tests::gibt_es_wirklich_nicht".into(),
};
let r = run_real(&none, root);
assert!(!r.ok && r.note.contains("lief kein Test"), "{r:?}");
}
#[test]
fn real_runner_reports_a_failing_command_as_failed() {
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let cmd = AutoCommand::Unittest {
path: "tools/gibt_es_nicht.py".into(),
};
let r = run_real(&cmd, root);
assert!(!r.ok, "{r:?}");
}
}