testing 28.0.1

Testing utilities for the swc project.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use std::{
    env,
    fmt::{self, Debug, Display, Formatter},
    fs::{create_dir_all, rename, File},
    io::Write,
    path::{Component, Path, PathBuf},
    process::Command,
    str::FromStr,
    sync::RwLock,
    thread,
};

use difference::Changeset;
use once_cell::sync::Lazy;
pub use pretty_assertions::{assert_eq, assert_ne};
use regex::Regex;
use rustc_hash::FxHashMap;
use swc_common::{
    errors::{Diagnostic, Handler, HANDLER},
    sync::Lrc,
    FilePathMapping, SourceMap,
};
pub use testing_macros::fixture;
use tracing_subscriber::EnvFilter;

pub use self::output::{NormalizedOutput, StdErr, StdOut, TestOutput};

mod errors;
pub mod json;
#[macro_use]
mod macros;
mod diag_errors;
mod output;
mod paths;
mod string_errors;

/// Configures logger
#[must_use]
pub fn init() -> tracing::subscriber::DefaultGuard {
    let log_env = env::var("RUST_LOG").unwrap_or_else(|_| "debug".to_string());

    let logger = tracing_subscriber::FmtSubscriber::builder()
        .without_time()
        .with_target(false)
        .with_ansi(true)
        .with_env_filter(EnvFilter::from_str(&log_env).unwrap())
        .with_test_writer()
        .pretty()
        .finish();

    tracing::subscriber::set_default(logger)
}

pub fn find_executable(name: &str) -> Option<PathBuf> {
    static CACHE: Lazy<RwLock<FxHashMap<String, PathBuf>>> = Lazy::new(Default::default);

    {
        let locked = CACHE.read().unwrap();
        if let Some(cached) = locked.get(name) {
            return Some(cached.clone());
        }
    }

    let candidates = executable_candidates(name);
    let mut path = env::var_os("PATH").and_then(|paths| {
        env::split_paths(&paths)
            .filter_map(|dir| find_executable_in_dir(&dir, &candidates))
            .next()
    });

    if path.is_none() {
        // pnpm bin prints the directory containing package executables.
        path = Command::new("pnpm")
            .arg("bin")
            .output()
            .ok()
            .and_then(|output| {
                if output.status.success() {
                    let bin_dir = String::from_utf8(output.stdout).ok()?;
                    let bin_dir = PathBuf::from(bin_dir.trim());
                    return find_executable_in_dir(&bin_dir, &candidates);
                }

                None
            });
    }

    if let Some(path) = path.clone() {
        let mut locked = CACHE.write().unwrap();
        locked.insert(name.to_string(), path);
    }

    path
}

fn executable_candidates(name: &str) -> Vec<String> {
    if cfg!(windows) && Path::new(name).extension().is_none() {
        vec![
            format!("{name}.exe"),
            format!("{name}.cmd"),
            format!("{name}.bat"),
            name.to_string(),
        ]
    } else {
        vec![name.to_string()]
    }
}

fn find_executable_in_dir(dir: &Path, candidates: &[String]) -> Option<PathBuf> {
    candidates
        .iter()
        .map(|candidate| dir.join(candidate))
        .find(|path| path.is_file())
}

/// Run test and print errors.
pub fn run_test<F, Ret>(treat_err_as_bug: bool, op: F) -> Result<Ret, StdErr>
where
    F: FnOnce(Lrc<SourceMap>, &Handler) -> Result<Ret, ()>,
{
    let _log = init();

    let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
    let (handler, errors) = self::string_errors::new_handler(cm.clone(), treat_err_as_bug);
    let result = swc_common::GLOBALS.set(&swc_common::Globals::new(), || {
        HANDLER.set(&handler, || op(cm, &handler))
    });

    match result {
        Ok(res) => Ok(res),
        Err(()) => Err(errors.into()),
    }
}

/// Run test and print errors.
pub fn run_test2<F, Ret>(treat_err_as_bug: bool, op: F) -> Result<Ret, StdErr>
where
    F: FnOnce(Lrc<SourceMap>, Handler) -> Result<Ret, ()>,
{
    let _log = init();

    let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
    let (handler, errors) = self::string_errors::new_handler(cm.clone(), treat_err_as_bug);
    let result = swc_common::GLOBALS.set(&swc_common::Globals::new(), || op(cm, handler));

    match result {
        Ok(res) => Ok(res),
        Err(()) => Err(errors.into()),
    }
}

pub struct Tester {
    pub cm: Lrc<SourceMap>,
    pub globals: swc_common::Globals,
    treat_err_as_bug: bool,
}

impl Tester {
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Tester {
            cm: Lrc::new(SourceMap::new(FilePathMapping::empty())),
            globals: swc_common::Globals::new(),
            treat_err_as_bug: false,
        }
    }

    pub fn no_error(mut self) -> Self {
        self.treat_err_as_bug = true;
        self
    }

    /// Run test and print errors.
    pub fn print_errors<F, Ret>(&self, op: F) -> Result<Ret, StdErr>
    where
        F: FnOnce(Lrc<SourceMap>, Handler) -> Result<Ret, ()>,
    {
        let _log = init();

        let (handler, errors) =
            self::string_errors::new_handler(self.cm.clone(), self.treat_err_as_bug);
        let result = swc_common::GLOBALS.set(&self.globals, || op(self.cm.clone(), handler));

        match result {
            Ok(res) => Ok(res),
            Err(()) => Err(errors.into()),
        }
    }

    /// Run test and collect errors.
    pub fn errors<F, Ret>(&self, op: F) -> Result<Ret, Vec<Diagnostic>>
    where
        F: FnOnce(Lrc<SourceMap>, Handler) -> Result<Ret, ()>,
    {
        let _log = init();

        let (handler, errors) =
            self::diag_errors::new_handler(self.cm.clone(), self.treat_err_as_bug);
        let result = swc_common::GLOBALS.set(&self.globals, || op(self.cm.clone(), handler));

        let mut errs: Vec<_> = errors.into();
        errs.sort_by_key(|d| {
            let span = d.span.primary_span().unwrap();
            let cp = self.cm.lookup_char_pos(span.lo());

            let line = cp.line;
            let column = cp.col.0 + 1;

            line * 10000 + column
        });

        match result {
            Ok(res) => Ok(res),
            Err(()) => Err(errs),
        }
    }
}

fn write_to_file(path: &Path, content: &str) {
    File::create(path)
        .unwrap_or_else(|err| {
            panic!(
                "failed to create file ({}) for writing data of the failed assertion: {}",
                path.display(),
                err
            )
        })
        .write_all(content.as_bytes())
        .expect("failed to write data of the failed assertion")
}

pub fn print_left_right(left: &dyn Debug, right: &dyn Debug) -> String {
    fn print(t: &dyn Debug) -> String {
        let s = format!("{t:#?}");

        // Replace 'Span { lo: BytePos(0), hi: BytePos(0), ctxt: #0 }' with '_'
        let s = {
            static RE: Lazy<Regex> =
                Lazy::new(|| Regex::new("Span \\{[\\a-zA-Z0#:\\(\\)]*\\}").unwrap());

            &RE
        }
        .replace_all(&s, "_");
        // Remove 'span: _,'
        let s = {
            static RE: Lazy<Regex> = Lazy::new(|| Regex::new("span: _[,]?\\s*").unwrap());

            &RE
        }
        .replace_all(&s, "");

        s.into()
    }

    let (left, right) = (print(left), print(right));

    let cur = thread::current();
    let test_name = cur
        .name()
        .expect("rustc sets test name as the name of thread");

    // ./target/debug/tests/${test_name}/
    let target_dir = {
        let mut buf = paths::test_results_dir().to_path_buf();
        for m in test_name.split("::") {
            buf.push(m)
        }

        create_dir_all(&buf).unwrap_or_else(|err| {
            panic!(
                "failed to create directory ({}) for writing data of the failed assertion: {}",
                buf.display(),
                err
            )
        });

        buf
    };

    write_to_file(&target_dir.join("left"), &left);
    write_to_file(&target_dir.join("right"), &right);

    format!("----- {test_name}\n    left:\n{left}\n    right:\n{right}")
}

#[macro_export]
macro_rules! assert_eq_ignore_span {
    ($l:expr, $r:expr) => {{
        println!("{}", module_path!());
        let (l, r) = ($crate::drop_span($l), $crate::drop_span($r));
        if l != r {
            panic!("assertion failed\n{}", $crate::print_left_right(&l, &r));
        }
    }};
}

pub fn diff(l: &str, r: &str) -> String {
    let cs = Changeset::new(l, r, "\n");

    format!("{cs}")
}

/// Used for assertions.
///
/// Prints string without escaping special characters on failure.
#[derive(PartialEq, Eq)]
pub struct DebugUsingDisplay<'a>(pub &'a str);

impl Debug for DebugUsingDisplay<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Display::fmt(self.0, f)
    }
}

/// Rename `foo/.bar/exec.js` => `foo/bar/exec.js`
///
/// Only components below the cargo workspace root mark a fixture as ignored.
/// Hidden directories above the workspace, such as a worktree stored in
/// `~/.worktrees`, are kept as they are.
pub fn unignore_fixture(fixture_path: &Path) {
    // Fast path: most fixtures have no hidden component at all, so avoid
    // resolving the workspace root for them.
    if !fixture_path.components().any(is_hidden_component) {
        return;
    }

    let root = CARGO_WORKSPACE_ROOT
        .canonicalize()
        .unwrap_or_else(|_| CARGO_WORKSPACE_ROOT.clone());

    let Some(new_path) = unignored_fixture_path(fixture_path, &root) else {
        return;
    };

    create_dir_all(new_path.parent().unwrap()).expect("failed to create parent dir");

    rename(fixture_path, &new_path).expect("failed to rename");
}

/// Returns the path of `fixture_path` with the leading `.` removed from every
/// hidden component below `root`.
///
/// Returns [None] if `fixture_path` is not in `root` or if no component below
/// `root` is hidden.
fn unignored_fixture_path(fixture_path: &Path, root: &Path) -> Option<PathBuf> {
    let relative = fixture_path.strip_prefix(root).ok()?;

    if !relative.components().any(is_hidden_component) {
        return None;
    }

    let mut new_path = root.to_path_buf();

    for c in relative.components() {
        if let Component::Normal(s) = c {
            if let Some(s) = s.to_string_lossy().strip_prefix('.') {
                new_path.push(s);

                continue;
            }
        }
        new_path.push(c);
    }

    Some(new_path)
}

/// Returns whether `c` is a normal path component that starts with `.`.
fn is_hidden_component(c: Component) -> bool {
    matches!(c, Component::Normal(s) if s.to_string_lossy().starts_with('.'))
}

pub static CARGO_TARGET_DIR: Lazy<PathBuf> = Lazy::new(|| {
    cargo_metadata::MetadataCommand::new()
        .no_deps()
        .exec()
        .unwrap()
        .target_directory
        .into()
});

pub static CARGO_WORKSPACE_ROOT: Lazy<PathBuf> = Lazy::new(|| {
    cargo_metadata::MetadataCommand::new()
        .no_deps()
        .exec()
        .unwrap()
        .workspace_root
        .into()
});

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};

    use super::unignored_fixture_path;

    #[test]
    fn unignores_hidden_fixture_components() {
        assert_eq!(
            unignored_fixture_path(
                Path::new("/repo/crates/foo/tests/exec/.case/exec.js"),
                Path::new("/repo")
            ),
            Some(PathBuf::from("/repo/crates/foo/tests/exec/case/exec.js"))
        );
    }

    #[test]
    fn keeps_hidden_components_above_workspace_root() {
        let root = Path::new("/home/user/.worktrees/repo");

        assert_eq!(
            unignored_fixture_path(&root.join("crates/foo/tests/exec/case/exec.js"), root),
            None
        );
        assert_eq!(
            unignored_fixture_path(&root.join("crates/foo/tests/exec/.case/exec.js"), root),
            Some(root.join("crates/foo/tests/exec/case/exec.js"))
        );
    }

    #[test]
    fn ignores_fixtures_outside_workspace_root() {
        assert_eq!(
            unignored_fixture_path(Path::new("/other/.case/exec.js"), Path::new("/repo")),
            None
        );
    }
}