From 8718d62b1100c000543e7cd7552aaa7df11b0d67 Mon Sep 17 00:00:00 2001 From: Daniel Rainer Date: Fri, 16 Jan 2026 19:12:12 +0100 Subject: [PATCH] assertions: use `assert_eq!` where possible Using `assert_eq!` instead of `assert!` has the advantage that when the assertion fails, the debug representation of both sides will be shown, which can provide more information about the failure than only seeing that the assertion failed. Part of #12336 --- crates/color/src/lib.rs | 15 +++++-- crates/printf/src/lib.rs | 2 +- crates/printf/src/printf_impl.rs | 6 +-- crates/util/src/lib.rs | 4 +- crates/wcstringutil/src/lib.rs | 2 +- src/autoload.rs | 11 ++++-- src/builtins/argparse.rs | 4 +- src/builtins/path.rs | 2 +- src/builtins/printf.rs | 2 +- src/builtins/set.rs | 5 ++- src/builtins/shared.rs | 2 +- src/builtins/test.rs | 6 +-- src/common.rs | 2 +- src/complete.rs | 5 ++- src/editable_line.rs | 2 +- src/env/environment_impl.rs | 2 +- src/highlight/highlight.rs | 6 +-- src/input.rs | 6 +-- src/input_common.rs | 6 +-- src/kill.rs | 16 ++++---- src/parse_execution.rs | 11 +++--- src/parse_util.rs | 2 +- src/parser.rs | 65 +++++++++++++++++++------------ src/path.rs | 2 +- src/proc.rs | 2 +- src/reader/reader.rs | 6 +-- src/threads/debounce.rs | 2 +- src/tokenizer.rs | 2 +- src/topic_monitor.rs | 21 +++++----- src/universal_notifier/notifyd.rs | 2 +- src/wildcard.rs | 4 +- src/wutil/dir_iter.rs | 10 +++-- src/wutil/mod.rs | 2 +- 33 files changed, 138 insertions(+), 99 deletions(-) diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index f5e891687..2f38617f7 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -343,9 +343,18 @@ fn parse() { #[test] fn parse_rgb() { assert!(Color::from_wstr(L!("##FF00A0")).is_none()); - assert!(Color::from_wstr(L!("#FF00A0")) == Some(Color::from_rgb(0xff, 0x00, 0xa0))); - assert!(Color::from_wstr(L!("FF00A0")) == Some(Color::from_rgb(0xff, 0x00, 0xa0))); - assert!(Color::from_wstr(L!("FAF")) == Some(Color::from_rgb(0xff, 0xaa, 0xff))); + assert_eq!( + Color::from_wstr(L!("#FF00A0")), + Some(Color::from_rgb(0xff, 0x00, 0xa0)) + ); + assert_eq!( + Color::from_wstr(L!("FF00A0")), + Some(Color::from_rgb(0xff, 0x00, 0xa0)) + ); + assert_eq!( + Color::from_wstr(L!("FAF")), + Some(Color::from_rgb(0xff, 0xaa, 0xff)) + ); } // Regression test for multiplicative overflow in convert_color. diff --git a/crates/printf/src/lib.rs b/crates/printf/src/lib.rs index 14081eb4b..8ef2a243c 100644 --- a/crates/printf/src/lib.rs +++ b/crates/printf/src/lib.rs @@ -84,7 +84,7 @@ macro_rules! sprintf { /// /// let result = printf_c_locale(&mut output, fmt, &mut args); /// -/// assert!(result == Ok(10)); +/// assert_eq!(result, Ok(10)); /// assert_eq!(output, "1.2346e+05"); /// ``` pub fn printf_c_locale( diff --git a/crates/printf/src/printf_impl.rs b/crates/printf/src/printf_impl.rs index 58e2f8d79..a7f39d83a 100644 --- a/crates/printf/src/printf_impl.rs +++ b/crates/printf/src/printf_impl.rs @@ -341,7 +341,7 @@ pub(super) fn pad( /// /// let result = sprintf_locale(&mut output, fmt, &locale::EN_US_LOCALE, &mut args); /// -/// assert!(result == Ok(12)); +/// assert_eq!(result, Ok(12)); /// assert_eq!(output, "1,234,567.89"); /// ``` pub fn sprintf_locale( @@ -371,7 +371,7 @@ pub fn sprintf_locale( } // Consume the % at the start of the format specifier. - debug_assert!(s.at(0) == Some('%')); + debug_assert_eq!(s.at(0), Some('%')); s.advance_by(1); // Read modifier flags. '-' and '0' flags are mutually exclusive. @@ -561,7 +561,7 @@ pub fn sprintf_locale( }; // Numeric output should be empty iff the value is 0. if spec_is_numeric && body.is_empty() { - debug_assert!(arg.as_uint().unwrap() == 0); + debug_assert_eq!(arg.as_uint().unwrap(), 0); } // Decide if we want to apply thousands grouping to the body, and compute its size. diff --git a/crates/util/src/lib.rs b/crates/util/src/lib.rs index c8f30b14e..06b7ca191 100644 --- a/crates/util/src/lib.rs +++ b/crates/util/src/lib.rs @@ -93,7 +93,7 @@ pub fn wcsfilecmp(a: &wstr, b: &wstr) -> Ordering { Ordering::Less // string a is a prefix of b and b is longer } } else { - assert!(bi == b.len()); + assert_eq!(bi, b.len()); Ordering::Greater // string b is a prefix of a and a is longer } } @@ -158,7 +158,7 @@ pub fn wcsfilecmp_glob(a: &wstr, b: &wstr) -> Ordering { Ordering::Less // string a is a prefix of b and b is longer } } else { - assert!(bi == b.len()); + assert_eq!(bi, b.len()); Ordering::Greater // string b is a prefix of a and a is longer } } diff --git a/crates/wcstringutil/src/lib.rs b/crates/wcstringutil/src/lib.rs index af9acbacb..1ca7d8757 100644 --- a/crates/wcstringutil/src/lib.rs +++ b/crates/wcstringutil/src/lib.rs @@ -388,7 +388,7 @@ pub fn split_string_tok<'val>( pos = next_sep + 1; } if pos < end && max_results > 0 { - assert!(out.len() + 1 == max_results, "Should have split the max"); + assert_eq!(out.len() + 1, max_results, "Should have split the max"); out.push(wstr::from_char_slice(&val[pos..])); } assert!(out.len() <= max_results, "Got too many results"); diff --git a/src/autoload.rs b/src/autoload.rs index 30e614cf9..f12471733 100644 --- a/src/autoload.rs +++ b/src/autoload.rs @@ -468,7 +468,7 @@ macro_rules! run { ( $fmt:expr $(, $arg:expr )* $(,)? ) => { let cmd = wcs2zstring(&sprintf!($fmt $(, $arg)*)); let status = unsafe { libc::system(cmd.as_ptr()) }; - assert!(status == 0); + assert_eq!(status, 0); }; } @@ -514,10 +514,10 @@ fn touch_file(path: &wstr) { AutoloadResult::Pending )); assert!(autoload.autoload_in_progress(L!("file1"))); - assert!(autoload.get_autoloaded_commands() == vec![L!("file1")]); + assert_eq!(autoload.get_autoloaded_commands(), vec![L!("file1")]); autoload.mark_autoload_finished(L!("file1")); assert!(!autoload.autoload_in_progress(L!("file1"))); - assert!(autoload.get_autoloaded_commands() == vec![L!("file1")]); + assert_eq!(autoload.get_autoloaded_commands(), vec![L!("file1")]); assert!(matches!( autoload.resolve_command_impl(L!("file1"), paths), @@ -538,7 +538,10 @@ fn touch_file(path: &wstr) { autoload.resolve_command_impl(L!("file2"), paths), AutoloadResult::Loaded )); - assert!((autoload.get_autoloaded_commands() == vec![L!("file1"), L!("file2")])); + assert_eq!( + autoload.get_autoloaded_commands(), + vec![L!("file1"), L!("file2")] + ); autoload.clear(); assert!(autoload.resolve_command_impl(L!("file1"), paths).is_some()); diff --git a/src/builtins/argparse.rs b/src/builtins/argparse.rs index 367592be3..6ce7c9db4 100644 --- a/src/builtins/argparse.rs +++ b/src/builtins/argparse.rs @@ -39,7 +39,7 @@ fn new(s: char) -> Self { } } -#[derive(Default, PartialEq)] +#[derive(Debug, Default, PartialEq)] enum UnknownHandling { #[default] Error, @@ -1051,7 +1051,7 @@ fn argparse_parse_flags<'args>( opts.args.push(Cow::Borrowed(value)); } } else { - assert!(opts.unknown_handling == UnknownHandling::Move); + assert_eq!(opts.unknown_handling, UnknownHandling::Move); // w.argv_opts will already contain the option and its value, unless the // value was given as a seperate argument if let Some(value) = separate_value { diff --git a/src/builtins/path.rs b/src/builtins/path.rs index 3a9f1fc52..94ebd3399 100644 --- a/src/builtins/path.rs +++ b/src/builtins/path.rs @@ -368,7 +368,7 @@ fn parse_opts<'args>( *optind = w.wopt_index; if n_req_args != 0 { - assert!(n_req_args == 1); + assert_eq!(n_req_args, 1); opts.arg1 = args.get(*optind).copied(); if opts.arg1.is_some() { *optind += 1; diff --git a/src/builtins/printf.rs b/src/builtins/printf.rs index fd14bf2da..2bb06e08e 100644 --- a/src/builtins/printf.rs +++ b/src/builtins/printf.rs @@ -615,7 +615,7 @@ fn fatal_error>(&mut self, errstr: Str) { /// If octal_0 is nonzero, octal escapes are of the form \0ooo, where o /// is an octal digit; otherwise they are of the form \ooo. fn print_esc(&mut self, escstart: &wstr, octal_0: bool) -> usize { - assert!(escstart.char_at(0) == '\\'); + assert_eq!(escstart.char_at(0), '\\'); let mut p = &escstart[1..]; let mut esc_value = 0; /* Value of \nnn escape. */ let mut esc_length; /* Length of \nnn escape. */ diff --git a/src/builtins/set.rs b/src/builtins/set.rs index 8cb3b375d..66531b383 100644 --- a/src/builtins/set.rs +++ b/src/builtins/set.rs @@ -907,8 +907,9 @@ fn new_var_values( /// This handles the more difficult case of setting individual slices of a var. fn new_var_values_by_index(split: &SplitVar, argv: &[&wstr]) -> Vec { - assert!( - argv.len() == split.indexes.len(), + assert_eq!( + argv.len(), + split.indexes.len(), "Must have the same number of indexes as arguments" ); diff --git a/src/builtins/shared.rs b/src/builtins/shared.rs index 81ab5609a..009caf809 100644 --- a/src/builtins/shared.rs +++ b/src/builtins/shared.rs @@ -909,7 +909,7 @@ fn get_arg_stdin(&mut self) -> Option> { return None; } - // assert!(num_bytes == self.buffer.len()); + // assert_eq!(num_bytes, self.buffer.len()); let (end, want_newline) = match (&self.split_behavior, buffer.last()) { // remove the newline — consumers do not expect it (Newline, Some(b'\n')) => (num_bytes - 1, true), diff --git a/src/builtins/test.rs b/src/builtins/test.rs index 8b3c8b959..e06608539 100644 --- a/src/builtins/test.rs +++ b/src/builtins/test.rs @@ -367,7 +367,7 @@ impl Expression for CombiningExpression { fn evaluate(&self, streams: &mut IoStreams, errors: &mut Vec) -> bool { let _res = self.subjects[0].evaluate(streams, errors); assert!(!self.subjects.is_empty()); - assert!(self.combiners.len() + 1 == self.subjects.len()); + assert_eq!(self.combiners.len() + 1, self.subjects.len()); // One-element case. if self.subjects.len() == 1 { @@ -651,7 +651,7 @@ fn parse_3_arg_expression( start: usize, end: usize, ) -> Option> { - assert!(end - start == 3); + assert_eq!(end - start, 3); let center_token = token_for_string(self.arg(start + 1)); @@ -677,7 +677,7 @@ fn parse_4_arg_expression( start: usize, end: usize, ) -> Option> { - assert!(end - start == 4); + assert_eq!(end - start, 4); let first_token = token_for_string(self.arg(start)); diff --git a/src/common.rs b/src/common.rs index 574657c36..ea7b138d2 100644 --- a/src/common.rs +++ b/src/common.rs @@ -710,7 +710,7 @@ pub fn read_unquoted_escape( allow_incomplete: bool, unescape_special: bool, ) -> Option { - assert!(input.char_at(0) == '\\', "not an escape"); + assert_eq!(input.char_at(0), '\\', "not an escape"); // Here's the character we'll ultimately append, or none. Note that '\0' is a // valid thing to append. diff --git a/src/complete.rs b/src/complete.rs index e09faaec3..7113ff8ff 100644 --- a/src/complete.rs +++ b/src/complete.rs @@ -2301,7 +2301,10 @@ pub fn complete_add( flags: CompleteFlags, ) { // option should be empty iff the option type is arguments only. - assert!(option.is_empty() == (option_type == CompleteOptionType::ArgsOnly)); + assert_eq!( + option.is_empty(), + (option_type == CompleteOptionType::ArgsOnly) + ); // Lock the lock that allows us to edit the completion entry list. let mut completion_map = COMPLETION_MAP.lock().expect("mutex poisoned"); diff --git a/src/editable_line.rs b/src/editable_line.rs index 43e9c9958..503a14698 100644 --- a/src/editable_line.rs +++ b/src/editable_line.rs @@ -154,7 +154,7 @@ pub fn push_edit(&mut self, mut edit: Edit, allow_coalesce: bool) { let is_insertion = range.is_empty(); // Coalescing insertion does not create a new undo entry but adds to the last insertion. if allow_coalesce && is_insertion && self.want_to_coalesce_insertion_of(&edit.replacement) { - assert!(range.start == self.position()); + assert_eq!(range.start, self.position()); let last_edit = self.undo_history.edits.last_mut().unwrap(); last_edit.replacement.push_utfstr(&edit.replacement); apply_edit(&mut self.text, &mut self.colors, &edit); diff --git a/src/env/environment_impl.rs b/src/env/environment_impl.rs index de21cff07..36882463d 100644 --- a/src/env/environment_impl.rs +++ b/src/env/environment_impl.rs @@ -975,7 +975,7 @@ fn try_set_electric( if key == "umask" { return Some(set_umask(val)); } else if key == "PWD" { - assert!(val.len() == 1, "Should have exactly one element in PWD"); + assert_eq!(val.len(), 1, "Should have exactly one element in PWD"); let pwd = val.pop().unwrap(); if pwd != self.base.perproc_data.pwd { self.base.perproc_data.pwd = pwd; diff --git a/src/highlight/highlight.rs b/src/highlight/highlight.rs index 75ea8d715..95002cefa 100644 --- a/src/highlight/highlight.rs +++ b/src/highlight/highlight.rs @@ -62,7 +62,7 @@ pub fn with_both(role: HighlightRole) -> Self { /// Given a string and list of colors of the same size, return the string with ANSI escape sequences /// representing the colors. pub fn colorize(text: &wstr, colors: &[HighlightSpec], vars: &dyn Environment) -> Vec { - assert!(colors.len() == text.len()); + assert_eq!(colors.len(), text.len()); let mut rv = HighlightColorResolver::new(); let mut outp = Outputter::new_buffering(); @@ -394,7 +394,7 @@ pub fn autosuggest_validate_from_history( // Highlights the variable starting with 'in', setting colors within the 'colors' array. Returns the // number of characters consumed. fn color_variable(inp: &wstr, colors: &mut [HighlightSpec]) -> usize { - assert!(inp.char_at(0) == '$'); + assert_eq!(inp.char_at(0), '$'); // Handle an initial run of $s. let mut idx = 0; @@ -854,7 +854,7 @@ fn color_as_argument(&mut self, node: &dyn ast::Node, options_allowed: bool /* = let subcolors = cmdsub_highlighter.highlight(); // Copy out the subcolors back into our array. - assert!(subcolors.len() == cmdsub_contents.len()); + assert_eq!(subcolors.len(), cmdsub_contents.len()); self.color_array[arg_start..][parens.command()].copy_from_slice(&subcolors); } } diff --git a/src/input.rs b/src/input.rs index ea3e574b1..84f1221e2 100644 --- a/src/input.rs +++ b/src/input.rs @@ -422,7 +422,7 @@ pub fn new(event_queue: &'q mut Queuer) -> Self { /// Return the next event. fn next(&mut self) -> CharEvent { - assert!(self.subidx == 0); + assert_eq!(self.subidx, 0); assert!( self.idx <= self.peeked.len(), "Index must not be larger than dequeued event count" @@ -491,7 +491,7 @@ fn next_is_char( if *style == KeyNameStyle::Plain { let result = match_key_event_to_key(&kevt.key, &key); if let Some(key_match) = &result { - assert!(self.subidx == 0); + assert_eq!(self.subidx, 0); self.idx += 1; flog!(reader, "matched full key", key, "kind", key_match); } @@ -1047,7 +1047,7 @@ fn test_input() { let mut peeker = EventQueuePeeker::new(&mut input); let mapping = peeker.find_mapping(&vars, &input_mappings); assert!(mapping.is_some()); - assert!(mapping.unwrap().commands == ["down-line"]); + assert_eq!(mapping.unwrap().commands, ["down-line"]); peeker.restart(); } } diff --git a/src/input_common.rs b/src/input_common.rs index dc6ba80a5..584f5716e 100644 --- a/src/input_common.rs +++ b/src/input_common.rs @@ -1404,7 +1404,7 @@ fn parse_xtversion(&mut self, buffer: &mut Vec) -> Option<()> { fn parse_osc(&mut self, buffer: &mut Vec) -> Option<()> { let osc_prefix = b"\x1b]"; - assert!(buffer == osc_prefix); + assert_eq!(buffer, osc_prefix); self.read_until_sequence_terminator(buffer, /*allow_bel=*/ true)?; let buffer = &buffer[osc_prefix.len()..]; let buffer = buffer.strip_prefix(b"11;")?; @@ -1415,7 +1415,7 @@ fn parse_osc(&mut self, buffer: &mut Vec) -> Option<()> { } fn parse_dcs(&mut self, buffer: &mut Vec) -> Option { - assert!(buffer == b"\x1bP"); + assert_eq!(buffer, b"\x1bP"); let Some(success) = self.read_sequence_byte(buffer) else { return Some(KeyEvent::from(alt('P'))); }; @@ -1783,7 +1783,7 @@ fn parse_hex(hex: &[u8]) -> Option> { Some(result) } fn parse_hex_into(out: &mut [u8], hex: &[u8]) -> Option<()> { - assert!(out.len() * 2 == hex.len()); + assert_eq!(out.len() * 2, hex.len()); let mut i = 0; while i < hex.len() { let d1 = char::from(hex[i]).to_digit(16)?; diff --git a/src/kill.rs b/src/kill.rs index a888a4dd9..b15b1f1ce 100644 --- a/src/kill.rs +++ b/src/kill.rs @@ -97,19 +97,19 @@ fn test_killring() { kr.add(WString::from_str("b")); kr.add(WString::from_str("c")); - assert!(kr.entries() == [L!("c"), L!("b"), L!("a")]); + assert_eq!(kr.entries(), [L!("c"), L!("b"), L!("a")]); - assert!(kr.yank_rotate() == "b"); - assert!(kr.entries() == [L!("b"), L!("a"), L!("c")]); + assert_eq!(kr.yank_rotate(), "b"); + assert_eq!(kr.entries(), [L!("b"), L!("a"), L!("c")]); - assert!(kr.yank_rotate() == "a"); - assert!(kr.entries() == [L!("a"), L!("c"), L!("b")]); + assert_eq!(kr.yank_rotate(), "a"); + assert_eq!(kr.entries(), [L!("a"), L!("c"), L!("b")]); kr.add(WString::from_str("d")); - assert!((kr.entries() == [L!("d"), L!("a"), L!("c"), L!("b")])); + assert_eq!(kr.entries(), [L!("d"), L!("a"), L!("c"), L!("b")]); - assert!(kr.yank_rotate() == "a"); - assert!((kr.entries() == [L!("a"), L!("c"), L!("b"), L!("d")])); + assert_eq!(kr.yank_rotate(), "a"); + assert_eq!(kr.entries(), [L!("a"), L!("c"), L!("b"), L!("d")]); } } diff --git a/src/parse_execution.rs b/src/parse_execution.rs index 415012363..f76fbc565 100644 --- a/src/parse_execution.rs +++ b/src/parse_execution.rs @@ -62,7 +62,7 @@ /// An eval_result represents evaluation errors including wildcards which failed to match, syntax /// errors, or other expansion errors. It also tracks when evaluation was skipped due to signal /// cancellation. Note it does not track the exit status of commands. -#[derive(Eq, PartialEq)] +#[derive(Debug, Eq, PartialEq)] pub enum EndExecutionReason { /// Evaluation was successful. Ok, @@ -937,7 +937,7 @@ fn run_for_statement( ParserEnvSetMode::user(EnvMode::LOCAL), var.map_or(vec![], |var| var.as_list().to_owned()), ); - assert!(retval == EnvStackSetResult::Ok); + assert_eq!(retval, EnvStackSetResult::Ok); trace_if_enabled_with_args(ctx.parser(), L!("for"), &arguments); @@ -957,8 +957,9 @@ fn run_for_statement( ParserEnvSetMode::user(EnvMode::empty()), vec![val], ); - assert!( - retval == EnvStackSetResult::Ok, + assert_eq!( + retval, + EnvStackSetResult::Ok, "for loop variable should have been successfully set" ); event::fire(ctx.parser(), evt.clone()); @@ -1171,7 +1172,7 @@ fn run_switch_statement( if let Some(case_item) = matching_case_item { // Success, evaluate the job list. - assert!(result == EndExecutionReason::Ok, "Expected success"); + assert_eq!(result, EndExecutionReason::Ok, "Expected success"); result = self.run_job_list(ctx, &case_item.body, Some(sb)); } diff --git a/src/parse_util.rs b/src/parse_util.rs index 630a1c17a..fb099cefa 100644 --- a/src/parse_util.rs +++ b/src/parse_util.rs @@ -1948,7 +1948,7 @@ pub fn parse_util_expand_variable_error( } // We should have appended exactly one error. - assert!(errors.as_ref().unwrap().len() == start_error_count + 1); + assert_eq!(errors.as_ref().unwrap().len(), start_error_count + 1); } localizable_consts!( diff --git a/src/parser.rs b/src/parser.rs index 06f98beec..a26f40a0c 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1035,7 +1035,7 @@ pub fn push_block(&self, mut block: Block) -> BlockId { pub fn pop_block(&self, expected: BlockId) { let block = { let mut block_list = self.block_list.borrow_mut(); - assert!(expected.0 == block_list.len() - 1); + assert_eq!(expected.0, block_list.len() - 1); block_list.pop().unwrap() }; if block.wants_pop_env() { @@ -1628,28 +1628,33 @@ fn detect_argument_errors(src: &str) -> Result<(), ParserTestErrorBits> { "redirection after 'end' wrongly reported as error" ); - assert!( - detect_errors!("true | ") == Err(ParserTestErrorBits::INCOMPLETE), + assert_eq!( + detect_errors!("true | "), + Err(ParserTestErrorBits::INCOMPLETE), "unterminated pipe not reported properly" ); - assert!( - detect_errors!("echo (\nfoo\n bar") == Err(ParserTestErrorBits::INCOMPLETE), + assert_eq!( + detect_errors!("echo (\nfoo\n bar"), + Err(ParserTestErrorBits::INCOMPLETE), "unterminated multiline subshell not reported properly" ); - assert!( - detect_errors!("begin ; true ; end | ") == Err(ParserTestErrorBits::INCOMPLETE), + assert_eq!( + detect_errors!("begin ; true ; end | "), + Err(ParserTestErrorBits::INCOMPLETE), "unterminated pipe not reported properly" ); - assert!( - detect_errors!(" | true ") == Err(ParserTestErrorBits::ERROR), + assert_eq!( + detect_errors!(" | true "), + Err(ParserTestErrorBits::ERROR), "leading pipe not reported properly" ); - assert!( - detect_errors!("true | # comment") == Err(ParserTestErrorBits::INCOMPLETE), + assert_eq!( + detect_errors!("true | # comment"), + Err(ParserTestErrorBits::INCOMPLETE), "comment after pipe not reported as incomplete" ); @@ -1658,8 +1663,9 @@ fn detect_argument_errors(src: &str) -> Result<(), ParserTestErrorBits> { "comment and newline after pipe wrongly reported as error" ); - assert!( - detect_errors!("true | ; false ") == Err(ParserTestErrorBits::ERROR), + assert_eq!( + detect_errors!("true | ; false "), + Err(ParserTestErrorBits::ERROR), "semicolon after pipe not detected as error" ); @@ -1766,8 +1772,9 @@ fn detect_argument_errors(src: &str) -> Result<(), ParserTestErrorBits> { "bogus boolean statement error not detected" ); - assert!( - detect_errors!("true && ") == Err(ParserTestErrorBits::INCOMPLETE), + assert_eq!( + detect_errors!("true && "), + Err(ParserTestErrorBits::INCOMPLETE), "unterminated conjunction not reported properly" ); @@ -1776,13 +1783,15 @@ fn detect_argument_errors(src: &str) -> Result<(), ParserTestErrorBits> { "newline after && reported as error" ); - assert!( - detect_errors!("true || \n") == Err(ParserTestErrorBits::INCOMPLETE), + assert_eq!( + detect_errors!("true || \n"), + Err(ParserTestErrorBits::INCOMPLETE), "unterminated conjunction not reported properly" ); - assert!( - detect_errors!("begin ; echo hi; }") == Err(ParserTestErrorBits::ERROR), + assert_eq!( + detect_errors!("begin ; echo hi; }"), + Err(ParserTestErrorBits::ERROR), "closing of unopened brace statement not reported properly" ); @@ -2054,8 +2063,11 @@ fn test_new_parser_ad_hoc() { ParseTreeFlags::LEAVE_UNTERMINATED, Some(&mut errors), ); - assert!(errors.len() == 1); - assert!(errors[0].code == ParseErrorCode::TokenizerUnterminatedSubshell); + assert_eq!(errors.len(), 1); + assert_eq!( + errors[0].code, + ParseErrorCode::TokenizerUnterminatedSubshell + ); errors.clear(); ast::parse( @@ -2063,8 +2075,11 @@ fn test_new_parser_ad_hoc() { ParseTreeFlags::LEAVE_UNTERMINATED, Some(&mut errors), ); - assert!(errors.len() == 1); - assert!(errors[0].code == ParseErrorCode::TokenizerUnterminatedSubshell); + assert_eq!(errors.len(), 1); + assert_eq!( + errors[0].code, + ParseErrorCode::TokenizerUnterminatedSubshell + ); errors.clear(); ast::parse( @@ -2072,8 +2087,8 @@ fn test_new_parser_ad_hoc() { ParseTreeFlags::LEAVE_UNTERMINATED, Some(&mut errors), ); - assert!(errors.len() == 1); - assert!(errors[0].code == ParseErrorCode::TokenizerUnterminatedQuote); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].code, ParseErrorCode::TokenizerUnterminatedQuote); } #[test] diff --git a/src/path.rs b/src/path.rs index cfe6f9f38..45bf5a7e7 100644 --- a/src/path.rs +++ b/src/path.rs @@ -340,7 +340,7 @@ pub fn path_get_cdpath(dir: &wstr, wd: &wstr, vars: &dyn Environment) -> Option< if dir.is_empty() { return None; } - assert!(wd.chars().next_back() == Some('/')); + assert_eq!(wd.chars().next_back(), Some('/')); let paths = path_apply_cdpath(dir, wd, vars); for a_dir in paths { diff --git a/src/proc.rs b/src/proc.rs index a7ae0c529..5bac6195a 100644 --- a/src/proc.rs +++ b/src/proc.rs @@ -1237,7 +1237,7 @@ fn process_mark_finished_children(parser: &Parser, block_ok: bool, block_io: Opt continue; } let pid = Pid::new(pid); - assert!(pid == proc.pid().unwrap(), "Unexpected waitpid() return"); + assert_eq!(pid, proc.pid().unwrap(), "Unexpected waitpid() return"); // The process has stopped or exited! Update its status. let status = ProcStatus::from_waitpid(statusv); diff --git a/src/reader/reader.rs b/src/reader/reader.rs index 24d7607e6..4be0157fe 100644 --- a/src/reader/reader.rs +++ b/src/reader/reader.rs @@ -640,7 +640,7 @@ struct LayoutData { right_prompt_buff: WString, } -#[derive(Clone, Copy, Eq, PartialEq)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] enum EditableLineTag { Commandline, SearchField, @@ -1775,7 +1775,7 @@ fn make_layout_data(&self) -> LayoutData { let focused_on_pager = self.active_edit_line_tag() == EditableLineTag::SearchField; result.text = self.command_line.text().to_owned(); result.colors = self.command_line.colors().to_vec(); - assert!(result.text.len() == result.colors.len()); + assert_eq!(result.text.len(), result.colors.len()); result.position = self.command_line.position(); result.pager_search_field_position = focused_on_pager.then(|| self.pager.cursor_position()); result.selection = self.selection; @@ -4376,7 +4376,7 @@ fn forward_token(&self, autosuggest: bool) -> Option { let (elt, el) = self.active_edit_line(); let pos = el.position(); let buffer = if autosuggest { - assert!(elt == EditableLineTag::Commandline); + assert_eq!(elt, EditableLineTag::Commandline); assert!(self.is_at_line_with_autosuggestion()); let autosuggestion = &self.autosuggestion; Cow::Owned(combine_command_and_autosuggestion( diff --git a/src/threads/debounce.rs b/src/threads/debounce.rs index 9e9d575f3..905e8eeb4 100644 --- a/src/threads/debounce.rs +++ b/src/threads/debounce.rs @@ -291,7 +291,7 @@ struct Data { // Wait 75 msec, then enqueue something else; this should spawn a new thread. std::thread::sleep(timeout + timeout / 2); - assert!(data.running.load(Ordering::Relaxed) == 1); + assert_eq!(data.running.load(Ordering::Relaxed), 1); let token3 = data.db.perform_void(handler); assert!(token3 > token2); diff --git a/src/tokenizer.rs b/src/tokenizer.rs index b4990a5d8..09139f036 100644 --- a/src/tokenizer.rs +++ b/src/tokenizer.rs @@ -997,7 +997,7 @@ fn try_from(buff: &wstr) -> Result { // Like try_consume, but asserts on failure. let consume = |cursor: &mut usize, c| { - assert!(buff.char_at(*cursor) == c, "Failed to consume char"); + assert_eq!(buff.char_at(*cursor), c, "Failed to consume char"); *cursor += 1; }; diff --git a/src/topic_monitor.rs b/src/topic_monitor.rs index 5d4251a1e..d88818773 100644 --- a/src/topic_monitor.rs +++ b/src/topic_monitor.rs @@ -44,7 +44,7 @@ pub enum Topic { } // XXX: Is it correct to use the default or should the default be invalid_generation? -#[derive(Clone, Default, PartialEq, PartialOrd, Eq, Ord)] +#[derive(Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)] pub struct GenerationsList { pub sighupint: Cell, pub sigchld: Cell, @@ -379,8 +379,9 @@ pub fn post(&self, topic: Topic) { .is_ok(); } // Note that if the STATUS_NEEDS_WAKEUP bit is set, no other bits must be set. - assert!( - (oldstatus == STATUS_NEEDS_WAKEUP) == ((oldstatus & STATUS_NEEDS_WAKEUP) != 0), + assert_eq!( + (oldstatus == STATUS_NEEDS_WAKEUP), + ((oldstatus & STATUS_NEEDS_WAKEUP) != 0), "If STATUS_NEEDS_WAKEUP is set no other bits should be set" ); @@ -418,8 +419,9 @@ fn updated_gens_in_data(&self, data: &mut MutexGuard) -> GenerationsList .compare_exchange_weak(changed_topic_bits, 0, relaxed, relaxed) .is_ok(); } - assert!( - (changed_topic_bits & STATUS_NEEDS_WAKEUP) == 0, + assert_eq!( + changed_topic_bits & STATUS_NEEDS_WAKEUP, + 0, "Thread waiting bit should not be set" ); @@ -487,8 +489,9 @@ fn try_update_gens_maybe_becoming_reader(&self, gens: &mut GenerationsList) -> b } else { // We will try to become the reader. // Reader bit should not be set in this case. - assert!( - (self.status_.load(Ordering::Relaxed) & STATUS_NEEDS_WAKEUP) == 0, + assert_eq!( + self.status_.load(Ordering::Relaxed) & STATUS_NEEDS_WAKEUP, + 0, "No thread should be waiting" ); // Try becoming the reader by marking the reader bit. @@ -527,8 +530,8 @@ fn await_gens(&self, input_gens: &GenerationsList) -> GenerationsList { if become_reader { // Now we are the reader. Read from the pipe, and then update with any changes. // Note we no longer hold the lock. - assert!( - gens == *input_gens, + assert_eq!( + gens, *input_gens, "Generations should not have changed if we are the reader." ); diff --git a/src/universal_notifier/notifyd.rs b/src/universal_notifier/notifyd.rs index 03d88b6eb..57295807e 100644 --- a/src/universal_notifier/notifyd.rs +++ b/src/universal_notifier/notifyd.rs @@ -110,7 +110,7 @@ fn notification_fd(&self) -> Option { fn notification_fd_became_readable(&self, fd: RawFd) -> bool { // notifyd notifications come in as 32 bit values. We don't care about the value. We set // ourselves as non-blocking, so just read until we can't read any more. - assert!(fd == self.notify_fd); + assert_eq!(fd, self.notify_fd); let mut read_something = false; let mut buff: [u8; 64] = [0; 64]; loop { diff --git a/src/wildcard.rs b/src/wildcard.rs index 9f763ae89..c0d215e68 100644 --- a/src/wildcard.rs +++ b/src/wildcard.rs @@ -648,8 +648,8 @@ pub fn expand( // ANY_STRING_RECURSIVE character is present in both the head and the tail. let head_any = wc_segment.slice_to(asr_idx + 1); let any_tail = wc.slice_from(asr_idx); - assert!(head_any.chars().next_back().unwrap() == ANY_STRING_RECURSIVE); - assert!(any_tail.chars().next().unwrap() == ANY_STRING_RECURSIVE); + assert_eq!(head_any.chars().next_back().unwrap(), ANY_STRING_RECURSIVE); + assert_eq!(any_tail.chars().next().unwrap(), ANY_STRING_RECURSIVE); dir.rewind(); self.expand_intermediate_segment( diff --git a/src/wutil/dir_iter.rs b/src/wutil/dir_iter.rs index 8ef826707..79c69907b 100644 --- a/src/wutil/dir_iter.rs +++ b/src/wutil/dir_iter.rs @@ -269,7 +269,10 @@ pub fn next(&mut self) -> Option> { }; // dent.d_name is c_char; pretend it's u8. - assert!(std::mem::size_of::() == std::mem::size_of::()); + assert_eq!( + std::mem::size_of::(), + std::mem::size_of::() + ); // Do not rely on `libc::dirent::d_name.len()` as dirent names may exceed // the nominal buffer size; instead use the terminating nul byte. @@ -463,8 +466,9 @@ fn test_dir_iter() { } // If we have a fast type, it should be correct. assert!(entry.fast_type().is_none() || entry.fast_type() == expected); - assert!( - entry.check_type() == expected, + assert_eq!( + entry.check_type(), + expected, "Wrong type for {}. Expected {:?}, got {:?}", entry.name, expected, diff --git a/src/wutil/mod.rs b/src/wutil/mod.rs index 760c50fa8..ab5192675 100644 --- a/src/wutil/mod.rs +++ b/src/wutil/mod.rs @@ -685,7 +685,7 @@ fn test_wwrite_to_fd() { input.len(), ) }; - assert!(usize::try_from(read_amt).unwrap() == input.len()); + assert_eq!(usize::try_from(read_amt).unwrap(), input.len()); assert_eq!(&contents, &input); } }