Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 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
45 changes: 43 additions & 2 deletions src/runtime/cli/test_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2036,6 +2036,8 @@ impl TestCommand {
let mut snapshot_values: bun_collections::HashMap<u64, Box<[u8]>> =
bun_collections::HashMap::new();
let mut snapshot_counts: StringHashMap<usize> = StringHashMap::new();
let mut snapshot_unchecked_keys: StringHashMap<()> = StringHashMap::new();
let mut snapshot_skipped_test_names: Vec<(FileId, Box<[u8]>)> = Vec::new();
let mut inline_snapshots_to_write: ArrayHashMap<FileId, Vec<InlineSnapshotToWrite>> =
ArrayHashMap::new();
jsc::virtual_machine::isBunTest.store(true, core::sync::atomic::Ordering::Relaxed);
Expand Down Expand Up @@ -2097,6 +2099,8 @@ impl TestCommand {
added: 0,
passed: 0,
failed: 0,
obsolete: 0,
removed: 0,
// SAFETY: lifetime-erase to `'static`; the backing locals are
// declared in this never-returning frame (`exec()` only exits
// via process exit).
Expand All @@ -2105,6 +2109,15 @@ impl TestCommand {
values: unsafe { bun_ptr::detach_lifetime_mut(&mut snapshot_values) },
// SAFETY: same never-returning-frame invariant as `file_buf` above.
counts: unsafe { bun_ptr::detach_lifetime_mut(&mut snapshot_counts) },
// SAFETY: same never-returning-frame invariant as `file_buf` above.
unchecked_keys: unsafe {
bun_ptr::detach_lifetime_mut(&mut snapshot_unchecked_keys)
},
// SAFETY: same never-returning-frame invariant as `file_buf` above.
skipped_test_names: unsafe {
bun_ptr::detach_lifetime_mut(&mut snapshot_skipped_test_names)
},
had_only_in_file: false,
_current_file: None,
snapshot_dir_path: None,
// SAFETY: same never-returning-frame invariant as `file_buf` above.
Expand Down Expand Up @@ -2845,13 +2858,20 @@ impl TestCommand {
}

let mut print_expect_calls = summary.expectations > 0;
if reporter.jest.snapshots.total > 0 {
let obsolete = reporter.jest.snapshots.obsolete;
let removed = reporter.jest.snapshots.removed;
if reporter.jest.snapshots.total > 0 || obsolete > 0 || removed > 0 {
Comment thread
robobun marked this conversation as resolved.
Resolved
let passed = reporter.jest.snapshots.passed;
let failed = reporter.jest.snapshots.failed;
let added = reporter.jest.snapshots.added;

let mut first = true;
if print_expect_calls && added == 0 && failed == 0 {
if print_expect_calls
&& added == 0
&& failed == 0
&& obsolete == 0
&& removed == 0
{
print_expect_calls = false;
pretty_error!(
"{}{:5>} snapshots, {:5>} expect() calls",
Expand All @@ -2876,13 +2896,34 @@ impl TestCommand {
}
}

if removed > 0 {
if first {
first = false;
pretty_error!("<b>{} removed<r>", removed);
} else {
pretty_error!("<b>, {} removed<r>", removed);
}
}

if failed > 0 {
if first {
first = false;
pretty_error!("<red>{} failed<r>", failed);
} else {
pretty_error!(", <red>{} failed<r>", failed);
}
}

if obsolete > 0 {
if first {
pretty_error!("<yellow>{} obsolete<r>", obsolete);
} else {
pretty_error!(", <yellow>{} obsolete<r>", obsolete);
}
pretty_error!(
"\n<d>To remove obsolete snapshots, run <r><cyan>bun test -u<r>"
);
}
}

pretty_error!("\n");
Expand Down
55 changes: 55 additions & 0 deletions src/runtime/test_runner/Execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,42 @@

fn on_entry_completed(_entry: NonNull<ExecutionEntry>) {}

/// Build `{describe...} {testName}` identical to `Expect::get_snapshot_name`
/// with an empty hint, so skipped tests can mark their snapshot keys checked.
fn snapshot_name_for_entry(entry: &ExecutionEntry) -> Vec<u8> {
let test_name: &[u8] = entry.base.name.as_deref().unwrap_or(b"(unnamed)");
Comment thread
robobun marked this conversation as resolved.
Resolved
let mut length = test_name.len();
let mut curr = entry.base.parent;
while let Some(scope) = curr {
// SAFETY: `parent` is a live backref into the BunTest-owned describe tree.
let scope = unsafe { &*scope };
if let Some(name) = scope.base.name.as_deref() {
if !name.is_empty() {
length += name.len() + 1;
}
}
curr = scope.base.parent;
}
let mut buf = vec![0u8; length];
let mut index = buf.len();
index -= test_name.len();
buf[index..].copy_from_slice(test_name);
curr = entry.base.parent;
while let Some(scope) = curr {
// SAFETY: `parent` is a live backref into the BunTest-owned describe tree.
let scope = unsafe { &*scope };
if let Some(name) = scope.base.name.as_deref() {
if !name.is_empty() {
index -= name.len() + 1;
buf[index..index + name.len()].copy_from_slice(name);
buf[index + name.len()] = b' ';
}
}
curr = scope.base.parent;
}
buf
}

fn on_sequence_completed(buntest: NonNull<BunTest>, sequence: &mut ExecutionSequence) {
let elapsed_ns: u64 = if sequence.started_at.eql(&Timespec::EPOCH) {
0
Expand Down Expand Up @@ -672,6 +708,25 @@
_ => Result::Pass,
};
}
if let Some(entry_ptr) = sequence.test_entry {
if let Some(runner) = super::jest::Jest::runner() {
// SAFETY: `buntest` is the live parent BunTest (owns `sequence`).
let (file_id, root_only) = {
let bt = unsafe { buntest.as_ref() };

Check failure on line 715 in src/runtime/test_runner/Execution.rs

View workflow job for this annotation

GitHub Actions / cargo clippy

unsafe block missing a safety comment
(bt.file_id, bt.collection.root_scope.base.only)
};
if root_only != super::bun_test::Only::No {
runner.snapshots.had_only_in_file = true;
}
if sequence.result != Result::Pass {
// SAFETY: arena-owned entry, alive for the lifetime of BunTest.
let name = Self::snapshot_name_for_entry(unsafe { entry_ptr.as_ref() });
runner
.snapshots
.note_skipped_test(file_id, name.into_boxed_slice());
}

Check warning on line 727 in src/runtime/test_runner/Execution.rs

View check run for this annotation

Claude / Claude Code Review

test.failing() that throws is not noted, causing false-positive obsolete

The `!= Result::Pass` guard misses one path: a `test.failing()` body that throws. `handle_uncaught_exception` sets `sequence.result = Result::Pass` for `ScopeMode::Failing` (with `maybe_skip = true`), so any `toMatchSnapshot()` after the throw is never reached and its key stays in `unchecked_keys` — but `note_skipped_test` is skipped because the result is `Pass`, and the key is tallied as obsolete on a green run. Simplest fix: drop the guard and note every completed test (a truly-passing test's
Comment thread
robobun marked this conversation as resolved.
Resolved
}
Comment thread
robobun marked this conversation as resolved.
Resolved
}
if let Some(first_entry) = sequence.first_entry {
if sequence.test_entry.is_some() || sequence.result != Result::Pass {
// SAFETY: deref parent BunTest at point-of-use. `sequence` aliases
Expand Down
113 changes: 94 additions & 19 deletions src/runtime/test_runner/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,26 @@
pub added: usize,
pub passed: usize,
pub failed: usize,
pub obsolete: usize,
pub removed: usize,

pub file_buf: &'a mut Vec<u8>,
// LIFETIMES.tsv said `HashMap<usize, String>`; overridden per §Strings (data is bytes) → Box<[u8]>.
// Key is u64 to match `bun.hash`'s return type (avoids a narrowing cast).
pub values: &'a mut HashMap<u64, Box<[u8]>>,
pub counts: &'a mut StringHashMap<usize>,
/// Snapshot keys loaded from the `.snap` file but not yet matched this run.
/// Remaining entries at file close are obsolete (or removed under `-u`).
pub unchecked_keys: &'a mut StringHashMap<()>,
/// Full names of tests that completed without matching all of their keys
/// (skipped/todo/filtered/failed). Reconciled against `unchecked_keys` at
/// `write_snapshot_file` so ordering relative to the first
/// `toMatchSnapshot` call does not matter.
pub skipped_test_names: &'a mut Vec<(FileId, Box<[u8]>)>,
/// Set when the current file used `.only()` (CLI or in-source). Unchecked
/// keys are then ignored for the obsolete tally since non-only tests were
/// never sequenced.
pub had_only_in_file: bool,
pub _current_file: Option<File>,
/// Read-only backref into `Jest::RUNNER.files[..].source.path` (not owned
/// here, never freed): the runner is process-global and its files are
Expand Down Expand Up @@ -158,6 +172,10 @@
name_with_counter.extend_from_slice(counter_string);

let name_hash: u64 = hash(&name_with_counter);
let was_in_file = self
.unchecked_keys
.remove(name_with_counter.as_slice())
.is_some();
// reshaped for borrowck — `get` then early-return borrows `*self.values`
// immutably for the whole fn body (NLL limitation with returned borrows), preventing
// the later `insert`. Probe with `contains_key` first; re-lookup on hit.
Expand Down Expand Up @@ -201,7 +219,11 @@
)
.map_err(|_| crate::Error::WriteError)?;

self.added += 1;
if was_in_file {
self.passed += 1;
} else {
self.added += 1;
}
self.values
.insert(name_hash, Box::<[u8]>::from(target_value));
Ok(None)
Expand Down Expand Up @@ -314,6 +336,7 @@
Box::<[u8]>::from(value);
let name_hash: u64 = hash(key);
self.values.insert(name_hash, value_clone);
let _ = self.unchecked_keys.put(key, ());
}
}
}
Expand All @@ -330,22 +353,69 @@
Ok(())
}

pub fn write_snapshot_file(&mut self) -> Result<(), Error> {
if let Some(file) = self._current_file.take() {
if self.update_snapshots {
// Skipped tests' entries are not rewritten into `file_buf`, so
// they are physically removed; keep them in the tally.
self.removed += self.unchecked_keys.len();
} else if !self.had_only_in_file {
for (id, name) in self.skipped_test_names.iter() {
if *id == file.id {
Self::mark_snapshots_as_checked_for_test(self.unchecked_keys, name);
}
}
self.obsolete += self.unchecked_keys.len();
}
self.skipped_test_names.retain(|(id, _)| *id != file.id);
self.had_only_in_file = false;

Check warning on line 371 in src/runtime/test_runner/snapshot.rs

View check run for this annotation

Claude / Claude Code Review

had_only_in_file leaks across files when .only() file has no toMatchSnapshot

Same structural issue as the `skipped_test_names` retain above, but with a correctness effect: `had_only_in_file` is set in `on_sequence_completed` whenever a file's root scope has `.only()`, but only reset here inside the `if let Some(file)` block. If file A has `test.only()` on a test that never calls `toMatchSnapshot()`, `_current_file` stays `None`, so when file B's `get_snapshot_file` calls `write_snapshot_file()` the body is skipped and the flag stays `true` — file B's genuinely-obsolete k
Comment thread
robobun marked this conversation as resolved.
Resolved

file.file
.write_all(self.file_buf)
.map_err(|_| crate::Error::FailedToWriteSnapshotFile)?;
if self.update_snapshots {
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
bun_sys::ftruncate(file.file.handle, self.file_buf.len() as i64)
.map_err(|_| crate::Error::FailedToWriteSnapshotFile)?;
}
let _ = file.file.close();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
self.file_buf.clear();
self.file_buf.shrink_to_fit();

self.values.clear();
self.unchecked_keys.clear();

self.counts.clear();
}
Ok(())
}

/// Record a test that did not run its full body (skip/todo/filtered/fail)
/// so its snapshot keys are excluded from the obsolete tally.
pub fn note_skipped_test(&mut self, file_id: FileId, test_name: Box<[u8]>) {
self.skipped_test_names.push((file_id, test_name));
}
Comment thread
robobun marked this conversation as resolved.
Resolved

/// Remove every unchecked snapshot key that belongs to `test_name` so that
/// skipped/todo/filtered tests do not cause false-positive obsolete counts.
fn mark_snapshots_as_checked_for_test(unchecked_keys: &mut StringHashMap<()>, test_name: &[u8]) {
if unchecked_keys.is_empty() {
return;
}
unchecked_keys.retain(|key, ()| {
let key: &[u8] = key.as_ref();
// Snapshot keys are `{snapshot_name} {counter}`; strip the trailing
// decimal counter before comparing (matches Jest's `keyToTestName`).
let mut end = key.len();
while end > 0 && key[end - 1].is_ascii_digit() {
end -= 1;
}
if end == key.len() || end == 0 || key[end - 1] != b' ' {
return true;
}
!strings::eql(&key[..end - 1], test_name)
});
Comment thread
robobun marked this conversation as resolved.
Resolved
}

pub fn add_inline_snapshot_to_write(
&mut self,
file_id: FileId,
Expand Down Expand Up @@ -879,10 +949,7 @@
// SAFETY: buf[pos] == 0 written above
let snapshot_file_path = ZStr::from_buf(&buf[..], pos);

let mut flags: i32 = bun_sys::O::CREAT | bun_sys::O::RDWR;
if self.update_snapshots {
flags |= bun_sys::O::TRUNC;
}
let flags: i32 = bun_sys::O::CREAT | bun_sys::O::RDWR;
let fd = match bun_sys::open(snapshot_file_path, flags, 0o644) {
bun_sys::Result::Ok(fd) => fd,
bun_sys::Result::Err(err) => return Ok(bun_sys::Result::Err(err)),
Expand All @@ -893,24 +960,32 @@
file: bun_sys::File::from_fd(fd),
};

let length = file.file.get_end_pos().map_err(Error::from)?;
if length > 0 {
let mut tmp = vec![0u8; length];
let _ = file.file.pread_all(&mut tmp, 0).map_err(Error::from)?;
#[cfg(windows)]
{
file.file.seek_to(0).map_err(Error::from)?;
}
self.file_buf.extend_from_slice(&tmp);
}

if self.update_snapshots {
self.file_buf.extend_from_slice(Self::FILE_HEADER);
// Rebuild from scratch; keep `unchecked_keys` so rewritten
// entries are not miscounted as "added" and dropped ones are
// tallied as "removed". A malformed prior file is ignored here
// since the rewrite replaces it anyway.
let _ = self.parse_file(&file);
self.file_buf.clear();
self.values.clear();
} else {
let length = file.file.get_end_pos().map_err(Error::from)?;
if length == 0 {
self.file_buf.extend_from_slice(Self::FILE_HEADER);
} else {
let mut tmp = vec![0u8; length];
let _ = file.file.pread_all(&mut tmp, 0).map_err(Error::from)?;
#[cfg(windows)]
{
file.file.seek_to(0).map_err(Error::from)?;
}
self.file_buf.extend_from_slice(&tmp);
}
self.parse_file(&file)?;
}
if self.file_buf.is_empty() {
self.file_buf.extend_from_slice(Self::FILE_HEADER);
}

self.parse_file(&file)?;
self._current_file = Some(file);
}

Expand Down
Loading
Loading