ctb_formats_javascript/
js_test.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! In-process JavaScript and TypeScript testing runner and assertion harness.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29use anyhow::{Result, bail};
30use std::path::Path;
31
32const ASSERT_JS: &str = r#"
33    // Headless browser environment stubs
34    const makeMock = () => {
35        const fn = (...args) => makeMock();
36        return new Proxy(fn, {
37            get: (target, prop) => {
38                if (prop === "classList") {
39                    return {
40                        add: () => {},
41                        remove: () => {},
42                        toggle: () => {},
43                        contains: () => false
44                    };
45                }
46                if (prop === "style") {
47                    return { setProperty: () => {} };
48                }
49                if (prop === "offsetWidth" || prop === "clientWidth" || prop === "innerWidth") {
50                    return 100;
51                }
52                if (prop === "querySelectorAll") {
53                    return () => [];
54                }
55                if (prop === "fontSize") {
56                    return "16px";
57                }
58                return makeMock();
59            }
60        });
61    };
62
63    globalThis.window = globalThis;
64    globalThis.window.location = { href: "http://localhost/", origin: "http://localhost" };
65    globalThis.document = makeMock();
66    globalThis.navigator = makeMock();
67    globalThis.getComputedStyle = () => makeMock();
68
69    globalThis.assert = function(condition, message) {
70        if (!condition) {
71            throw new Error(message || "Assertion failed: expected truthy, got " + condition);
72        }
73    };
74    globalThis.assertSame = function(actual, expected, message) {
75        if (actual !== expected) {
76            throw new Error(message || "Assertion failed: expected " + expected + " (strict), got " + actual);
77        }
78    };
79    globalThis.assertThrows = function(fn, expectedError, message) {
80        if (typeof fn !== 'function') {
81            throw new Error("assertThrows: first argument must be a function");
82        }
83        let threw = false;
84        let thrownError = null;
85        try {
86            fn();
87        } catch (e) {
88            threw = true;
89            thrownError = e;
90        }
91        if (!threw) {
92            throw new Error(message || "Assertion failed: expected function to throw, but it returned successfully");
93        }
94        if (expectedError !== undefined && expectedError !== null) {
95            if (typeof expectedError === 'function') {
96                if (!(thrownError instanceof expectedError)) {
97                    throw new Error(message || "Assertion failed: expected throw of type " + expectedError.name + ", but threw " + (thrownError ? thrownError.name || thrownError.constructor.name : "undefined"));
98                }
99            } else if (typeof expectedError === 'string') {
100                const errorMsg = thrownError ? (thrownError.message || String(thrownError)) : "";
101                if (!errorMsg.includes(expectedError)) {
102                    throw new Error(message || "Assertion failed: expected throw message to contain \"" + expectedError + "\", but was \"" + errorMsg + "\"");
103                }
104            }
105        }
106    };
107"#;
108
109#[derive(clap::Args, Debug, Clone, Default)]
110pub struct JsTestArgs {
111    /// Folder containing JavaScript tests
112    #[arg(value_name = "FOLDER")]
113    pub folder: String,
114}
115
116#[derive(clap::Parser, Debug, Clone)]
117#[command(name = "js-test", version = env!("CARGO_PKG_VERSION"))]
118pub struct JsTestBinaryCli {
119    #[command(flatten)]
120    pub args: JsTestArgs,
121}
122
123struct FileTestResult {
124    total: usize,
125    failed: usize,
126}
127
128fn run_test_file(file_path: &Path) -> Result<FileTestResult> {
129    let file_path = std::fs::canonicalize(file_path)?;
130    let cwd = std::fs::canonicalize(std::env::current_dir()?)?;
131
132    let (mut context, loader) =
133        ctb_formats_javascript_boa_host::create_context_with_bindings(
134            &file_path,
135            &cwd,
136            &[],
137            false,
138        )?;
139
140    // Register assertions
141    context
142        .eval(boa_engine::Source::from_bytes(ASSERT_JS.as_bytes()))
143        .map_err(|e| {
144            anyhow::anyhow!("Failed to evaluate assert helpers: {e}")
145        })?;
146
147    // Load and evaluate the test file module
148    let entry_source =
149        boa_engine::Source::from_filepath(&file_path).map_err(|e| {
150            anyhow::anyhow!(
151                "Failed to open entry file '{}': {}",
152                file_path.display(),
153                e
154            )
155        })?;
156    let module = boa_engine::Module::parse(entry_source, None, &mut context)
157        .map_err(|e| anyhow::anyhow!("Failed to parse module: {e}"))?;
158
159    loader.insert(file_path.clone(), module.clone());
160
161    let promise = module.load_link_evaluate(&mut context);
162    context
163        .run_jobs()
164        .map_err(|e| anyhow::anyhow!("Failed to run jobs: {e}"))?;
165
166    // Verify promise state
167    if let boa_engine::builtins::promise::PromiseState::Rejected(err) =
168        promise.state()
169    {
170        let js_err = boa_engine::JsError::from_opaque(err);
171        let erased = js_err.into_erased(&mut context);
172        let mut stack_trace = String::new();
173        for frame in context.stack_trace() {
174            let loc = frame.position();
175            let name = loc.function_name.to_std_string_escaped();
176            let path = format!("{}", loc.path);
177            // Reason for fallback: if source position information is unavailable for stack frame, empty string fallback omits line/column.
178            let pos = loc
179                .position
180                .map(|p| format!(":{}:{}", p.line_number(), p.column_number()))
181                .unwrap_or_default();
182            stack_trace.push_str(&format!("    at {name} ({path}{pos})\n"));
183        }
184        bail!(
185            "Module evaluation rejected: {erased:?}\nJS Stack Trace:\n{stack_trace}"
186        );
187    }
188
189    // Now find all test functions in the namespace and globalThis
190    let mut test_funcs = Vec::new();
191
192    // 1. From module namespace exports
193    let namespace = module.namespace(&mut context);
194    let keys = namespace.own_property_keys(&mut context).map_err(|e| {
195        anyhow::anyhow!("Failed to get namespace property keys: {e}")
196    })?;
197    for key in keys {
198        if let boa_engine::property::PropertyKey::String(js_str) = key {
199            let name = js_str.to_std_string_escaped();
200            if name.starts_with("test_") {
201                let val = namespace.get(js_str.clone(), &mut context).map_err(
202                    |e| {
203                        anyhow::anyhow!(
204                            "Failed to get namespace property '{name}': {e}"
205                        )
206                    },
207                )?;
208                if val.is_callable() {
209                    test_funcs.push((name, val));
210                }
211            }
212        }
213    }
214
215    // 2. From globalThis
216    let global_obj = context.global_object();
217    let global_keys =
218        global_obj.own_property_keys(&mut context).map_err(|e| {
219            anyhow::anyhow!("Failed to get global property keys: {e}")
220        })?;
221    for key in global_keys {
222        if let boa_engine::property::PropertyKey::String(js_str) = key {
223            let name = js_str.to_std_string_escaped();
224            if name.starts_with("test_") {
225                let val = global_obj
226                    .get(js_str.clone(), &mut context)
227                    .map_err(|e| {
228                        anyhow::anyhow!(
229                            "Failed to get global property '{name}': {e}"
230                        )
231                    })?;
232                if val.is_callable() {
233                    if !test_funcs.iter().any(|(n, _)| n == &name) {
234                        test_funcs.push((name, val));
235                    }
236                }
237            }
238        }
239    }
240
241    // Sort tests to make order deterministic
242    test_funcs.sort_by(|a, b| a.0.cmp(&b.0));
243
244    let mut total: usize = 0;
245    let mut failed: usize = 0;
246
247    for (name, val) in test_funcs {
248        total = total.saturating_add(1);
249        print!("  - {name} ... ");
250        std::io::Write::flush(&mut std::io::stdout())?;
251
252        let start = std::time::Instant::now();
253        let Some(obj) = val.as_object() else {
254            continue;
255        };
256        let result =
257            obj.call(&boa_engine::JsValue::undefined(), &[], &mut context);
258
259        let test_result = match result {
260            Ok(res_val) => {
261                let run_jobs_res = context.run_jobs();
262                match run_jobs_res {
263                    Ok(()) => {
264                        // Check if returned value is a promise
265                        if let Some(promise) = res_val.as_promise() {
266                            match promise.state() {
267                                boa_engine::builtins::promise::PromiseState::Rejected(err) => {
268                                    Err(boa_engine::JsError::from_opaque(err))
269                                }
270                                boa_engine::builtins::promise::PromiseState::Pending => {
271                                    Err(boa_engine::JsError::from_opaque(
272                                        boa_engine::JsValue::from(boa_engine::js_string!(
273                                            "Promise remained pending"
274                                        ))
275                                    ))
276                                }
277                                boa_engine::builtins::promise::PromiseState::Fulfilled(_) => {
278                                    Ok(())
279                                }
280                            }
281                        } else {
282                            Ok(())
283                        }
284                    }
285                    Err(e) => Err(e),
286                }
287            }
288            Err(e) => Err(e),
289        };
290
291        let duration = start.elapsed();
292
293        match test_result {
294            Ok(()) => {
295                println!("OK ({}ms)", duration.as_millis());
296            }
297            Err(js_err) => {
298                failed = failed.saturating_add(1);
299                let erased = js_err.into_erased(&mut context);
300                let mut stack_trace = String::new();
301                for frame in context.stack_trace() {
302                    let loc = frame.position();
303                    let name = loc.function_name.to_std_string_escaped();
304                    let path = format!("{}", loc.path);
305                    // Reason for fallback: if source position information is unavailable for stack frame, empty string fallback omits line/column.
306                    let pos = loc
307                        .position
308                        .map(|p| {
309                            format!(
310                                ":{}:{}",
311                                p.line_number(),
312                                p.column_number()
313                            )
314                        })
315                        .unwrap_or_default();
316                    stack_trace
317                        .push_str(&format!("    at {name} ({path}{pos})\n"));
318                }
319                println!("FAIL");
320                println!("    Error: {erased:?}");
321                if !stack_trace.is_empty() {
322                    println!("    JS Stack Trace:\n{stack_trace}");
323                }
324            }
325        }
326    }
327
328    Ok(FileTestResult { total, failed })
329}
330
331pub fn run_test_args(args: &JsTestArgs) -> Result<i32> {
332    let folder_path = Path::new(&args.folder);
333    if !folder_path.exists() {
334        bail!("Directory does not exist: {}", args.folder);
335    }
336    if !folder_path.is_dir() {
337        bail!("Path is not a directory: {}", args.folder);
338    }
339
340    let mut js_files = Vec::new();
341    for entry in walkdir::WalkDir::new(folder_path) {
342        let entry = entry?;
343        let path = entry.path();
344        if path.is_file()
345            && path.extension().and_then(|s| s.to_str()) == Some("js")
346        {
347            js_files.push(path.to_path_buf());
348        }
349    }
350
351    // Sort files to ensure deterministic execution order
352    js_files.sort();
353
354    let mut total_tests: usize = 0;
355    let mut total_failed: usize = 0;
356    let mut failed_files: usize = 0;
357
358    println!("Running tests in {}", folder_path.display());
359    println!("{}", "-".repeat(80));
360
361    for file_path in &js_files {
362        println!("File: {}", file_path.display());
363        match run_test_file(file_path) {
364            Ok(file_result) => {
365                total_tests = total_tests.saturating_add(file_result.total);
366                total_failed = total_failed.saturating_add(file_result.failed);
367                if file_result.failed > 0 {
368                    failed_files = failed_files.saturating_add(1);
369                }
370                println!(
371                    "  Result: {} passed, {} failed",
372                    file_result.total.saturating_sub(file_result.failed),
373                    file_result.failed
374                );
375            }
376            Err(e) => {
377                failed_files = failed_files.saturating_add(1);
378                println!("  Failed to load/run test file: {e}");
379            }
380        }
381        println!();
382    }
383
384    println!("{}", "-".repeat(80));
385    println!(
386        "Summary: {}/{} tests passed. {} failed. {}/{} files had failures.",
387        total_tests.saturating_sub(total_failed),
388        total_tests,
389        total_failed,
390        failed_files,
391        js_files.len()
392    );
393
394    if failed_files > 0 || total_failed > 0 {
395        Ok(1)
396    } else {
397        Ok(0)
398    }
399}
400
401#[cfg(test)]
402#[allow(
403    clippy::panic,
404    clippy::expect_used,
405    clippy::unwrap_used,
406    clippy::unwrap_in_result,
407    clippy::panic_in_result_fn,
408    clippy::indexing_slicing,
409    clippy::arithmetic_side_effects,
410    reason = "Standard repository test boilerplate"
411)]
412mod tests {
413    use super::*;
414    use tempfile::TempDir;
415
416    #[crate::ctb_test]
417    fn test_js_runner_success_and_failure() {
418        let temp_dir = TempDir::new().unwrap();
419        let path = temp_dir.path();
420
421        // 1. Write a passing test file
422        let pass_file = path.join("test_pass.js");
423        std::fs::write(
424            &pass_file,
425            r"
426            export function test_assert_true() {
427                assert(true);
428            }
429            export function test_assertSame() {
430                assertSame(5, 5);
431            }
432            ",
433        )
434        .unwrap();
435
436        // 2. Write a failing test file
437        let fail_file = path.join("test_fail.js");
438        std::fs::write(
439            &fail_file,
440            r#"
441            export function test_assert_false() {
442                assert(false, "this should fail");
443            }
444            "#,
445        )
446        .unwrap();
447
448        // 3. Run on the whole folder
449        let args = JsTestArgs {
450            folder: path.to_string_lossy().into_owned(),
451        };
452
453        let exit_code = run_test_args(&args).unwrap();
454        // Since one file has a failing test, exit code should be 1
455        assert_eq!(exit_code, 1);
456    }
457
458    #[crate::ctb_test]
459    fn test_js_runner_all_pass() {
460        let temp_dir = TempDir::new().unwrap();
461        let path = temp_dir.path();
462
463        let pass_file = path.join("test_pass.js");
464        std::fs::write(
465            &pass_file,
466            r#"
467            export function test_assert_true() {
468                assert(true);
469            }
470            export function test_assertSame() {
471                assertSame("hello", "hello");
472            }
473            export function test_assertThrows() {
474                assertThrows(() => {
475                    throw new TypeError("some error");
476                }, TypeError);
477            }
478            "#,
479        )
480        .unwrap();
481
482        let args = JsTestArgs {
483            folder: path.to_string_lossy().into_owned(),
484        };
485
486        let exit_code = run_test_args(&args).unwrap();
487        assert_eq!(exit_code, 0);
488    }
489
490    #[crate::ctb_test]
491    fn test_js_runner_filesystem_isolation() {
492        let temp_dir = TempDir::new().unwrap();
493        let path = temp_dir.path();
494
495        let pass_file = path.join("test_isolated.js");
496        std::fs::write(
497            &pass_file,
498            r#"
499            export function test_fs_is_isolated() {
500                // process.cwd should throw error
501                assertThrows(() => {
502                    process.cwd();
503                });
504                // require("fs").readFileSync should throw error
505                assertThrows(() => {
506                    require("fs").readFileSync("foo.txt");
507                });
508            }
509            "#,
510        )
511        .unwrap();
512
513        let args = JsTestArgs {
514            folder: path.to_string_lossy().into_owned(),
515        };
516
517        let exit_code = run_test_args(&args).unwrap();
518        assert_eq!(exit_code, 0);
519    }
520}