Skip to main content

lux_lib/operations/
test.rs

1use crate::package;
2use crate::rockspec;
3use std::{io, process::Command};
4
5use crate::drivers::sync::{self, Sync, SyncMode, TargetSet};
6
7pub(crate) mod tiniest;
8use crate::fs;
9use crate::tree::InstallTree;
10use crate::workspace::{self, TreeError};
11use crate::{
12    build::BuildBehaviour,
13    config::{self, Config},
14    lua,
15    path::{self, Paths},
16    project::{self, Project},
17    rockspec::Rockspec,
18    workspace::Workspace,
19};
20use bon::Builder;
21use itertools::Itertools;
22use miette::Diagnostic;
23use path_slash::PathBufExt;
24use thiserror::Error;
25
26#[cfg(target_family = "unix")]
27const BUSTED_EXE: &str = "busted";
28#[cfg(target_family = "windows")]
29const BUSTED_EXE: &str = "busted.bat";
30
31#[derive(Builder)]
32#[builder(start_fn = new, finish_fn(name = _run, vis = ""))]
33pub struct Test<'a> {
34    #[builder(start_fn)]
35    workspace: Workspace,
36    #[builder(start_fn)]
37    config: &'a Config,
38
39    #[builder(field)]
40    args: Vec<String>,
41
42    /// Package to run tests for
43    package: Option<package::Name>,
44
45    no_lock: Option<bool>,
46
47    #[builder(default)]
48    env: Env,
49}
50
51impl<State: test_builder::State> TestBuilder<'_, State> {
52    pub fn arg(mut self, arg: impl Into<String>) -> Self {
53        self.args.push(arg.into());
54        self
55    }
56
57    pub fn args(mut self, args: impl IntoIterator<Item: Into<String>>) -> Self {
58        self.args.extend(args.into_iter().map_into());
59        self
60    }
61
62    pub async fn run(self) -> Result<(), Error>
63    where
64        State: test_builder::IsComplete,
65    {
66        run_tests(self._run()).await
67    }
68}
69
70#[derive(Default)]
71pub enum Env {
72    /// An environment that is isolated from `HOME` and `XDG` base directories (default).
73    #[default]
74    Pure,
75    /// An impure environment in which `HOME` and `XDG` base directories can influence
76    /// the test results.
77    Impure,
78}
79
80#[derive(Error, Debug, Diagnostic)]
81pub enum Error {
82    #[error(transparent)]
83    #[diagnostic(transparent)]
84    Config(#[from] config::Error),
85    #[error("build failed")]
86    #[diagnostic(forward(0))]
87    Sync(#[from] Box<sync::Error>),
88    #[error("tests failed!")]
89    #[diagnostic(help("see the test runner's output for details"))]
90    TestFailure,
91    #[error("failed to execute '{cmd}'")]
92    RunCommandFailure {
93        cmd: String,
94        source: io::Error,
95        #[help]
96        help: Option<String>,
97    },
98    #[error(transparent)]
99    #[diagnostic(transparent)]
100    Fs(#[from] fs::Error),
101    #[error(transparent)]
102    #[diagnostic(transparent)]
103    Project(#[from] project::Error),
104    #[error(transparent)]
105    #[diagnostic(transparent)]
106    Paths(#[from] path::Error),
107    #[error(transparent)]
108    #[diagnostic(transparent)]
109    Workspace(#[from] workspace::Error),
110    #[error(transparent)]
111    #[diagnostic(transparent)]
112    Tree(#[from] TreeError),
113    #[error(transparent)]
114    #[diagnostic(transparent)]
115    ProjectTomlValidation(#[from] rockspec::toml::Error),
116    #[error(transparent)]
117    #[diagnostic(transparent)]
118    Test(#[from] rockspec::test::Error),
119    #[error(transparent)]
120    #[diagnostic(transparent)]
121    LuaVersion(#[from] rockspec::Error),
122    #[error(transparent)]
123    #[diagnostic(transparent)]
124    LuaBinary(#[from] lua::installation::Error),
125    #[error("failed to set up tiniest")]
126    #[diagnostic(forward(0))]
127    Tiniest(#[from] tiniest::Error),
128    #[error(transparent)]
129    #[diagnostic(transparent)]
130    RunLua(#[from] super::run_lua::Error),
131}
132
133impl From<sync::Error> for Error {
134    fn from(source: sync::Error) -> Self {
135        Self::Sync(Box::new(source))
136    }
137}
138
139#[tracing::instrument(name = "🧪 Running tests", skip_all)]
140
141async fn run_tests(test: Test<'_>) -> Result<(), Error> {
142    let workspace = test.workspace;
143    let config = test.config;
144    let no_lock = test.no_lock.unwrap_or(false);
145
146    if let Some(package) = test.package {
147        let project = workspace.select_member(&package)?;
148        Box::pin(run_project_tests(
149            &workspace, project, no_lock, &test.args, &test.env, config,
150        ))
151        .await
152    } else {
153        for project in workspace.members() {
154            Box::pin(run_project_tests(
155                &workspace, project, no_lock, &test.args, &test.env, config,
156            ))
157            .await?;
158        }
159        Ok(())
160    }
161}
162
163async fn run_project_tests(
164    workspace: &Workspace,
165    project: &Project,
166    no_lock: bool,
167    test_args: &[String],
168    test_env: &Env,
169    config: &Config,
170) -> Result<(), Error> {
171    let rocks = project.toml().into_local()?;
172    let test_spec = match rocks.test().current_platform().to_validated(project) {
173        Ok(test_spec) => test_spec,
174        Err(rockspec::test::Error::NoTestSpecDetected)
175            if project.lua_version(config)? == lua::Version::Luau =>
176        {
177            // tiniest is the default test framework for Luau projects
178            rockspec::test::internal::Validated::Tiniest
179        }
180        Err(err) => return Err(err.into()),
181    };
182    let test_config = test_spec.test_config(config)?;
183
184    Sync::new(workspace, &test_config)
185        .mode(SyncMode::Open)
186        .targets(TargetSet::member(project.toml().package().clone(), true))
187        .no_lock(no_lock)
188        .behaviour(BuildBehaviour::Ignore)
189        .sync()
190        .await?;
191
192    let lua_version = project.lua_version(&test_config)?.clone();
193    let project_tree = workspace.lua_version_tree(lua_version.clone(), &test_config)?;
194    let test_tree = workspace.test_tree(&test_config)?;
195    let mut paths = Paths::new(&project_tree)?;
196    let test_tree_paths = Paths::new(&test_tree)?;
197    paths.prepend(&test_tree_paths);
198
199    let collector_path = match &test_spec {
200        rockspec::test::internal::Validated::Tiniest => {
201            let spec_files = tiniest::discover_spec_files(project.root());
202            if spec_files.is_empty() {
203                tracing::warn!("no *.spec.luau or *.spec.lua files found in test/ or tests/");
204            }
205            let tiniest_src = tiniest::ensure_installed(&test_tree, &test_config).await?;
206            Some(tiniest::write_collector(workspace.root(), &spec_files, &tiniest_src).await?)
207        }
208        _ => None,
209    };
210    let mut runner_args = test_spec.args();
211    if let Some(collector_path) = &collector_path {
212        runner_args.push(collector_path.to_slash_lossy().to_string());
213    }
214
215    let test_executable = match &test_spec {
216        rockspec::test::internal::Validated::Busted { .. } => BUSTED_EXE.to_string(),
217        rockspec::test::internal::Validated::BustedNlua { .. } => BUSTED_EXE.to_string(),
218        rockspec::test::internal::Validated::Command(spec) => spec.command.to_string(),
219        rockspec::test::internal::Validated::Tiniest
220        | rockspec::test::internal::Validated::LuaScript(_) => {
221            let runtime =
222                super::run_lua::resolve_runtime(&lua_version.clone(), &test_config).await?;
223            runtime.to_string_lossy().to_string()
224        }
225    };
226    let mut command = Command::new(&test_executable);
227    let mut command = command
228        .current_dir(project.root())
229        .args(runner_args)
230        .args(test_args)
231        .env("PATH", paths.path_prepended().joined())
232        .env("LUA_PATH", paths.package_path().joined())
233        .env("LUA_CPATH", paths.package_cpath().joined());
234    if matches!(
235        &test_spec,
236        rockspec::test::internal::Validated::Busted { .. }
237            | rockspec::test::internal::Validated::BustedNlua { .. }
238    ) && !test_spec
239        .args()
240        .iter()
241        .chain(test_args.iter())
242        .any(|arg| arg == "--directory" || arg == "-C" || arg.starts_with("--directory="))
243    {
244        let directory = fs::sync::absolute(project.root())?;
245        command = command
246            .arg("--directory")
247            .arg(directory.to_slash_lossy().to_string());
248    }
249    if let Env::Pure = test_env {
250        // isolate the test runner from the user's own config/data files
251        // by initialising empty HOME and XDG base directory paths
252        let home = test_tree.root().join("home");
253        let xdg = home.join("xdg");
254        let _ = fs::tokio::remove_dir_all(&home).await;
255        let xdg_config_home = xdg.join("config");
256        fs::tokio::create_dir_all(&xdg_config_home).await?;
257        let xdg_state_home = xdg.join("local").join("state");
258        fs::tokio::create_dir_all(&xdg_state_home).await?;
259        let xdg_data_home = xdg.join("local").join("share");
260        fs::tokio::create_dir_all(&xdg_data_home).await?;
261        command = command
262            .env("HOME", home)
263            .env("XDG_CONFIG_HOME", xdg_config_home)
264            .env("XDG_STATE_HOME", xdg_state_home)
265            .env("XDG_DATA_HOME", xdg_data_home);
266    }
267    let status = match command.status() {
268        Ok(status) => Ok(status),
269        Err(err) => {
270            let help = if err.to_string().starts_with("No such file") {
271                Some(format!(
272                    "make sure '{}' is available on your PATH",
273                    test_executable
274                ))
275            } else {
276                None
277            };
278            Err(Error::RunCommandFailure {
279                cmd: test_executable,
280                source: err,
281                help,
282            })
283        }
284    }?;
285    if !status.success() {
286        Err(Error::TestFailure)
287    } else {
288        Ok(())
289    }
290}
291
292#[cfg(all(test, feature = "impure_tests"))]
293mod tests {
294    use std::path::{Path, PathBuf};
295
296    use crate::{config, fs, lua};
297
298    use super::*;
299    use assert_fs::{prelude::PathCopy, TempDir};
300
301    #[tokio::test]
302    async fn test_command_spec() {
303        let project_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
304            .join("resources/test/sample-projects/command-test/");
305        run_test(&project_root).await
306    }
307
308    #[tokio::test]
309    async fn test_lua_script_spec() {
310        let project_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
311            .join("resources/test/sample-projects/lua-script-test/");
312        run_test(&project_root).await
313    }
314
315    async fn run_test(project_root: &Path) {
316        let temp_dir = TempDir::new().unwrap();
317        temp_dir.copy_from(project_root, &["**"]).unwrap();
318        let workspace_root = temp_dir.path();
319        let workspace = Workspace::from(workspace_root).unwrap().unwrap();
320        let tree_root = workspace.root().to_path_buf().join(".lux");
321        let _ = fs::tokio::remove_dir_all(&tree_root).await;
322
323        let lua_version = lua::detect::installed_version().or(Some(lua::Version::Lua51));
324
325        let config = config::Builder::new()
326            .unwrap()
327            .user_tree(Some(tree_root))
328            .lua_version(lua_version)
329            .build()
330            .unwrap();
331
332        Test::new(workspace, &config).run().await.unwrap();
333    }
334}