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>
This commit is contained in:
445
src/autorun.rs
Normal file
445
src/autorun.rs
Normal file
@ -0,0 +1,445 @@
|
|||||||
|
//! 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:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -252,6 +252,59 @@ pub fn write_report(
|
|||||||
Ok(path)
|
Ok(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Text eines Berichts der Art `auto-lauf`: je Test eine Zeile `- id: ✓ Notiz`; Gesamtergebnis ✓, wenn alle bestanden.
|
||||||
|
pub fn auto_report_text(
|
||||||
|
results: &[(String, bool, String)],
|
||||||
|
zeit: &str,
|
||||||
|
commit: &str,
|
||||||
|
hint: &str,
|
||||||
|
) -> String {
|
||||||
|
let all_ok = results.iter().all(|(_, ok, _)| *ok);
|
||||||
|
let mut out = format!(
|
||||||
|
"---\ntest: auto-lauf\nzeit: {zeit}\ncommit: {commit}\nart: auto-lauf\nergebnis: {}\n---\n",
|
||||||
|
if all_ok { "✓" } else { "✗" }
|
||||||
|
);
|
||||||
|
for (id, ok, note) in results {
|
||||||
|
let note = note.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||||
|
out.push_str(&format!("- {id}: {}", if *ok { "✓" } else { "✗" }));
|
||||||
|
if !note.is_empty() {
|
||||||
|
out.push(' ');
|
||||||
|
out.push_str(¬e);
|
||||||
|
}
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
let hint = hint.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||||
|
if !hint.is_empty() {
|
||||||
|
out.push_str(&hint);
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Schreibt einen `auto-lauf`-Bericht und überschreibt nie eine vorhandene Datei.
|
||||||
|
pub fn write_auto_report(
|
||||||
|
dir: &Path,
|
||||||
|
results: &[(String, bool, String)],
|
||||||
|
zeit: &str,
|
||||||
|
commit: &str,
|
||||||
|
hint: &str,
|
||||||
|
) -> Result<PathBuf, String> {
|
||||||
|
if results.is_empty() {
|
||||||
|
return Err("Kein Ergebnis zum Speichern.".into());
|
||||||
|
}
|
||||||
|
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||||
|
let path = dir.join(report_file_name(zeit, "auto-lauf"));
|
||||||
|
if path.exists() {
|
||||||
|
return Err(format!(
|
||||||
|
"{} gibt es schon (gleiche Minute); eine Minute warten.",
|
||||||
|
path.display()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
std::fs::write(&path, auto_report_text(results, zeit, commit, hint))
|
||||||
|
.map_err(|e| format!("{}: {e}", path.display()))?;
|
||||||
|
Ok(path)
|
||||||
|
}
|
||||||
|
|
||||||
/// Kurz-Hash des aktuellen Commits und ob der Arbeitsordner ungespeicherte Änderungen hat.
|
/// Kurz-Hash des aktuellen Commits und ob der Arbeitsordner ungespeicherte Änderungen hat.
|
||||||
pub fn git_state(repo: &Path) -> (String, bool) {
|
pub fn git_state(repo: &Path) -> (String, bool) {
|
||||||
let run = |args: &[&str]| {
|
let run = |args: &[&str]| {
|
||||||
@ -432,6 +485,52 @@ mod tests {
|
|||||||
assert_eq!(next_open_manual(&p, &[], None, Some("gibt-es-nicht")), None);
|
assert_eq!(next_open_manual(&p, &[], None, Some("gibt-es-nicht")), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn auto_report_has_one_line_per_test_and_round_trips() {
|
||||||
|
let results = vec![
|
||||||
|
(
|
||||||
|
"mikro2pegel.4".to_string(),
|
||||||
|
true,
|
||||||
|
"cargo test pitch:: – 12 Tests bestanden".to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"chart2score.4".to_string(),
|
||||||
|
false,
|
||||||
|
"fehlgeschlagen: a\nb".to_string(),
|
||||||
|
),
|
||||||
|
("x2y.1".to_string(), true, String::new()),
|
||||||
|
];
|
||||||
|
let text = auto_report_text(&results, "2026-11-02 10:00", "abc1234", "Hinweis: Probe");
|
||||||
|
assert!(text.ends_with("Hinweis: Probe\n"));
|
||||||
|
assert!(
|
||||||
|
text.contains("ergebnis: ✗\n---\n"),
|
||||||
|
"ein ✗ macht das Gesamtergebnis ✗"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
text.contains("- chart2score.4: ✗ fehlgeschlagen: a b\n"),
|
||||||
|
"Zeilenumbrüche in der Notiz werden Leerzeichen"
|
||||||
|
);
|
||||||
|
assert!(text.contains("- x2y.1: ✓\n"));
|
||||||
|
let runs = parse_report("2026-11-02_1000_auto-lauf.md", &text);
|
||||||
|
assert_eq!(runs.len(), 3);
|
||||||
|
assert_eq!(
|
||||||
|
(runs[1].id.as_str(), runs[1].ok, runs[1].note.as_str()),
|
||||||
|
("chart2score.4", false, "fehlgeschlagen: a b")
|
||||||
|
);
|
||||||
|
assert!(auto_report_text(&results[..1], "z", "c", "").contains("ergebnis: ✓"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn auto_report_is_never_overwritten_and_needs_results() {
|
||||||
|
let d = tmp("autoreport");
|
||||||
|
let r = vec![("a2b.1".to_string(), true, String::new())];
|
||||||
|
assert!(write_auto_report(&d, &[], "2026-11-02 10:00", "abc", "").is_err());
|
||||||
|
assert!(write_auto_report(&d, &r, "2026-11-02 10:00", "abc", "").is_ok());
|
||||||
|
assert!(write_auto_report(&d, &r, "2026-11-02 10:00", "abc", "").is_err());
|
||||||
|
assert_eq!(load_runs(&d).len(), 1);
|
||||||
|
std::fs::remove_dir_all(&d).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn report_has_checker_format() {
|
fn report_has_checker_format() {
|
||||||
let t = parse_tests(SAMPLE)[0].tests[0].clone();
|
let t = parse_tests(SAMPLE)[0].tests[0].clone();
|
||||||
@ -507,6 +606,26 @@ mod tests {
|
|||||||
"Fehler",
|
"Fehler",
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
// Auch ein Bericht der Art auto-lauf muss das Prüfskript bestehen.
|
||||||
|
write_auto_report(
|
||||||
|
&d.join("testberichte"),
|
||||||
|
&[
|
||||||
|
(
|
||||||
|
t.id.clone(),
|
||||||
|
true,
|
||||||
|
"cargo test x:: – 3 Tests bestanden".to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"unbekannt2test.9".to_string(),
|
||||||
|
false,
|
||||||
|
"fehlgeschlagen: x".to_string(),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
"2026-11-02 09:32",
|
||||||
|
"abc1234",
|
||||||
|
"Hinweis: Probe",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
let out = std::process::Command::new("python3")
|
let out = std::process::Command::new("python3")
|
||||||
.arg(repo.join("tools/check-roadmap.py"))
|
.arg(repo.join("tools/check-roadmap.py"))
|
||||||
.arg(&d)
|
.arg(&d)
|
||||||
|
|||||||
@ -1,4 +1,5 @@
|
|||||||
mod audio;
|
mod audio;
|
||||||
|
mod autorun;
|
||||||
mod calib;
|
mod calib;
|
||||||
mod chart;
|
mod chart;
|
||||||
mod config;
|
mod config;
|
||||||
|
|||||||
@ -205,6 +205,8 @@ fn test_window_guides_a_manual_run_without_writing_a_report() {
|
|||||||
h.run_steps(3);
|
h.run_steps(3);
|
||||||
h.get_by_label("Tests").click();
|
h.get_by_label("Tests").click();
|
||||||
h.run_steps(3);
|
h.run_steps(3);
|
||||||
|
// Die Schaltfläche für die auto-Tests gibt es; geklickt wird sie hier nicht (sie würde echte Befehle starten).
|
||||||
|
assert!(h.query_by_label("Auto-Tests ausführen").is_some());
|
||||||
h.get_by_label("Nächsten offenen Test starten").click();
|
h.get_by_label("Nächsten offenen Test starten").click();
|
||||||
h.run_steps(3);
|
h.run_steps(3);
|
||||||
assert!(
|
assert!(
|
||||||
@ -225,3 +227,46 @@ fn test_window_guides_a_manual_run_without_writing_a_report() {
|
|||||||
);
|
);
|
||||||
assert_eq!(reports(), before, "der Test darf keinen Bericht schreiben");
|
assert_eq!(reports(), before, "der Test darf keinen Bericht schreiben");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Drückt „Auto-Tests ausführen“ wirklich und führt alle `auto`-Tests aus `KLICKTESTS.md` aus (mehrere Minuten, startet
|
||||||
|
/// verschachtelte `cargo test`). Nur von Hand: `cargo test real_auto_run_end_to_end -- --ignored --nocapture`.
|
||||||
|
/// Der entstandene Bericht wird gezeigt und danach wieder gelöscht.
|
||||||
|
#[test]
|
||||||
|
#[ignore = "führt die echten auto-Tests aus"]
|
||||||
|
fn real_auto_run_end_to_end() {
|
||||||
|
let reports = || -> Vec<std::path::PathBuf> {
|
||||||
|
std::fs::read_dir("testberichte")
|
||||||
|
.map(|d| d.flatten().map(|e| e.path()).collect())
|
||||||
|
.unwrap_or_default()
|
||||||
|
};
|
||||||
|
let before = reports();
|
||||||
|
let mut h = harness();
|
||||||
|
h.get_by_label("Roadmap").click();
|
||||||
|
h.run_steps(3);
|
||||||
|
h.get_by_label("Tests").click();
|
||||||
|
h.run_steps(3);
|
||||||
|
h.get_by_label("Auto-Tests ausführen").click();
|
||||||
|
let start = std::time::Instant::now();
|
||||||
|
loop {
|
||||||
|
h.run_steps(2);
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||||
|
if reports().len() > before.len() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
start.elapsed().as_secs() < 25 * 60,
|
||||||
|
"Auto-Lauf nach 25 Minuten nicht fertig"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let new: Vec<_> = reports()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|p| !before.contains(p))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(new.len(), 1, "genau ein neuer Bericht");
|
||||||
|
eprintln!(
|
||||||
|
"Dauer: {} s\n{}",
|
||||||
|
start.elapsed().as_secs(),
|
||||||
|
std::fs::read_to_string(&new[0]).unwrap()
|
||||||
|
);
|
||||||
|
std::fs::remove_file(&new[0]).unwrap();
|
||||||
|
}
|
||||||
|
|||||||
@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
use super::gear::{AMBER, ENGRAVING, LED_GREEN, LED_RED, PLATE_BG, PLATE_EDGE, panel};
|
use super::gear::{AMBER, ENGRAVING, LED_GREEN, LED_RED, PLATE_BG, PLATE_EDGE, panel};
|
||||||
use super::roadmap_view::md_label;
|
use super::roadmap_view::md_label;
|
||||||
|
use crate::autorun::{AutoCommand, AutoJob, Runner, run_real};
|
||||||
use crate::klicktests::{self, Process, Test, TestRun};
|
use crate::klicktests::{self, Process, Test, TestRun};
|
||||||
use eframe::egui::{self, Color32, RichText, Stroke};
|
use eframe::egui::{self, Color32, RichText, Stroke};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
@ -34,6 +35,8 @@ pub(super) struct KlickState {
|
|||||||
message: Option<(bool, String)>,
|
message: Option<(bool, String)>,
|
||||||
commit: String,
|
commit: String,
|
||||||
dirty: bool,
|
dirty: bool,
|
||||||
|
/// Laufender Satz von Auto-Tests im Hintergrund.
|
||||||
|
auto: Option<AutoJob>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl KlickState {
|
impl KlickState {
|
||||||
@ -52,6 +55,7 @@ impl KlickState {
|
|||||||
message: None,
|
message: None,
|
||||||
commit: String::new(),
|
commit: String::new(),
|
||||||
dirty: false,
|
dirty: false,
|
||||||
|
auto: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -178,6 +182,107 @@ impl KlickState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Auto-Tests im Geltungsbereich (Prozessfilter) mit freigegebenem Befehl und die IDs der übersprungenen.
|
||||||
|
fn auto_commands(&self) -> (Vec<(String, AutoCommand)>, Vec<String>) {
|
||||||
|
let (mut run, mut skipped) = (Vec::new(), Vec::new());
|
||||||
|
for t in self
|
||||||
|
.processes
|
||||||
|
.iter()
|
||||||
|
.filter(|p| self.process_filter.as_deref().is_none_or(|n| p.name == n))
|
||||||
|
.flat_map(|p| &p.tests)
|
||||||
|
.filter(|t| !t.is_manual())
|
||||||
|
{
|
||||||
|
match AutoCommand::parse(&t.steps) {
|
||||||
|
Some(c) => run.push((t.id.clone(), c)),
|
||||||
|
None => skipped.push(t.id.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(run, skipped)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn auto_running(&self) -> bool {
|
||||||
|
self.auto.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_auto(&mut self) {
|
||||||
|
self.start_auto_with(run_real);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_auto_with(&mut self, runner: Runner) {
|
||||||
|
if self.auto.is_some() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let (cmds, skipped) = self.auto_commands();
|
||||||
|
if cmds.is_empty() {
|
||||||
|
self.message = Some((
|
||||||
|
false,
|
||||||
|
"Kein auto-Test mit freigegebenem Befehl.".to_string(),
|
||||||
|
));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let extra = if skipped.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
format!(", {} ohne freigegebenen Befehl übersprungen", skipped.len())
|
||||||
|
};
|
||||||
|
self.message = Some((
|
||||||
|
true,
|
||||||
|
format!("Auto-Tests gestartet: {} Befehle{extra}.", cmds.len()),
|
||||||
|
));
|
||||||
|
self.auto = Some(AutoJob::spawn(cmds, self.root.clone(), runner));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Übernimmt Meldungen des Hintergrundlaufs; schreibt den Bericht, sobald alles durch ist.
|
||||||
|
fn poll_auto(&mut self) {
|
||||||
|
let Some(job) = self.auto.as_mut() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
job.poll();
|
||||||
|
if !job.finished {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let results: Vec<(String, bool, String)> = job
|
||||||
|
.results
|
||||||
|
.iter()
|
||||||
|
.map(|(id, r)| (id.clone(), r.ok, r.note.clone()))
|
||||||
|
.collect();
|
||||||
|
self.auto = None;
|
||||||
|
let (_, skipped) = self.auto_commands();
|
||||||
|
let mut hint = Vec::new();
|
||||||
|
if self.dirty {
|
||||||
|
hint.push("Hinweis: Der Arbeitsordner hatte ungespeicherte Änderungen; die Commit-Kennung nennt nur den letzten Commit.".to_string());
|
||||||
|
}
|
||||||
|
if !skipped.is_empty() {
|
||||||
|
hint.push(format!(
|
||||||
|
"Nicht ausgeführt (kein freigegebener Befehl): {}.",
|
||||||
|
skipped.join(", ")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let zeit = klicktests::now_stamp();
|
||||||
|
let dir = self.root.join("testberichte");
|
||||||
|
let passed = results.iter().filter(|(_, ok, _)| *ok).count();
|
||||||
|
self.message = Some(
|
||||||
|
match klicktests::write_auto_report(
|
||||||
|
&dir,
|
||||||
|
&results,
|
||||||
|
&zeit,
|
||||||
|
&self.commit,
|
||||||
|
&hint.join(" "),
|
||||||
|
) {
|
||||||
|
Ok(path) => (
|
||||||
|
passed == results.len(),
|
||||||
|
format!(
|
||||||
|
"Auto-Lauf fertig: {passed} von {} bestanden. Bericht: {}",
|
||||||
|
results.len(),
|
||||||
|
path.display()
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Err(e) => (false, e),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
self.reload_runs();
|
||||||
|
}
|
||||||
|
|
||||||
/// Wählt den nächsten offenen manuellen Test (nach dem aktuellen); ohne weiteren schließt es den Testlauf.
|
/// Wählt den nächsten offenen manuellen Test (nach dem aktuellen); ohne weiteren schließt es den Testlauf.
|
||||||
pub fn next_open(&mut self) {
|
pub fn next_open(&mut self) {
|
||||||
let after = self.selected.clone();
|
let after = self.selected.clone();
|
||||||
@ -349,6 +454,11 @@ fn run_panel(ui: &mut egui::Ui, st: &mut KlickState) {
|
|||||||
/// Zeigt die Klicktests; gibt eine Stand-ID zurück, wenn ein Verweis „Deckt ab“ angeklickt wurde.
|
/// Zeigt die Klicktests; gibt eine Stand-ID zurück, wenn ein Verweis „Deckt ab“ angeklickt wurde.
|
||||||
pub(super) fn klicktest_ui(ui: &mut egui::Ui, st: &mut KlickState) -> Option<u32> {
|
pub(super) fn klicktest_ui(ui: &mut egui::Ui, st: &mut KlickState) -> Option<u32> {
|
||||||
st.ensure_loaded();
|
st.ensure_loaded();
|
||||||
|
st.poll_auto();
|
||||||
|
if st.auto_running() {
|
||||||
|
ui.ctx()
|
||||||
|
.request_repaint_after(std::time::Duration::from_millis(250));
|
||||||
|
}
|
||||||
let mut jump = None;
|
let mut jump = None;
|
||||||
panel(ui, "Klicktests (nur Entwicklung)", |ui| {
|
panel(ui, "Klicktests (nur Entwicklung)", |ui| {
|
||||||
ui.horizontal_wrapped(|ui| {
|
ui.horizontal_wrapped(|ui| {
|
||||||
@ -449,6 +559,25 @@ pub(super) fn klicktest_ui(ui: &mut egui::Ui, st: &mut KlickState) -> Option<u32
|
|||||||
{
|
{
|
||||||
st.select(&id);
|
st.select(&id);
|
||||||
}
|
}
|
||||||
|
let (auto_cmds, _) = st.auto_commands();
|
||||||
|
if ui
|
||||||
|
.add_enabled(
|
||||||
|
!st.auto_running() && !auto_cmds.is_empty(),
|
||||||
|
egui::Button::new("Auto-Tests ausführen"),
|
||||||
|
)
|
||||||
|
.on_hover_text("Führt die auto-Tests nacheinander aus (cargo test, python3 -m unittest), das kann Minuten dauern, und schreibt einen auto-lauf-Bericht.")
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
st.start_auto();
|
||||||
|
}
|
||||||
|
if let Some(job) = &st.auto {
|
||||||
|
let now = job.current.as_deref().unwrap_or("…");
|
||||||
|
ui.label(
|
||||||
|
RichText::new(format!("Auto-Tests: {}/{} fertig, läuft {now}", job.results.len(), job.total))
|
||||||
|
.small()
|
||||||
|
.color(AMBER),
|
||||||
|
);
|
||||||
|
}
|
||||||
for (f, text) in [
|
for (f, text) in [
|
||||||
(ResFilter::All, format!("Alle ({total})")),
|
(ResFilter::All, format!("Alle ({total})")),
|
||||||
(ResFilter::Ok, format!("✓ {ok}")),
|
(ResFilter::Ok, format!("✓ {ok}")),
|
||||||
@ -542,11 +671,11 @@ fn test_row(ui: &mut egui::Ui, st: &mut KlickState, t: &Test) {
|
|||||||
md_label(ui, &format!("**Schritte:** {}", t.steps));
|
md_label(ui, &format!("**Schritte:** {}", t.steps));
|
||||||
md_label(ui, &format!("**Erwartet:** {}", t.expected));
|
md_label(ui, &format!("**Erwartet:** {}", t.expected));
|
||||||
if !t.is_manual() {
|
if !t.is_manual() {
|
||||||
ui.label(
|
let text = match AutoCommand::parse(&t.steps) {
|
||||||
RichText::new("läuft ohne Mensch (Befehl in den Schritten)")
|
Some(c) => format!("läuft ohne Mensch: {}", c.display()),
|
||||||
.small()
|
None => "kein freigegebener Befehl: wird nicht ausgeführt".to_string(),
|
||||||
.color(ENGRAVING),
|
};
|
||||||
);
|
ui.label(RichText::new(text).small().color(ENGRAVING));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
ui.add_space(4.0);
|
ui.add_space(4.0);
|
||||||
@ -685,4 +814,131 @@ mod tests {
|
|||||||
assert_eq!(st.covering(1001), vec![("demo2test".to_string(), 1, 3)]);
|
assert_eq!(st.covering(1001), vec![("demo2test".to_string(), 1, 3)]);
|
||||||
std::fs::remove_dir_all(&d).unwrap();
|
std::fs::remove_dir_all(&d).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn auto_fixture(name: &str) -> PathBuf {
|
||||||
|
let d = std::env::temp_dir().join(format!(
|
||||||
|
"singtrainer-klickauto-{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"),
|
||||||
|
"## auto2test\n\n**Zweck:** Z.\n**Deckt ab:** #1001\n\n| Test | Schritte | Erwartet | Art |\n| --- | --- | --- | --- |\n| auto2test.1 | `cargo test gruen::` ausführen | grün | auto |\n| auto2test.2 | `cargo test rot::` ausführen | grün | auto |\n| auto2test.3 | `rm -rf x` ausführen | nichts | auto |\n| auto2test.4 | klicken | geht | manuell |\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fake_runner(cmd: &AutoCommand, _root: &std::path::Path) -> crate::autorun::CmdResult {
|
||||||
|
let red = matches!(cmd, AutoCommand::Cargo { filter } if filter == "rot::");
|
||||||
|
crate::autorun::CmdResult {
|
||||||
|
ok: !red,
|
||||||
|
note: if red {
|
||||||
|
"fehlgeschlagen: rot".into()
|
||||||
|
} else {
|
||||||
|
format!("{} – 2 Tests bestanden", cmd.display())
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wait_for_auto(st: &mut KlickState) {
|
||||||
|
for _ in 0..200 {
|
||||||
|
st.poll_auto();
|
||||||
|
if !st.auto_running() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(25));
|
||||||
|
}
|
||||||
|
panic!("Auto-Lauf wurde nicht fertig");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_approved_auto_commands_are_run_and_the_rest_is_reported_as_skipped() {
|
||||||
|
let d = auto_fixture("scope");
|
||||||
|
let mut st = state_in(&d);
|
||||||
|
st.load();
|
||||||
|
let (run, skipped) = st.auto_commands();
|
||||||
|
assert_eq!(
|
||||||
|
run.iter().map(|(i, _)| i.as_str()).collect::<Vec<_>>(),
|
||||||
|
["auto2test.1", "auto2test.2"]
|
||||||
|
);
|
||||||
|
assert_eq!(skipped, ["auto2test.3"], "rm -rf wird nie ausgeführt");
|
||||||
|
st.process_filter = Some("gibt-es-nicht".into());
|
||||||
|
assert!(st.auto_commands().0.is_empty());
|
||||||
|
std::fs::remove_dir_all(&d).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn auto_run_writes_one_auto_lauf_report_and_updates_the_results() {
|
||||||
|
let d = auto_fixture("run");
|
||||||
|
let mut st = state_in(&d);
|
||||||
|
st.load();
|
||||||
|
st.start_auto_with(fake_runner);
|
||||||
|
assert!(st.auto_running());
|
||||||
|
wait_for_auto(&mut st);
|
||||||
|
let files: Vec<_> = std::fs::read_dir(d.join("testberichte"))
|
||||||
|
.unwrap()
|
||||||
|
.flatten()
|
||||||
|
.collect();
|
||||||
|
assert_eq!(files.len(), 1);
|
||||||
|
assert!(
|
||||||
|
files[0]
|
||||||
|
.file_name()
|
||||||
|
.to_string_lossy()
|
||||||
|
.ends_with("_auto-lauf.md")
|
||||||
|
);
|
||||||
|
let text = std::fs::read_to_string(files[0].path()).unwrap();
|
||||||
|
assert!(
|
||||||
|
text.contains("ergebnis: ✗"),
|
||||||
|
"ein rotes Ergebnis macht den Lauf ✗"
|
||||||
|
);
|
||||||
|
assert!(text.contains("- auto2test.1: ✓ cargo test gruen:: – 2 Tests bestanden"));
|
||||||
|
assert!(text.contains("- auto2test.2: ✗ fehlgeschlagen: rot"));
|
||||||
|
assert!(text.contains("Nicht ausgeführt (kein freigegebener Befehl): auto2test.3."));
|
||||||
|
// Die Anzeige übernimmt die Läufe: 1 ✓, 1 ✗, 2 nie geprüft (der übersprungene auto und der manuelle).
|
||||||
|
assert_eq!(st.counts(), (4, 1, 1, 2));
|
||||||
|
assert_eq!(
|
||||||
|
klicktests::last_run(&st.runs, "auto2test.1").unwrap().art,
|
||||||
|
"auto-lauf"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
st.message
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|(ok, m)| !*ok && m.contains("1 von 2 bestanden")),
|
||||||
|
"{:?}",
|
||||||
|
st.message
|
||||||
|
);
|
||||||
|
std::fs::remove_dir_all(&d).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn starting_twice_or_without_commands_does_not_run_anything() {
|
||||||
|
let d = fixture("noauto");
|
||||||
|
let mut st = state_in(&d);
|
||||||
|
st.load();
|
||||||
|
st.start_auto_with(fake_runner);
|
||||||
|
assert!(
|
||||||
|
!st.auto_running(),
|
||||||
|
"`cargo test` ohne Filter ist nicht freigegeben"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
st.message
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|(ok, m)| !*ok && m.contains("freigegebenem Befehl"))
|
||||||
|
);
|
||||||
|
std::fs::remove_dir_all(&d).unwrap();
|
||||||
|
let d = auto_fixture("twice");
|
||||||
|
let mut st = state_in(&d);
|
||||||
|
st.load();
|
||||||
|
st.start_auto_with(fake_runner);
|
||||||
|
st.start_auto_with(fake_runner);
|
||||||
|
wait_for_auto(&mut st);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_dir(d.join("testberichte")).unwrap().count(),
|
||||||
|
1,
|
||||||
|
"nur ein Bericht"
|
||||||
|
);
|
||||||
|
std::fs::remove_dir_all(&d).unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user