M5: affected tests at turn end (closes #35 #36 #37 #38 #39 #40 #41)
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s

This commit is contained in:
hermes committed 2026-09-30 15:03:17 +00:00
1 parent 4592887325
commit f4e55c8dd3
8 files changed
+1347

No files matched your search

+881
View File
@@ -0,0 +1,881 @@
//! Test adapters: detect the framework for a file, run a scoped selection, parse structured output.
//!
//! cargo (libtest output), pytest (JUnit XML), vitest/jest (JSON reporter), go (`go test -json`).
use crate::manager::which;
use crate::runners::marker_root;
use serde_json::Value;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::process::Command;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Adapter {
Cargo,
Pytest,
Vitest,
Jest,
Go,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Failure {
pub name: String,
/// test file, when the framework reports it
pub file: Option<PathBuf>,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Outcome {
pub passed: usize,
pub failures: Vec<Failure>,
}
/// One scoped run: `targets` empty = the whole root (cargo crate), else test files (py/js) or package dirs (go).
#[derive(Debug, Clone, PartialEq)]
pub struct Run {
pub adapter: Adapter,
pub root: PathBuf,
pub targets: Vec<PathBuf>,
}
pub fn is_test_file(p: &Path) -> bool {
let n = p.file_name().and_then(|s| s.to_str()).unwrap_or_default();
let in_tests_dir = p
.components()
.any(|c| matches!(c.as_os_str().to_str(), Some("tests" | "__tests__")));
match p.extension().and_then(|e| e.to_str()).unwrap_or_default() {
"py" => n.starts_with("test_") || n.ends_with("_test.py"),
"go" => n.ends_with("_test.go"),
"js" | "jsx" | "ts" | "tsx" | "mjs" | "cjs" => {
n.contains(".test.") || n.contains(".spec.") || in_tests_dir && n != "index.ts"
}
"rs" => in_tests_dir,
_ => false,
}
}
/// Framework + root for `file`, or None when no supported test setup is found.
pub fn detect(file: &Path, ws: &Path) -> Option<(Adapter, PathBuf)> {
match file.extension().and_then(|e| e.to_str())? {
"rs" => Some((Adapter::Cargo, marker_root(file, &["Cargo.toml"], ws)?)),
"go" => Some((Adapter::Go, marker_root(file, &["go.mod"], ws)?)),
"py" => Some((
Adapter::Pytest,
marker_root(
file,
&[
"pytest.ini",
"pyproject.toml",
"setup.cfg",
"tox.ini",
"conftest.py",
],
ws,
)?,
)),
"js" | "jsx" | "ts" | "tsx" | "mjs" | "cjs" => {
let root = marker_root(file, &["package.json"], ws)?;
let pkg = std::fs::read_to_string(root.join("package.json")).unwrap_or_default();
if pkg.contains("\"vitest\"") {
Some((Adapter::Vitest, root))
} else if pkg.contains("\"jest\"") {
Some((Adapter::Jest, root))
} else {
None
}
}
_ => None,
}
}
pub fn installed(a: Adapter, root: &Path) -> bool {
match a {
Adapter::Cargo => which("cargo"),
Adapter::Go => which("go"),
Adapter::Pytest => which("pytest"),
Adapter::Vitest => root.join("node_modules/.bin/vitest").exists() || which("vitest"),
Adapter::Jest => root.join("node_modules/.bin/jest").exists() || which("jest"),
}
}
/// Execute `run`. Err = could not produce results (timeout, build failure without test output, etc).
pub async fn run(r: &Run, timeout: Duration) -> Result<Outcome, String> {
let tmp = std::env::temp_dir().join(format!(
"hx-test-{}-{}",
std::process::id(),
hx_ai::auth::now_ms()
));
let bin = |b: &str| {
let local = r.root.join("node_modules/.bin").join(b);
if local.exists() {
local
} else {
PathBuf::from(b)
}
};
let mut cmd = match r.adapter {
Adapter::Cargo => {
let mut c = Command::new("cargo");
c.args(["test", "--no-fail-fast", "--color", "never"]);
c
}
Adapter::Pytest => {
let mut c = Command::new("pytest");
c.args(["-q", "-p", "no:cacheprovider", "--junitxml"])
.arg(&tmp)
.args(&r.targets);
c
}
Adapter::Vitest => {
let mut c = Command::new(bin("vitest"));
c.args(["run", "--reporter=json", "--outputFile"])
.arg(&tmp)
.args(&r.targets);
c
}
Adapter::Jest => {
let mut c = Command::new(bin("jest"));
c.args(["--json", "--outputFile"])
.arg(&tmp)
.args(&r.targets);
c
}
Adapter::Go => {
let mut c = Command::new("go");
c.args(["test", "-json"]);
c.args(r.targets.iter().map(|d| {
let rel = d.strip_prefix(&r.root).unwrap_or(d);
format!("./{}", rel.display())
}));
c
}
};
cmd.current_dir(&r.root)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true);
let o = match tokio::time::timeout(timeout, cmd.output()).await {
Err(_) => return Err(format!("timed out after {}s", timeout.as_secs())),
Ok(Err(e)) => return Err(e.to_string()),
Ok(Ok(o)) => o,
};
let stdout = String::from_utf8_lossy(&o.stdout);
let stderr = String::from_utf8_lossy(&o.stderr);
let file = std::fs::read_to_string(&tmp).ok();
let _ = std::fs::remove_file(&tmp);
let res = match r.adapter {
Adapter::Cargo => Ok(parse_libtest(&stdout)),
Adapter::Go => Ok(parse_go(&stdout)),
Adapter::Pytest => file
.as_deref()
.map(|x| parse_junit(x, &r.root))
.ok_or_else(|| "no junit report".to_string()),
Adapter::Vitest | Adapter::Jest => file
.as_deref()
.ok_or_else(|| "no json report".to_string())
.and_then(parse_jest),
};
match res {
Ok(out) if out.passed == 0 && out.failures.is_empty() && !o.status.success() => {
// nothing ran and the command failed: build/collection error
let tail: Vec<&str> = stderr.lines().chain(stdout.lines()).collect();
let tail = tail[tail.len().saturating_sub(8)..].join("\n");
Err(format!("test run failed:\n{tail}"))
}
x => x,
}
}
fn clip(s: &str, lines: usize) -> String {
let v: Vec<&str> = s.trim().lines().collect();
let mut out = v[..v.len().min(lines)].join("\n");
if v.len() > lines {
out.push_str(&format!("\n… {} more lines", v.len() - lines));
}
out
}
/// libtest human output (`cargo test`).
pub fn parse_libtest(s: &str) -> Outcome {
let mut out = Outcome::default();
let mut msgs: HashMap<String, String> = HashMap::new();
let mut cur: Option<(String, String)> = None;
for line in s.lines() {
if let Some(rest) = line.strip_prefix("test ") {
if let Some(name) = rest.strip_suffix(" ... ok") {
let _ = name;
out.passed += 1;
} else if let Some(name) = rest.strip_suffix(" ... FAILED") {
out.failures.push(Failure {
name: name.to_string(),
file: None,
message: String::new(),
});
}
}
if let Some(n) = line
.strip_prefix("---- ")
.and_then(|x| x.strip_suffix(" stdout ----"))
{
if let Some((k, v)) = cur.take() {
msgs.insert(k, v);
}
cur = Some((n.to_string(), String::new()));
continue;
}
if line == "failures:" || line.starts_with("test result:") {
if let Some((k, v)) = cur.take() {
msgs.insert(k, v);
}
continue;
}
if let Some((_, v)) = cur.as_mut()
&& !line.starts_with("note: run with `RUST_BACKTRACE")
{
// drop the per-run thread id: "thread 'x' (1234) panicked" -> "thread 'x' panicked"
let line = match (line.find("' ("), line.find(") panicked")) {
(Some(a), Some(b)) if line.starts_with("thread '") && a < b => {
format!("{}'{}", &line[..a], &line[b + 1..])
}
_ => line.to_string(),
};
v.push_str(&line);
v.push('\n');
}
}
for f in &mut out.failures {
f.message = clip(msgs.get(&f.name).map_or("", |s| s), 12);
}
out
}
fn unescape(s: &str) -> String {
s.replace("&lt;", "<")
.replace("&gt;", ">")
.replace("&quot;", "\"")
.replace("&apos;", "'")
.replace("&#10;", "\n")
.replace("&amp;", "&")
}
fn attr(tag: &str, name: &str) -> Option<String> {
let k = format!(" {name}=\"");
let i = tag.find(&k)? + k.len();
Some(unescape(&tag[i..i + tag[i..].find('"')?]))
}
/// JUnit XML (pytest `--junitxml`, nextest). Hand-rolled: only `<testcase>` + `<failure>`/`<error>`.
pub fn parse_junit(s: &str, root: &Path) -> Outcome {
let mut out = Outcome::default();
let mut rest = s;
while let Some(i) = rest.find("<testcase") {
rest = &rest[i..];
let open_end = rest.find('>').unwrap_or(rest.len() - 1);
let tag = &rest[..=open_end];
let body_end = if tag.ends_with("/>") {
open_end + 1
} else {
rest.find("</testcase>").map_or(rest.len(), |e| e + 11)
};
let body = &rest[open_end + 1..body_end.max(open_end + 1)];
let name = match (attr(tag, "classname"), attr(tag, "name")) {
(Some(c), Some(n)) if !c.is_empty() => format!("{c}::{n}"),
(_, n) => n.unwrap_or_default(),
};
let fail = ["<failure", "<error"].iter().find_map(|t| body.find(t));
match fail {
Some(j) => {
let ftag_end = body[j..].find('>').map_or(body.len(), |e| j + e);
let ftag = &body[j..=ftag_end.min(body.len() - 1)];
let text_end = body[ftag_end..]
.find("</")
.map_or(body.len(), |e| ftag_end + e);
let text = unescape(body.get(ftag_end + 1..text_end).unwrap_or_default());
let msg = if text.trim().is_empty() {
attr(ftag, "message").unwrap_or_default()
} else {
text
};
out.failures.push(Failure {
name,
file: attr(tag, "file").map(|f| root.join(f)),
message: clip(&msg, 12),
});
}
None if body.contains("<skipped") => {}
None => out.passed += 1,
}
rest = &rest[body_end.min(rest.len())..];
}
out
}
/// Jest / vitest JSON reporter.
pub fn parse_jest(s: &str) -> Result<Outcome, String> {
let v: Value = serde_json::from_str(s).map_err(|e| format!("bad json report: {e}"))?;
let mut out = Outcome::default();
for tr in v["testResults"].as_array().into_iter().flatten() {
let file = tr["name"].as_str().map(PathBuf::from);
let asserts = tr["assertionResults"]
.as_array()
.cloned()
.unwrap_or_default();
for a in &asserts {
match a["status"].as_str() {
Some("passed") => out.passed += 1,
Some("failed") => out.failures.push(Failure {
name: a["fullName"].as_str().unwrap_or_default().to_string(),
file: file.clone(),
message: clip(
&a["failureMessages"]
.as_array()
.into_iter()
.flatten()
.filter_map(|m| m.as_str())
.collect::<Vec<_>>()
.join("\n"),
12,
),
}),
_ => {}
}
}
// suite-level failure (syntax error, import error) with no assertions
if asserts.is_empty() && tr["status"] == "failed" {
out.failures.push(Failure {
name: "(suite)".into(),
file: file.clone(),
message: clip(tr["message"].as_str().unwrap_or_default(), 12),
});
}
}
Ok(out)
}
/// `go test -json` event stream.
pub fn parse_go(s: &str) -> Outcome {
let mut out = Outcome::default();
let mut logs: HashMap<(String, String), String> = HashMap::new();
for line in s.lines() {
let Ok(e) = serde_json::from_str::<Value>(line) else {
continue;
};
let pkg = e["Package"].as_str().unwrap_or_default().to_string();
let test = e["Test"].as_str().unwrap_or_default().to_string();
match e["Action"].as_str() {
Some("output") => logs
.entry((pkg, test))
.or_default()
.push_str(e["Output"].as_str().unwrap_or_default()),
Some("pass") if !test.is_empty() => out.passed += 1,
Some("fail") => {
// package-level fail without tests = build failure; with tests it's just the summary
let has_test_fail = out.failures.iter().any(|f| f.name.starts_with(&pkg));
if test.is_empty() && has_test_fail {
continue;
}
let log = logs
.get(&(pkg.clone(), test.clone()))
.cloned()
.unwrap_or_default();
let log: String = log
.lines()
.filter(|l| {
let t = l.trim();
!(t.starts_with("=== ") || t.starts_with("--- FAIL") || t == "FAIL")
})
.map(|l| format!("{l}\n"))
.collect();
out.failures.push(Failure {
name: if test.is_empty() {
pkg
} else {
format!("{pkg}.{test}")
},
file: None,
message: clip(&log, 12),
});
}
_ => {}
}
}
out
}
/// Scoped selection for changed files. Heuristic (v1):
/// - Rust: `cargo test` in the changed file's crate and every crate depending on it (path/workspace deps).
/// - Go: the changed package dir + importing package dirs, one `go test` per module.
/// - Python/JS: changed test files + test files that import a changed file (up to 3 hops).
///
/// Known false positives: Rust/Go run whole crates/packages, not just affected tests. Known misses:
/// dynamic imports, fixtures/conftest changes, tests that load files at runtime (non-code files never
/// select tests).
pub fn select(changed: &[PathBuf], ws: &Path, g: &crate::deps::Graph) -> Vec<Run> {
let mut runs: Vec<Run> = vec![];
let mut push = |adapter: Adapter, root: PathBuf, target: Option<PathBuf>| match runs
.iter_mut()
.find(|r| r.adapter == adapter && r.root == root)
{
Some(r) => {
if let Some(t) = target
&& !r.targets.contains(&t)
{
r.targets.push(t);
}
}
None => runs.push(Run {
adapter,
root,
targets: target.into_iter().collect(),
}),
};
for f in changed {
let Some((a, root)) = detect(f, ws) else {
continue;
};
let node = crate::deps::node(f, ws);
let mut nodes = vec![node.clone()];
nodes.extend(g.users(&node, 3));
for n in nodes {
match a {
Adapter::Cargo => push(a, n, None),
Adapter::Go => push(a, root.clone(), Some(n)),
_ if is_test_file(&n) => {
// a user may live under a different root/framework
if let Some((a2, r2)) = detect(&n, ws) {
push(a2, r2, Some(n));
}
}
_ => {}
}
}
}
runs.sort_by(|a, b| a.root.cmp(&b.root));
runs
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TestMode {
/// after each tool round that changed files (default)
TurnEnd,
/// only when the agent is about to stop; failures make it continue
AgentEnd,
Off,
}
/// Hook: collects files the agent wrote/edited, runs the selected tests, injects failures only.
pub struct TestLens {
pub ws: PathBuf,
pub mode: TestMode,
pub timeout: Duration,
/// max characters injected per report
pub cap: usize,
pending: tokio::sync::Mutex<Vec<PathBuf>>,
/// last report, so an unchanged failure set isn't repeated every turn
last: tokio::sync::Mutex<String>,
}
impl TestLens {
pub fn new(ws: PathBuf, mode: TestMode) -> Self {
Self {
ws,
mode,
timeout: Duration::from_secs(120),
cap: 3000,
pending: Default::default(),
last: Default::default(),
}
}
/// Run tests for pending changes. None = nothing new to say.
pub async fn report(&self) -> Option<String> {
let changed: Vec<PathBuf> = std::mem::take(&mut *self.pending.lock().await);
if changed.is_empty() {
return None;
}
// ponytail: graph rebuilt per report (walk + line scan). Cache keyed by seq if it gets slow on big repos.
let g = crate::deps::build(&self.ws);
let runs = select(&changed, &self.ws, &g);
if runs.is_empty() {
return None;
}
let snap = |fs: &[PathBuf]| fs.iter().map(|f| std::fs::read(f).ok()).collect::<Vec<_>>();
let before = snap(&changed);
let mut fails = vec![];
let mut notes = vec![];
let mut passed = 0;
let mut ran = 0;
for r in &runs {
if !installed(r.adapter, &r.root) {
notes.push(format!("{:?}: not installed", r.adapter));
continue;
}
ran += 1;
let where_ = r
.root
.strip_prefix(&self.ws)
.unwrap_or(&r.root)
.display()
.to_string();
match run(r, self.timeout).await {
Ok(o) => {
passed += o.passed;
fails.extend(o.failures);
}
Err(e) => fails.push(Failure {
name: format!("{:?} in ./{where_}", r.adapter).to_lowercase(),
file: None,
message: clip(&e, 12),
}),
}
}
let stale = snap(&changed) != before;
let mut last = self.last.lock().await;
let body = if fails.is_empty() {
if ran == 0 || last.is_empty() {
// nothing ran, or tests were already green: stay quiet
*last = String::new();
return (!notes.is_empty()).then(|| format!("[lens] tests: {}", notes.join("; ")));
}
format!("[lens] tests: all {passed} selected tests pass now")
} else {
let mut out = format!(
"[lens] {} failing test(s) affected by this turn's changes{}:\n",
fails.len(),
if stale {
" (stale: files changed during the run)"
} else {
""
}
);
for f in &fails {
let file = f
.file
.as_ref()
.map(|p| format!(" ({})", p.strip_prefix(&self.ws).unwrap_or(p).display()))
.unwrap_or_default();
let s = format!("- {}{file}\n{}\n", f.name, indent(&f.message));
if out.len() + s.len() > self.cap {
out.push_str("… (truncated; run the tests with bash for full output)\n");
break;
}
out.push_str(&s);
}
if !notes.is_empty() {
out.push_str(&format!("(notes: {})\n", notes.join("; ")));
}
out.trim_end().to_string()
};
let key = if fails.is_empty() {
String::new()
} else {
body.clone()
};
if !fails.is_empty() && *last == key {
return None;
}
*last = key;
Some(body)
}
}
fn indent(s: &str) -> String {
s.lines()
.map(|l| format!(" {l}"))
.collect::<Vec<_>>()
.join("\n")
}
#[async_trait::async_trait]
impl hx_core::hook::Hook for TestLens {
async fn on(&self, ev: &hx_core::hook::Event) -> hx_core::hook::HookAction {
use hx_core::hook::{Event, HookAction};
match ev {
Event::ToolResult {
name,
args,
is_error: false,
..
} if name == "write" || name == "edit" => {
if let Some(p) = args["path"].as_str() {
let p = self.ws.join(p);
let mut v = self.pending.lock().await;
if !v.contains(&p) {
v.push(p);
}
}
HookAction::Continue
}
Event::TurnEnd if self.mode == TestMode::TurnEnd => self
.report()
.await
.map_or(HookAction::Continue, HookAction::Inject),
Event::AgentEnd if self.mode == TestMode::AgentEnd => match self.report().await {
Some(r) if r.contains("failing test") => HookAction::Inject(r),
_ => HookAction::Continue,
},
_ => HookAction::Continue,
}
}
}
#[cfg(test)]
mod t {
use super::*;
#[test]
fn libtest() {
let s = "running 3 tests\ntest a::ok ... ok\ntest a::bad ... FAILED\ntest b ... ignored\n\nfailures:\n\n---- a::bad stdout ----\n\nthread 'a::bad' panicked at src/lib.rs:9:5:\nassertion `left == right` failed\n left: 5\n right: 4\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n\nfailures:\n a::bad\n\ntest result: FAILED. 1 passed; 1 failed\n";
let o = parse_libtest(s);
assert_eq!(o.passed, 1);
assert_eq!(o.failures.len(), 1);
assert_eq!(o.failures[0].name, "a::bad");
assert!(
o.failures[0].message.contains("left: 5"),
"{:?}",
o.failures[0]
);
assert!(!o.failures[0].message.contains("RUST_BACKTRACE"));
assert_eq!(
parse_libtest("test x ... ok\ntest result: ok. 1 passed").failures,
vec![]
);
}
#[test]
fn junit() {
let s = r#"<?xml version="1.0"?><testsuites><testsuite name="pytest" tests="3">
<testcase classname="tests.test_m" name="test_ok" file="tests/test_m.py" line="1" time="0.001" />
<testcase classname="tests.test_m" name="test_bad" file="tests/test_m.py" line="4" time="0.001"><failure message="assert 5 == 4">def test_bad():
&gt; assert add(2, 2) == 4
E assert 5 == 4</failure></testcase>
<testcase classname="tests.test_m" name="test_skip" time="0"><skipped message="x"/></testcase>
<testcase classname="tests.test_m" name="test_err" time="0"><error message="fixture &apos;db&apos; not found"/></testcase>
</testsuite></testsuites>"#;
let o = parse_junit(s, Path::new("/r"));
assert_eq!(o.passed, 1);
assert_eq!(o.failures.len(), 2, "{o:?}");
assert_eq!(o.failures[0].name, "tests.test_m::test_bad");
assert_eq!(
o.failures[0].file.as_deref(),
Some(Path::new("/r/tests/test_m.py"))
);
assert!(o.failures[0].message.contains("> ") && o.failures[0].message.contains("5 == 4"));
assert_eq!(o.failures[1].message, "fixture 'db' not found");
}
#[test]
fn jest() {
let s = r#"{"numFailedTests":1,"testResults":[
{"name":"/r/a.test.ts","status":"failed","message":"","assertionResults":[
{"fullName":"add works","status":"passed","failureMessages":[]},
{"fullName":"add fails","status":"failed","failureMessages":["Error: expect(received).toBe(expected)\n\nExpected: 4\nReceived: 5"]}]},
{"name":"/r/b.test.ts","status":"failed","message":"SyntaxError: Unexpected token","assertionResults":[]}]}"#;
let o = parse_jest(s).unwrap();
assert_eq!(o.passed, 1);
assert_eq!(o.failures.len(), 2);
assert!(o.failures[0].message.contains("Received: 5"));
assert_eq!(o.failures[1].name, "(suite)");
assert!(parse_jest("nope").is_err());
}
#[test]
fn go() {
let s = r#"{"Action":"run","Package":"m/p","Test":"TestOk"}
{"Action":"pass","Package":"m/p","Test":"TestOk"}
{"Action":"run","Package":"m/p","Test":"TestBad"}
{"Action":"output","Package":"m/p","Test":"TestBad","Output":"=== RUN TestBad\n"}
{"Action":"output","Package":"m/p","Test":"TestBad","Output":" p_test.go:8: add(2,2) = 5, want 4\n"}
{"Action":"output","Package":"m/p","Test":"TestBad","Output":"--- FAIL: TestBad (0.00s)\n"}
{"Action":"fail","Package":"m/p","Test":"TestBad"}
{"Action":"fail","Package":"m/p"}
{"Action":"output","Package":"m/q","Output":"q.go:3:1: syntax error\n"}
{"Action":"fail","Package":"m/q"}"#;
let o = parse_go(s);
assert_eq!(o.passed, 1);
assert_eq!(o.failures.len(), 2, "{o:?}");
assert_eq!(o.failures[0].name, "m/p.TestBad");
assert_eq!(o.failures[0].message, "p_test.go:8: add(2,2) = 5, want 4");
assert_eq!(o.failures[1].name, "m/q");
assert!(o.failures[1].message.contains("syntax error"));
}
#[test]
fn detection() {
let d = tempfile::tempdir().unwrap();
let ws = d.path();
std::fs::write(
ws.join("package.json"),
r#"{"devDependencies":{"vitest":"1"}}"#,
)
.unwrap();
std::fs::create_dir_all(ws.join("py")).unwrap();
std::fs::write(ws.join("py/pyproject.toml"), "").unwrap();
assert_eq!(
detect(&ws.join("src/a.ts"), ws),
Some((Adapter::Vitest, ws.into()))
);
assert_eq!(
detect(&ws.join("py/m.py"), ws),
Some((Adapter::Pytest, ws.join("py")))
);
assert_eq!(detect(&ws.join("x.go"), ws), None);
assert!(is_test_file(Path::new("a/test_x.py")) && !is_test_file(Path::new("a/x.py")));
assert!(is_test_file(Path::new("a/x.spec.ts")) && is_test_file(Path::new("x_test.go")));
}
#[test]
fn selection() {
let d = tempfile::tempdir().unwrap();
let ws = &std::fs::canonicalize(d.path()).unwrap();
let w = |p: &str, s: &str| {
let p = ws.join(p);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, s).unwrap();
};
w("package.json", r#"{"devDependencies":{"jest":"29"}}"#);
w("src/util.ts", "");
w("src/api.ts", "import './util'\n");
w("src/api.test.ts", "import './api'\n");
w("src/other.test.ts", "");
w("core/Cargo.toml", "[package]\nname = \"core\"\n");
w(
"app/Cargo.toml",
"[package]\nname = \"app\"\n[dependencies]\ncore = { path = \"../core\" }\n",
);
w("docs/x.md", "");
let g = crate::deps::build(ws);
let r = select(
&[
ws.join("src/util.ts"),
ws.join("core/src/lib.rs"),
ws.join("docs/x.md"),
],
ws,
&g,
);
assert_eq!(
r,
vec![
Run {
adapter: Adapter::Jest,
root: ws.clone(),
targets: vec![ws.join("src/api.test.ts")]
},
Run {
adapter: Adapter::Cargo,
root: ws.join("app"),
targets: vec![]
},
Run {
adapter: Adapter::Cargo,
root: ws.join("core"),
targets: vec![]
},
]
);
// a changed non-test file nobody tests selects nothing
assert!(
select(
&[ws.join("src/api.test.ts").with_file_name("lonely.ts")],
ws,
&g
)
.is_empty()
);
}
/// real cargo run: one passing, one failing test
#[tokio::test]
async fn real_cargo() {
let d = tempfile::tempdir().unwrap();
let ws = d.path();
std::fs::create_dir_all(ws.join("src")).unwrap();
std::fs::write(
ws.join("Cargo.toml"),
"[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n[workspace]\n",
)
.unwrap();
std::fs::write(
ws.join("src/lib.rs"),
"pub fn add(a: u32, b: u32) -> u32 { a + b + 1 }\n#[test] fn good() { assert!(add(0, 0) > 0) }\n#[test] fn bad() { assert_eq!(add(2, 2), 4) }\n",
)
.unwrap();
let r = Run {
adapter: Adapter::Cargo,
root: ws.into(),
targets: vec![],
};
let o = run(&r, Duration::from_secs(120)).await.unwrap();
assert_eq!(o.passed, 1, "{o:?}");
assert_eq!(o.failures[0].name, "bad");
assert!(o.failures[0].message.contains("left: 5"), "{o:?}");
std::fs::write(ws.join("src/lib.rs"), "pub fn f( {\n").unwrap();
let e = run(&r, Duration::from_secs(120)).await.unwrap_err();
assert!(e.contains("test run failed"), "{e}");
}
/// hook: failing affected test surfaced at turn end, repeated report suppressed, green reported once
#[tokio::test]
async fn hook_report() {
use hx_core::hook::{Event, Hook, HookAction};
let d = tempfile::tempdir().unwrap();
let ws = std::fs::canonicalize(d.path()).unwrap();
std::fs::create_dir_all(ws.join("src")).unwrap();
std::fs::write(
ws.join("Cargo.toml"),
"[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n[workspace]\n",
)
.unwrap();
let lib = ws.join("src/lib.rs");
let tl = TestLens::new(ws.clone(), TestMode::TurnEnd);
let edit = || Event::ToolResult {
id: "1".into(),
name: "edit".into(),
args: serde_json::json!({"path": "src/lib.rs"}),
content: String::new(),
is_error: false,
};
assert_eq!(tl.on(&Event::TurnEnd).await, HookAction::Continue);
std::fs::write(
&lib,
"pub fn add(a: u32) -> u32 { a + 2 }\n#[test] fn t() { assert_eq!(add(1), 2) }\n",
)
.unwrap();
tl.on(&edit()).await;
let HookAction::Inject(r) = tl.on(&Event::TurnEnd).await else {
panic!("expected failure")
};
assert!(
r.contains("1 failing test") && r.contains("- t\n") && r.contains("left: 3"),
"{r}"
);
tl.on(&edit()).await;
assert_eq!(
tl.on(&Event::TurnEnd).await,
HookAction::Continue,
"same failure repeated"
);
std::fs::write(
&lib,
"pub fn add(a: u32) -> u32 { a + 1 }\n#[test] fn t() { assert_eq!(add(1), 2) }\n",
)
.unwrap();
tl.on(&edit()).await;
let HookAction::Inject(r) = tl.on(&Event::TurnEnd).await else {
panic!("expected green")
};
assert!(r.contains("all 1 selected tests pass"), "{r}");
tl.on(&edit()).await;
assert_eq!(
tl.on(&Event::TurnEnd).await,
HookAction::Continue,
"green only once"
);
}
}