Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/fspy/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ tempfile = { workspace = true }
anyhow = { workspace = true }
csv-async = { workspace = true }
ctor = { workspace = true }
ntest = { workspace = true }
subprocess_test = { workspace = true, features = ["fspy"] }
test-log = { workspace = true }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "fs", "io-std"] }
Expand Down
143 changes: 96 additions & 47 deletions crates/fspy/tests/node_fs.rs
Original file line number Diff line number Diff line change
@@ -1,112 +1,161 @@
mod test_utils;

use std::{
env::{current_dir, vars_os},
ffi::OsStr,
env::{current_dir, join_paths, split_paths, var_os, vars_os},
ffi::{OsStr, OsString},
iter,
path::PathBuf,
};

use fspy::{AccessMode, PathAccessIterable};
use test_log::test;
use ntest::test_case;
use test_utils::assert_contains;

async fn track_node_script(script: &str, args: &[&OsStr]) -> anyhow::Result<PathAccessIterable> {
let mut command = fspy::Command::new("node");
fn resolve_runtime(runtime: &str) -> anyhow::Result<(PathBuf, OsString)> {
let manifest_dir = PathBuf::from(var_os("CARGO_MANIFEST_DIR").unwrap());
let tools_bin =
manifest_dir.parent().unwrap().parent().unwrap().join("packages/tools/node_modules/.bin");
let path =
join_paths(iter::once(tools_bin).chain(var_os("PATH").iter().flat_map(split_paths)))?;
let program = which::which_in(runtime, Some(&path), current_dir()?)?;
Ok((program, path))
}

fn track_script(
runtime: &str,
script: &str,
args: &[&OsStr],
) -> anyhow::Result<PathAccessIterable> {
let (program, path) = resolve_runtime(runtime)?;

let mut command = fspy::Command::new(program);
command
.arg("-e")
.envs(vars_os()) // https://github.com/jdx/mise/discussions/5968
.arg(script)
.args(args);
let child = command.spawn(tokio_util::sync::CancellationToken::new()).await?;
let termination = child.wait_handle.await?;
assert!(termination.status.success());
Ok(termination.path_accesses)
.envs(vars_os().filter(|(name, _)| !name.eq_ignore_ascii_case("PATH")))
.env("PATH", path); // https://github.com/jdx/mise/discussions/5968
let script = format!(
"const fs = require('node:fs'); \
const child_process = require('node:child_process'); \
{script}"
);
if runtime == "deno" {
command.args(["eval", "--ext=cjs"]).arg(script).args(args);
} else {
command.arg("-e").arg(script).args(args);
}

// `ntest::test_case` generates synchronous `#[test]` functions, so drive
// fspy's asynchronous process tracking from this shared helper.
tokio::runtime::Runtime::new()?.block_on(async {
let child = command.spawn(tokio_util::sync::CancellationToken::new()).await?;
let termination = child.wait_handle.await?;
assert!(termination.status.success());
Ok(termination.path_accesses)
})
}

#[test(tokio::test)]
// Deno does not distribute a musl runtime, so only its generated cases are
// excluded there. Node remains covered by the same tests on musl.
#[test_case("node")]
#[ignore = "requires node"]
async fn read_sync() -> anyhow::Result<()> {
let accesses = track_node_script("try { fs.readFileSync('hello') } catch {}", &[]).await?;
#[cfg_attr(not(target_env = "musl"), test_case("deno"))]
#[cfg_attr(not(target_env = "musl"), ignore = "requires node")]
fn read_sync(runtime: &str) -> anyhow::Result<()> {
let accesses = track_script(runtime, "try { fs.readFileSync('hello') } catch {}", &[])?;
assert_contains(&accesses, current_dir().unwrap().join("hello").as_path(), AccessMode::READ);
Ok(())
}

#[test(tokio::test)]
#[test_case("node")]
#[ignore = "requires node"]
async fn exist_sync() -> anyhow::Result<()> {
let accesses = track_node_script("try { fs.existsSync('hello') } catch {}", &[]).await?;
#[cfg_attr(not(target_env = "musl"), test_case("deno"))]
#[cfg_attr(not(target_env = "musl"), ignore = "requires node")]
fn exist_sync(runtime: &str) -> anyhow::Result<()> {
let accesses = track_script(runtime, "try { fs.existsSync('hello') } catch {}", &[])?;
assert_contains(&accesses, current_dir().unwrap().join("hello").as_path(), AccessMode::READ);
Ok(())
}

#[test(tokio::test)]
#[test_case("node")]
#[ignore = "requires node"]
async fn stat_sync() -> anyhow::Result<()> {
let accesses = track_node_script("try { fs.statSync('hello') } catch {}", &[]).await?;
#[cfg_attr(not(target_env = "musl"), test_case("deno"))]
#[cfg_attr(not(target_env = "musl"), ignore = "requires node")]
fn stat_sync(runtime: &str) -> anyhow::Result<()> {
let accesses = track_script(runtime, "try { fs.statSync('hello') } catch {}", &[])?;
assert_contains(&accesses, current_dir().unwrap().join("hello").as_path(), AccessMode::READ);
Ok(())
}

#[test(tokio::test)]
#[test_case("node")]
#[ignore = "requires node"]
async fn create_read_stream() -> anyhow::Result<()> {
let accesses = track_node_script(
#[cfg_attr(not(target_env = "musl"), test_case("deno"))]
#[cfg_attr(not(target_env = "musl"), ignore = "requires node")]
fn create_read_stream(runtime: &str) -> anyhow::Result<()> {
let accesses = track_script(
runtime,
"try { fs.createReadStream('hello').on('error', () => {}) } catch {}",
&[],
)
.await?;
)?;
assert_contains(&accesses, current_dir().unwrap().join("hello").as_path(), AccessMode::READ);
Ok(())
}

#[test(tokio::test)]
#[test_case("node")]
#[ignore = "requires node"]
async fn create_write_stream() -> anyhow::Result<()> {
#[cfg_attr(not(target_env = "musl"), test_case("deno"))]
#[cfg_attr(not(target_env = "musl"), ignore = "requires node")]
fn create_write_stream(runtime: &str) -> anyhow::Result<()> {
let tmpdir = tempfile::tempdir()?;
let file_path = tmpdir.path().join("hello");
let accesses = track_node_script(
"try { fs.createWriteStream(process.argv[1]).on('error', () => {}) } catch {}",
let accesses = track_script(
runtime,
"try { fs.createWriteStream(process.argv.at(-1)).on('error', () => {}) } catch {}",
&[file_path.as_os_str()],
)
.await?;
)?;
assert_contains(&accesses, file_path.as_path(), AccessMode::WRITE);
Ok(())
}

#[test(tokio::test)]
#[test_case("node")]
#[ignore = "requires node"]
async fn write_sync() -> anyhow::Result<()> {
#[cfg_attr(not(target_env = "musl"), test_case("deno"))]
#[cfg_attr(not(target_env = "musl"), ignore = "requires node")]
fn write_sync(runtime: &str) -> anyhow::Result<()> {
let tmpdir = tempfile::tempdir()?;
let file_path = tmpdir.path().join("hello");
let accesses = track_node_script(
"try { fs.writeFileSync(process.argv[1], '') } catch {}",
let accesses = track_script(
runtime,
"try { fs.writeFileSync(process.argv.at(-1), '') } catch {}",
&[file_path.as_os_str()],
)
.await?;
)?;
assert_contains(&accesses, &file_path, AccessMode::WRITE);
Ok(())
}

#[test(tokio::test)]
#[test_case("node")]
#[ignore = "requires node"]
async fn read_dir_sync() -> anyhow::Result<()> {
let accesses = track_node_script("try { fs.readdirSync('.') } catch {}", &[]).await?;
#[cfg_attr(not(target_env = "musl"), test_case("deno"))]
#[cfg_attr(not(target_env = "musl"), ignore = "requires node")]
fn read_dir_sync(runtime: &str) -> anyhow::Result<()> {
let accesses = track_script(runtime, "try { fs.readdirSync('.') } catch {}", &[])?;
assert_contains(&accesses, &current_dir().unwrap(), AccessMode::READ_DIR);
Ok(())
}

#[test(tokio::test)]
#[test_case("node")]
#[ignore = "requires node"]
async fn subprocess() -> anyhow::Result<()> {
#[cfg_attr(not(target_env = "musl"), test_case("deno"))]
#[cfg_attr(not(target_env = "musl"), ignore = "requires node")]
fn subprocess(runtime: &str) -> anyhow::Result<()> {
let cmd = if cfg!(windows) {
r"'cmd', ['/c', 'type hello']"
} else {
r"'/bin/sh', ['-c', 'cat hello']"
};
let accesses = track_node_script(
let accesses = track_script(
runtime,
&format!("try {{ child_process.spawnSync({cmd}, {{ stdio: 'ignore' }}) }} catch {{}}"),
&[],
)
.await?;
)?;
assert_contains(&accesses, current_dir().unwrap().join("hello").as_path(), AccessMode::READ);
Ok(())
}
1 change: 1 addition & 0 deletions packages/tools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"@vitest/browser-playwright": "catalog:",
"@voidzero-dev/vite-task-client": "workspace:*",
"cross-env": "catalog:",
"deno": "catalog:",
"oxfmt": "catalog:",
"oxlint": "catalog:",
"oxlint-tsgolint": "catalog:",
Expand Down
69 changes: 69 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ packages:

allowBuilds:
'@playwright/browser-chromium': true
deno: true

catalog:
'@tsconfig/strictest': ^2.0.8
'@types/node': 25.0.3
'@playwright/browser-chromium': 1.52.0
'@vitest/browser-playwright': 4.1.10
cross-env: ^10.1.0
deno: 2.9.2
husky: ^9.1.7
lint-staged: ^17.0.0
oxfmt: 0.57.0
Expand Down
Loading