1use crate::{CheckInfo, Htl, parent_dir, write_if_changed};
10use anyhow::{Context, Result};
11use mlua::{Function, Table, Value};
12use std::path::{Path, PathBuf};
13
14const TEST_LUA: &str = include_str!("../lua/test.lua");
15const TEST_DTL: &str = include_str!("../lua/test.d.tl");
16
17pub const DEFAULT_LIB: &str = "htl.test";
19
20pub fn lib_dir() -> Result<PathBuf> {
23 let dir = std::env::temp_dir().join(format!("htl-lib-{}", env!("CARGO_PKG_VERSION")));
24 write_if_changed(&dir.join("htl").join("test.d.tl"), TEST_DTL)
25 .with_context(|| format!("writing bundled declarations under {}", dir.display()))?;
26 Ok(dir)
27}
28
29impl Htl {
30 pub fn install_test_lib(&self) -> Result<()> {
32 self.preload(DEFAULT_LIB, TEST_LUA)?;
33 self.add_path(&lib_dir()?)?;
34 Ok(())
35 }
36}
37
38#[derive(Debug, Default)]
40pub struct FileReport {
41 pub path: PathBuf,
42 pub check: CheckInfo,
43 pub error: Option<String>,
45 pub passed: usize,
46 pub failed: usize,
47 pub failures: Vec<String>,
48 pub file_level: bool,
50 pub tests: Vec<TestResult>,
52 pub duration_ms: f64,
54}
55
56#[derive(Debug, Clone, Default)]
58pub struct TestResult {
59 pub name: String,
60 pub ok: bool,
61 pub ms: f64,
62}
63
64#[derive(Debug, Clone, Default)]
66pub struct RunOptions {
67 pub fail_fast: bool,
69}
70
71impl FileReport {
72 pub fn ok(&self) -> bool {
73 self.check.ok() && self.error.is_none() && self.failed == 0
74 }
75}
76
77pub fn discover_tests(paths: &[PathBuf]) -> Result<Vec<PathBuf>> {
81 let mut out = Vec::new();
82 for p in paths {
83 if p.is_file() {
84 out.push(p.clone());
85 continue;
86 }
87 let extra = crate::project_skip_dirs(p);
88 let root = p.clone();
89 let walker = walkdir::WalkDir::new(p)
90 .sort_by_file_name()
91 .into_iter()
92 .filter_entry(move |e| e.path() == root || !crate::is_skipped_dir(e.path(), &extra));
93 for e in walker {
94 let e = e?;
95 let path = e.path();
96 if !crate::is_tl_source(path) {
97 continue;
98 }
99 let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
100 let in_tests_dir = path
101 .strip_prefix(p)
102 .ok()
103 .map(|rel| rel.components().any(|c| c.as_os_str() == "tests"))
104 .unwrap_or(false);
105 if name.ends_with("_test.tl") || in_tests_dir {
106 out.push(path.to_path_buf());
107 }
108 }
109 }
110 out.sort();
111 out.dedup();
112 Ok(out)
113}
114
115pub fn run_test_file(
118 path: &Path,
119 filter: Option<&str>,
120 lib: &str,
121 lint_spec: Option<&str>,
122 opts: &RunOptions,
123) -> Result<FileReport> {
124 let started = std::time::Instant::now();
125 let mut rep = run_test_file_inner(path, filter, lib, lint_spec, opts)?;
126 rep.duration_ms = started.elapsed().as_secs_f64() * 1000.0;
127 Ok(rep)
128}
129
130fn run_test_file_inner(
131 path: &Path,
132 filter: Option<&str>,
133 lib: &str,
134 lint_spec: Option<&str>,
135 opts: &RunOptions,
136) -> Result<FileReport> {
137 let mut rep = FileReport { path: path.to_path_buf(), ..Default::default() };
138 let h = Htl::new()?;
139 if let Some(spec) = lint_spec {
140 h.configure_lints(spec)?;
141 }
142 h.install_test_lib()?;
143 let dir = parent_dir(path);
144 h.add_path(&dir)?;
145 #[cfg(feature = "pkg")]
146 if let Some(p) = crate::pkg::Project::find(path) {
147 h.apply_project(&p)?;
148 }
149 if let Some((cfg_path, cfg)) = crate::config::HtlConfig::find(path)? {
150 h.apply_config(&parent_dir(&cfg_path), &cfg)?;
151 }
152 if dir.file_name().is_some_and(|n| n == "tests")
154 && let Some(root) = dir.parent()
155 {
156 h.add_path(root)?;
157 h.add_path(&root.join("src"))?;
158 }
159 h.install_searcher()?;
160 h.set_arg(&path.to_string_lossy(), &[])?;
161
162 let (code, check) = h.gen_lua(path)?;
163 rep.check = check;
164 let Some(code) = code else { return Ok(rep) };
165 if let Err(e) = h.exec(&code, &format!("@{}", path.display()), &[]) {
166 rep.error = Some(crate::user_message(&e));
167 return Ok(rep);
168 }
169
170 let package: Table = h.lua().globals().get("package")?;
172 let loaded: Table = package.get("loaded")?;
173 match loaded.get::<Value>(lib)? {
174 Value::Table(t) => {
175 let run: Function = t.get("run")?;
176 let lua_opts = h.lua().create_table()?;
177 lua_opts.set("fail_fast", opts.fail_fast)?;
178 let report: Table = run.call((filter, lua_opts))?;
179 rep.passed = report.get::<Option<usize>>("passed")?.unwrap_or(0);
180 rep.failed = report.get::<Option<usize>>("failed")?.unwrap_or(0);
181 if let Ok(f) = report.get::<Table>("failures") {
182 rep.failures = f.sequence_values::<String>().collect::<mlua::Result<_>>()?;
183 }
184 if let Ok(tests) = report.get::<Table>("tests") {
185 for tr in tests.sequence_values::<Table>() {
186 let tr = tr?;
187 rep.tests.push(TestResult {
188 name: tr.get::<Option<String>>("name")?.unwrap_or_default(),
189 ok: tr.get::<Option<bool>>("ok")?.unwrap_or(false),
190 ms: tr.get::<Option<f64>>("ms")?.unwrap_or(0.0),
191 });
192 }
193 }
194 }
195 _ => {
196 rep.file_level = true;
197 rep.passed = 1;
198 }
199 }
200 Ok(rep)
201}