Skip to main content

lux_lib/rockspec/test/
mod.rs

1use super::platform;
2use crate::package;
3use itertools::Itertools;
4
5use miette::Diagnostic;
6use path_slash::PathExt;
7use serde::{Deserialize, Deserializer};
8use serde_enum_str::Serialize_enum_str;
9use std::{convert::Infallible, path::PathBuf};
10use thiserror::Error;
11
12use crate::lua;
13
14use crate::{
15    config::{self, Config},
16    project::Project,
17    rockspec::platform::per_platform_from_intermediate,
18    rockspec::Rockspec,
19};
20
21use super::PerPlatform;
22
23#[cfg(target_family = "unix")]
24const NLUA_EXE: &str = "nlua";
25#[cfg(target_family = "windows")]
26const NLUA_EXE: &str = "nlua.bat";
27
28#[derive(Error, Debug, Diagnostic)]
29#[non_exhaustive]
30pub enum DecodeError {
31    #[error("the 'command' test type must specify either a 'command' or 'script' field")]
32    NoCommandOrScript,
33    #[error("the 'command' test type cannot have both 'command' and 'script' fields")]
34    CommandAndScript,
35}
36
37#[derive(Error, Debug, Diagnostic)]
38#[non_exhaustive]
39pub enum Error {
40    #[error("could not auto-detect the test spec. Please add one to your lux.toml")]
41    NoTestSpecDetected,
42    #[error("project validation failed")]
43    #[diagnostic(forward(0))]
44    LocalProjectTomlValidation(#[from] super::toml::Error),
45}
46
47#[derive(Clone, Debug, PartialEq, Default)]
48pub enum Spec {
49    #[default]
50    AutoDetect,
51    Busted(Busted),
52    BustedNlua(Busted),
53    Tiniest,
54    Command(Command),
55    Script(LuaScript),
56}
57
58impl Spec {
59    pub(crate) fn test_dependencies(&self, project: &Project) -> Vec<package::Req> {
60        self.to_validated(project)
61            .ok()
62            .iter()
63            .flat_map(|spec| spec.test_dependencies())
64            .collect_vec()
65    }
66
67    pub(crate) fn to_validated(&self, project: &Project) -> Result<internal::Validated, Error> {
68        let project_root = project.root();
69        let toml = project.toml().into_local()?;
70        let test_dependencies = toml.test_dependencies().current_platform();
71        let busted_dependency = test_dependencies
72            .iter()
73            .find(|dep| dep.name().to_string() == "busted");
74        let busted = busted_dependency
75            .map(|dep| dep.package_req.clone())
76            .unwrap_or_else(|| unsafe { package::Req::new_unchecked("busted".into(), None) });
77        let nlua_dependency = test_dependencies
78            .iter()
79            .find(|dep| dep.name().to_string() == "nlua");
80        let nlua = nlua_dependency
81            .map(|dep| dep.package_req.clone())
82            .unwrap_or_else(|| unsafe { package::Req::new_unchecked("nlua".into(), None) });
83        let is_busted = project_root.join(".busted").is_file() || busted_dependency.is_some();
84        match self {
85            Self::AutoDetect if is_busted => {
86                if nlua_dependency.is_some() {
87                    Ok(internal::Validated::BustedNlua {
88                        spec: Busted::default(),
89                        dependencies: vec![busted, nlua],
90                    })
91                } else {
92                    Ok(internal::Validated::Busted {
93                        spec: Busted::default(),
94                        dependencies: vec![busted],
95                    })
96                }
97            }
98            Self::Busted(spec) => Ok(internal::Validated::Busted {
99                spec: spec.clone(),
100                dependencies: vec![busted],
101            }),
102            Self::BustedNlua(spec) => Ok(internal::Validated::BustedNlua {
103                spec: spec.clone(),
104                dependencies: vec![busted, nlua],
105            }),
106            Self::Tiniest => Ok(internal::Validated::Tiniest),
107            Self::Command(spec) => Ok(internal::Validated::Command(spec.clone())),
108            Self::Script(spec) => Ok(internal::Validated::LuaScript(spec.clone())),
109            Self::AutoDetect => Err(Error::NoTestSpecDetected),
110        }
111    }
112}
113
114/// Specification for running a test suite with busted
115#[derive(Clone, Debug, PartialEq, Default)]
116pub struct Busted {
117    /// Additional CLI flags to pass to Busted when running
118    pub(crate) flags: Vec<String>,
119}
120
121impl Busted {
122    pub fn flags(&self) -> &Vec<String> {
123        &self.flags
124    }
125}
126
127/// Specification for running a test suite with a command
128#[derive(Clone, Debug, PartialEq)]
129pub struct Command {
130    /// The command to run
131    pub(crate) command: String,
132    /// Additional CLI flags to pass to Busted when running
133    pub(crate) flags: Vec<String>,
134}
135
136impl Command {
137    pub fn flags(&self) -> &Vec<String> {
138        &self.flags
139    }
140
141    pub fn command(&self) -> &str {
142        &self.command
143    }
144}
145
146/// Specification for running a test suite with a Lua script
147#[derive(Clone, Debug, PartialEq)]
148pub struct LuaScript {
149    /// The script to run
150    pub(crate) script: PathBuf,
151    /// Additional CLI flags to pass to the script when running
152    pub(crate) flags: Vec<String>,
153}
154
155impl LuaScript {
156    pub fn flags(&self) -> &Vec<String> {
157        &self.flags
158    }
159
160    pub fn script(&self) -> &PathBuf {
161        &self.script
162    }
163}
164
165pub(crate) mod internal {
166    use super::*;
167
168    #[derive(Clone, Debug, PartialEq)]
169    pub(crate) enum Validated {
170        Busted {
171            spec: Busted,
172            dependencies: Vec<package::Req>,
173        },
174        BustedNlua {
175            spec: Busted,
176            dependencies: Vec<package::Req>,
177        },
178        Tiniest,
179        Command(Command),
180        LuaScript(LuaScript),
181    }
182    impl Validated {
183        pub fn args(&self) -> Vec<String> {
184            match self {
185                Self::Busted {
186                    spec,
187                    dependencies: _,
188                } => spec.flags.clone(),
189                Self::BustedNlua {
190                    spec,
191                    dependencies: _,
192                } => {
193                    let mut flags = spec.flags.clone();
194                    // If there's a .busted config file which has lua set to "nlua",
195                    // we tell busted to ignore it, because we set the correct
196                    // platform-dependent "nlua" executable in the wrapper script.
197                    flags.push("--ignore-lua".into());
198                    flags
199                }
200                Self::Tiniest => Vec::new(),
201                Self::Command(spec) => spec.flags.clone(),
202                Self::LuaScript(spec) => std::iter::once(spec.script.to_slash_lossy().to_string())
203                    .chain(spec.flags.clone())
204                    .collect_vec(),
205            }
206        }
207
208        pub(crate) fn test_config(&self, config: &Config) -> Result<Config, config::Error> {
209            match self {
210                Self::BustedNlua { .. } => {
211                    let config_builder: config::Builder = config.clone().into();
212
213                    // XXX: On macos and msvc, Neovim and LuaJIT segfault when
214                    // requiring luafilesystem's `lfs` module
215                    // if it is built with Lua 5.1 headers.
216                    #[cfg(not(any(target_os = "macos", target_env = "msvc")))]
217                    let lua_version = lua::Version::Lua51;
218
219                    #[cfg(any(target_os = "macos", target_env = "msvc"))]
220                    let lua_version = lua::Version::LuaJIT;
221
222                    Ok(config_builder
223                        .lua_version(Some(lua_version))
224                        .variables(Some(
225                            vec![("LUA".to_string(), NLUA_EXE.to_string())]
226                                .into_iter()
227                                .collect(),
228                        ))
229                        .build()?)
230                }
231                _ => Ok(config.clone()),
232            }
233        }
234
235        pub(crate) fn test_dependencies(&self) -> Vec<package::Req> {
236            match self {
237                Self::Busted {
238                    spec: _,
239                    dependencies,
240                } => dependencies.clone(),
241                Self::BustedNlua {
242                    spec: _,
243                    dependencies,
244                } => dependencies.clone(),
245                Self::Tiniest => Vec::new(),
246                Self::Command(_) => Vec::new(),
247                Self::LuaScript(_) => Vec::new(),
248            }
249        }
250    }
251    #[derive(Debug, Deserialize, Serialize_enum_str, PartialEq, Clone)]
252    #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
253    #[serde(rename_all = "kebab-case")]
254    pub(crate) enum Type {
255        Busted,
256        BustedNlua,
257        Tiniest,
258        Command,
259    }
260
261    #[derive(Debug, PartialEq, Deserialize, Default, Clone)]
262    #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
263    pub(crate) struct Spec {
264        /// The test backend: "busted", "busted-nlua", "tiniest", or "command".
265        /// If unset, Lux auto-detects a backend (e.g. "busted" when a ".busted"
266        /// file or the "busted" dependency is present).
267        #[serde(default, rename = "type")]
268        pub(crate) test_type: Option<Type>,
269        /// Extra CLI flags to pass to the test backend.
270        #[serde(default)]
271        pub(crate) flags: Option<Vec<String>>,
272        /// Shell command to run as the test suite. Mutually exclusive with `script`.
273        #[serde(default)]
274        #[cfg_attr(
275            feature = "schema",
276            schemars(extend("x-lux-toml-example" = r#"
277    [test]
278    type = "command"
279    command = "make"
280    flags = ["test"]
281    "#))
282        )]
283        pub(crate) command: Option<String>,
284        /// Lua script to run as the test suite. Mutually exclusive with `command`.
285        #[serde(default, rename = "script", alias = "lua_script")]
286        #[cfg_attr(
287            feature = "schema",
288            schemars(extend("x-lux-toml-example" = r#"
289    [test]
290    type = "script"
291    script = "tests.lua"
292    flags = []
293    "#))
294        )]
295        pub(crate) script: Option<PathBuf>,
296    }
297
298    impl platform::PartialOverride for Spec {
299        type Err = Infallible;
300
301        fn apply_overrides(&self, override_spec: &Self) -> Result<Self, Self::Err> {
302            Ok(Spec {
303                test_type: override_opt(&override_spec.test_type, &self.test_type),
304                flags: match (override_spec.flags.clone(), self.flags.clone()) {
305                    (Some(override_vec), Some(base_vec)) => {
306                        let merged: Vec<String> =
307                            base_vec.into_iter().chain(override_vec).unique().collect();
308                        Some(merged)
309                    }
310                    (None, base_vec @ Some(_)) => base_vec,
311                    (override_vec @ Some(_), None) => override_vec,
312                    _ => None,
313                },
314                command: match override_spec.script.clone() {
315                    Some(_) => None,
316                    None => override_opt(&override_spec.command, &self.command),
317                },
318                script: match override_spec.command.clone() {
319                    Some(_) => None,
320                    None => override_opt(&override_spec.script, &self.script),
321                },
322            })
323        }
324    }
325
326    impl platform::Overridable for Spec {
327        type Err = Infallible;
328
329        fn on_nil<T>() -> Result<PerPlatform<T>, <Self as platform::Overridable>::Err>
330        where
331            T: platform::Overridable,
332            T: Default,
333        {
334            Ok(PerPlatform::default())
335        }
336    }
337
338    fn override_opt<T: Clone>(override_opt: &Option<T>, base: &Option<T>) -> Option<T> {
339        match override_opt.clone() {
340            override_val @ Some(_) => override_val,
341            None => base.clone(),
342        }
343    }
344    impl TryFrom<Spec> for super::Spec {
345        type Error = DecodeError;
346
347        fn try_from(internal: Spec) -> Result<Self, Self::Error> {
348            let test_spec = match internal.test_type {
349                Some(Type::Busted) => Ok(Self::Busted(Busted {
350                    flags: internal.flags.unwrap_or_default(),
351                })),
352                Some(Type::BustedNlua) => Ok(Self::BustedNlua(Busted {
353                    flags: internal.flags.unwrap_or_default(),
354                })),
355                Some(Type::Tiniest) => Ok(Self::Tiniest),
356                Some(Type::Command) => match (internal.command, internal.script) {
357                    (None, None) => Err(DecodeError::NoCommandOrScript),
358                    (None, Some(script)) => Ok(Self::Script(LuaScript {
359                        script,
360                        flags: internal.flags.unwrap_or_default(),
361                    })),
362                    (Some(command), None) => Ok(Self::Command(Command {
363                        command,
364                        flags: internal.flags.unwrap_or_default(),
365                    })),
366                    (Some(_), Some(_)) => Err(DecodeError::CommandAndScript),
367                },
368                None => Ok(Self::default()),
369            }?;
370            Ok(test_spec)
371        }
372    }
373    impl<'de> Deserialize<'de> for PerPlatform<super::Spec> {
374        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
375        where
376            D: Deserializer<'de>,
377        {
378            per_platform_from_intermediate::<_, Spec, _>(deserializer)
379        }
380    }
381    impl<'de> Deserialize<'de> for super::Spec {
382        fn deserialize<D>(deserializer: D) -> Result<super::Spec, D::Error>
383        where
384            D: Deserializer<'de>,
385        {
386            let internal = Spec::deserialize(deserializer)?;
387            super::Spec::try_from(internal).map_err(serde::de::Error::custom)
388        }
389    }
390}
391
392#[cfg(test)]
393mod tests {
394
395    use ottavino::{Closure, Executor, Fuel, Lua};
396    use ottavino_util::serde::from_value;
397
398    use super::*;
399
400    fn exec_lua<T: serde::de::DeserializeOwned>(
401        code: &str,
402        key: &'static str,
403    ) -> Result<T, ottavino::ExternError> {
404        Lua::core().try_enter(|ctx| {
405            let closure = Closure::load(ctx, None, code.as_bytes())?;
406            let executor = Executor::start(ctx, closure.into(), ());
407            executor.step(ctx, &mut Fuel::with(i32::MAX))?;
408            from_value(ctx.globals().get_value(ctx, key)).map_err(ottavino::Error::from)
409        })
410    }
411
412    #[tokio::test]
413    pub async fn test_spec_from_lua() {
414        let lua_content = "
415        test = {\n
416        }\n
417        ";
418        let test_spec: PerPlatform<Spec> = exec_lua(lua_content, "test").unwrap();
419        assert!(matches!(test_spec.default, Spec::AutoDetect));
420        let lua_content = "
421        test = {\n
422            type = 'busted',\n
423        }\n
424        ";
425        let test_spec: PerPlatform<Spec> = exec_lua(lua_content, "test").unwrap();
426        assert_eq!(test_spec.default, Spec::Busted(Busted::default()));
427        let lua_content = "
428        test = {\n
429            type = 'busted',\n
430            flags = { 'foo', 'bar' },\n
431        }\n
432        ";
433        let test_spec: PerPlatform<Spec> = exec_lua(lua_content, "test").unwrap();
434        assert_eq!(
435            test_spec.default,
436            Spec::Busted(Busted {
437                flags: vec!["foo".into(), "bar".into()],
438            })
439        );
440        let lua_content = "
441        test = {\n
442            type = 'command',\n
443        }\n
444        ";
445        let result: Result<PerPlatform<Spec>, _> = exec_lua(lua_content, "test");
446        let _err = result.unwrap_err();
447        let lua_content = "
448        test = {\n
449            type = 'command',\n
450            command = 'foo',\n
451            script = 'bar',\n
452        }\n
453        ";
454        let result: Result<PerPlatform<Spec>, _> = exec_lua(lua_content, "test");
455        let _err = result.unwrap_err();
456        let lua_content = "
457        test = {\n
458            type = 'command',\n
459            command = 'baz',\n
460            flags = { 'foo', 'bar' },\n
461        }\n
462        ";
463        let test_spec: PerPlatform<Spec> = exec_lua(lua_content, "test").unwrap();
464        assert_eq!(
465            test_spec.default,
466            Spec::Command(Command {
467                command: "baz".into(),
468                flags: vec!["foo".into(), "bar".into()],
469            })
470        );
471        let lua_content = "
472        test = {\n
473            type = 'command',\n
474            script = 'test.lua',\n
475            flags = { 'foo', 'bar' },\n
476        }\n
477        ";
478        let test_spec: PerPlatform<Spec> = exec_lua(lua_content, "test").unwrap();
479        assert_eq!(
480            test_spec.default,
481            Spec::Script(LuaScript {
482                script: PathBuf::from("test.lua"),
483                flags: vec!["foo".into(), "bar".into()],
484            })
485        );
486        let lua_content = "
487        test = {\n
488            type = 'command',\n
489            command = 'baz',\n
490            flags = { 'foo', 'bar' },\n
491            platforms = {\n
492                unix = { flags = { 'baz' }, },\n
493                macosx = {\n
494                    script = 'bat.lua',\n
495                    flags = { 'bat' },\n
496                },\n
497                linux = { type = 'busted' },\n
498            },\n
499        }\n
500        ";
501        let test_spec: PerPlatform<Spec> = exec_lua(lua_content, "test").unwrap();
502        assert_eq!(
503            test_spec.default,
504            Spec::Command(Command {
505                command: "baz".into(),
506                flags: vec!["foo".into(), "bar".into()],
507            })
508        );
509        let unix = test_spec
510            .per_platform
511            .get(&platform::Identifier::Unix)
512            .unwrap();
513        assert_eq!(
514            *unix,
515            Spec::Command(Command {
516                command: "baz".into(),
517                flags: vec!["foo".into(), "bar".into(), "baz".into()],
518            })
519        );
520        let macosx = test_spec
521            .per_platform
522            .get(&platform::Identifier::MacOSX)
523            .unwrap();
524        assert_eq!(
525            *macosx,
526            Spec::Script(LuaScript {
527                script: "bat.lua".into(),
528                flags: vec!["foo".into(), "bar".into(), "bat".into(), "baz".into()],
529            })
530        );
531        let linux = test_spec
532            .per_platform
533            .get(&platform::Identifier::Linux)
534            .unwrap();
535        assert_eq!(
536            *linux,
537            Spec::Busted(Busted {
538                flags: vec!["foo".into(), "bar".into(), "baz".into()],
539            })
540        );
541        let lua_content = "
542        test = {\n
543            type = 'busted-nlua',\n
544        }";
545        let test_spec: PerPlatform<Spec> = exec_lua(lua_content, "test").unwrap();
546        assert_eq!(
547            test_spec.default,
548            Spec::BustedNlua(Busted { flags: Vec::new() })
549        );
550    }
551}