nextest_runner/reporter/displayer/
progress.rs

1// Copyright (c) The nextest Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use crate::{
5    cargo_config::{CargoConfigs, DiscoveredConfig},
6    helpers::{DisplayTestInstance, plural},
7    list::TestInstanceId,
8    reporter::{
9        displayer::formatters::DisplayBracketedHhMmSs,
10        events::*,
11        helpers::{Styles, print_lines_in_chunks},
12    },
13    run_mode::NextestRunMode,
14};
15use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
16use nextest_metadata::{RustBinaryId, TestCaseName};
17use owo_colors::OwoColorize;
18use std::{
19    cmp::{max, min},
20    env, fmt,
21    str::FromStr,
22    time::{Duration, Instant},
23};
24use swrite::{SWrite, swrite};
25use tracing::debug;
26
27/// The refresh rate for the progress bar, set to a minimal value.
28///
29/// For progress, during each tick, two things happen:
30///
31/// - We update the message, calling self.bar.set_message.
32/// - We print any buffered output.
33///
34/// We want both of these updates to be combined into one terminal flush, so we
35/// set *this* to a minimal value (so self.bar.set_message doesn't do a redraw),
36/// and rely on ProgressBar::print_and_flush_buffer to always flush the
37/// terminal.
38const PROGRESS_REFRESH_RATE_HZ: u8 = 1;
39
40/// The maximum number of running tests to display with
41/// `--show-progress=running` or `only`.
42#[derive(Clone, Copy, Debug, Eq, PartialEq)]
43pub enum MaxProgressRunning {
44    /// Show a specific maximum number of running tests.
45    /// If 0, running tests (including the overflow summary) aren't displayed.
46    Count(usize),
47
48    /// Show all running tests (no limit).
49    Infinite,
50}
51
52impl MaxProgressRunning {
53    /// The default value (8 tests).
54    pub const DEFAULT_VALUE: Self = Self::Count(8);
55}
56
57impl Default for MaxProgressRunning {
58    fn default() -> Self {
59        Self::DEFAULT_VALUE
60    }
61}
62
63impl FromStr for MaxProgressRunning {
64    type Err = String;
65
66    fn from_str(s: &str) -> Result<Self, Self::Err> {
67        if s.eq_ignore_ascii_case("infinite") {
68            return Ok(Self::Infinite);
69        }
70
71        match s.parse::<usize>() {
72            Err(e) => Err(format!("Error: {e} parsing {s}")),
73            Ok(n) => Ok(Self::Count(n)),
74        }
75    }
76}
77
78impl fmt::Display for MaxProgressRunning {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        match self {
81            Self::Infinite => write!(f, "infinite"),
82            Self::Count(n) => write!(f, "{n}"),
83        }
84    }
85}
86
87/// How to show progress.
88///
89/// In the `Auto` variant, the progress display is chosen based on the
90/// environment: a progress bar in interactive terminals, a counter otherwise.
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92pub enum ShowProgress {
93    /// Automatically decide based on environment.
94    ///
95    /// When `suppress_success` is true and a progress bar is shown,
96    /// successful test output is suppressed (status level defaults to
97    /// `Slow`, final status level defaults to `None`). In non-interactive
98    /// contexts, output behaves identically to `suppress_success: false`:
99    /// all test results are displayed normally.
100    Auto {
101        /// Whether to hide successful test output when a progress bar is
102        /// shown.
103        suppress_success: bool,
104    },
105
106    /// No progress display.
107    None,
108
109    /// Show a counter on each line.
110    Counter,
111
112    /// Show a progress bar and the running tests.
113    Running,
114}
115
116impl Default for ShowProgress {
117    fn default() -> Self {
118        ShowProgress::Auto {
119            suppress_success: false,
120        }
121    }
122}
123
124#[derive(Debug)]
125pub(super) enum RunningTestStatus {
126    Running,
127    Slow,
128    Delay(Duration),
129    Retry,
130}
131
132#[derive(Debug)]
133pub(super) struct RunningTest {
134    binary_id: RustBinaryId,
135    test_name: TestCaseName,
136    status: RunningTestStatus,
137    start_time: Instant,
138    paused_for: Duration,
139}
140
141impl RunningTest {
142    fn message(&self, now: Instant, width: usize, styles: &Styles) -> String {
143        let mut elapsed = (now - self.start_time).saturating_sub(self.paused_for);
144        let status = match self.status {
145            RunningTestStatus::Running => "     ".to_owned(),
146            RunningTestStatus::Slow => " SLOW".style(styles.skip).to_string(),
147            RunningTestStatus::Delay(d) => {
148                // The elapsed might be greater than the delay duration in case
149                // we ticked past the delay duration without receiving a
150                // notification that the test retry started.
151                elapsed = d.saturating_sub(elapsed);
152                "DELAY".style(styles.retry).to_string()
153            }
154            RunningTestStatus::Retry => "RETRY".style(styles.retry).to_string(),
155        };
156        let elapsed = format!(
157            "{:0>2}:{:0>2}:{:0>2}",
158            elapsed.as_secs() / 3600,
159            elapsed.as_secs() / 60,
160            elapsed.as_secs() % 60,
161        );
162        let max_width = width.saturating_sub(25);
163        let test = DisplayTestInstance::new(
164            None,
165            None,
166            TestInstanceId {
167                binary_id: &self.binary_id,
168
169                test_name: &self.test_name,
170            },
171            &styles.list_styles,
172        )
173        .with_max_width(max_width);
174        format!("       {} [{:>9}] {}", status, elapsed, test)
175    }
176}
177
178#[derive(Debug)]
179pub(super) struct ProgressBarState {
180    bar: ProgressBar,
181    mode: NextestRunMode,
182    stats: RunStats,
183    running: usize,
184    max_progress_running: MaxProgressRunning,
185    // Keep track of the maximum number of lines used. This allows to adapt the
186    // size of the 'viewport' to what we are using, and not just to the maximum
187    // number of tests that can be run in parallel
188    max_running_displayed: usize,
189    // None when the running tests are not displayed
190    running_tests: Option<Vec<RunningTest>>,
191    buffer: String,
192    // Size in bytes for chunking println calls. Configurable via the
193    // undocumented __NEXTEST_PROGRESS_PRINTLN_CHUNK_SIZE env var.
194    println_chunk_size: usize,
195    // Reasons for hiding the progress bar. We show the progress bar if none of
196    // these are set and hide it if any of them are set.
197    //
198    // indicatif cannot handle this kind of "stacked" state management, so it
199    // falls on us to do so.
200    //
201    // The current draw target is a pure function of these three booleans: if
202    // any of them are set, the draw target is hidden, otherwise it's stderr. If
203    // this changes, we'll need to track those other inputs.
204    hidden_no_capture: bool,
205    hidden_run_paused: bool,
206    hidden_info_response: bool,
207}
208
209impl ProgressBarState {
210    pub(super) fn new(
211        mode: NextestRunMode,
212        run_count: usize,
213        progress_chars: &str,
214        max_progress_running: MaxProgressRunning,
215    ) -> Self {
216        let bar = ProgressBar::new(run_count as u64);
217        let run_count_width = format!("{run_count}").len();
218        // Create the template using the width as input. This is a
219        // little confusing -- {{foo}} is what's passed into the
220        // ProgressBar, while {bar} is inserted by the format!()
221        // statement.
222        let template = format!(
223            "{{prefix:>12}} [{{elapsed_precise:>9}}] {{wide_bar}} \
224            {{pos:>{run_count_width}}}/{{len:{run_count_width}}}: {{msg}}"
225        );
226        bar.set_style(
227            ProgressStyle::default_bar()
228                .progress_chars(progress_chars)
229                .template(&template)
230                .expect("template is known to be valid"),
231        );
232
233        let running_tests =
234            (!matches!(max_progress_running, MaxProgressRunning::Count(0))).then(Vec::new);
235
236        // The println chunk size defaults to a value chosen by experimentation,
237        // locally and over SSH. This controls how often the progress bar
238        // refreshes during large output bursts.
239        let println_chunk_size = env::var("__NEXTEST_PROGRESS_PRINTLN_CHUNK_SIZE")
240            .ok()
241            .and_then(|s| s.parse::<usize>().ok())
242            .unwrap_or(4096);
243
244        Self {
245            bar,
246            mode,
247            stats: RunStats::default(),
248            running: 0,
249            max_progress_running,
250            max_running_displayed: 0,
251            running_tests,
252            buffer: String::new(),
253            println_chunk_size,
254            hidden_no_capture: false,
255            hidden_run_paused: false,
256            hidden_info_response: false,
257        }
258    }
259
260    pub(super) fn tick(&mut self, styles: &Styles) {
261        self.update_message(styles);
262        self.print_and_clear_buffer();
263    }
264
265    fn print_and_clear_buffer(&mut self) {
266        self.print_and_force_redraw();
267        self.buffer.clear();
268    }
269
270    /// Prints the contents of the buffer, and always forces a redraw.
271    fn print_and_force_redraw(&self) {
272        if self.buffer.is_empty() {
273            // Force a redraw as part of our contract. See the documentation for
274            // `PROGRESS_REFRESH_RATE_HZ`.
275            self.bar.force_draw();
276            return;
277        }
278
279        // println below also forces a redraw, so we don't need to call
280        // force_draw in this case.
281
282        // ProgressBar::println is only called if there's something in the
283        // buffer, for two reasons:
284        //
285        // 1. If passed in nothing at all, it prints an empty line.
286        // 2. It forces a full redraw.
287        //
288        // But if self.buffer is too large, we can overwhelm the terminal with
289        // large amounts of non-progress-bar output, causing the progress bar to
290        // flicker in and out. To avoid those issues, we chunk the output to
291        // maintain progress bar visibility by redrawing it regularly.
292        print_lines_in_chunks(&self.buffer, self.println_chunk_size, |chunk| {
293            self.bar.println(chunk);
294        });
295    }
296
297    fn update_message(&mut self, styles: &Styles) {
298        let mut msg = self.progress_bar_msg(styles);
299        msg += "     ";
300
301        if let Some(running_tests) = &self.running_tests {
302            let (_, width) = console::Term::stderr().size();
303            let width = max(width as usize, 40);
304            let now = Instant::now();
305            let mut count = match self.max_progress_running {
306                MaxProgressRunning::Count(count) => min(running_tests.len(), count),
307                MaxProgressRunning::Infinite => running_tests.len(),
308            };
309            for running_test in &running_tests[..count] {
310                msg.push('\n');
311                msg.push_str(&running_test.message(now, width, styles));
312            }
313            if count < running_tests.len() {
314                let overflow_count = running_tests.len() - count;
315                swrite!(
316                    msg,
317                    "\n             ... and {} more {} running",
318                    overflow_count.style(styles.count),
319                    plural::tests_str(self.mode, overflow_count),
320                );
321                count += 1;
322            }
323            self.max_running_displayed = max(self.max_running_displayed, count);
324            msg.push_str(&"\n".to_string().repeat(self.max_running_displayed - count));
325        }
326        self.bar.set_message(msg);
327    }
328
329    fn progress_bar_msg(&self, styles: &Styles) -> String {
330        progress_bar_msg(&self.stats, self.running, styles)
331    }
332
333    pub(super) fn update_progress_bar(&mut self, event: &TestEvent<'_>, styles: &Styles) {
334        let before_should_hide = self.should_hide();
335
336        match &event.kind {
337            TestEventKind::StressSubRunStarted { .. } => {
338                self.bar.reset();
339            }
340            TestEventKind::StressSubRunFinished { .. } => {
341                // Clear all test bars to remove empty lines of output between
342                // sub-runs.
343                self.bar.finish_and_clear();
344            }
345            TestEventKind::SetupScriptStarted { no_capture, .. } => {
346                // Hide the progress bar if either stderr or stdout are being passed through.
347                if *no_capture {
348                    self.hidden_no_capture = true;
349                }
350            }
351            TestEventKind::SetupScriptFinished { no_capture, .. } => {
352                // Restore the progress bar if it was hidden.
353                if *no_capture {
354                    self.hidden_no_capture = false;
355                }
356            }
357            TestEventKind::TestStarted {
358                current_stats,
359                running,
360                test_instance,
361                ..
362            } => {
363                self.running = *running;
364                self.stats = *current_stats;
365
366                self.bar.set_prefix(progress_bar_prefix(
367                    current_stats,
368                    current_stats.cancel_reason,
369                    styles,
370                ));
371                self.bar.set_length(current_stats.initial_run_count as u64);
372                self.bar.set_position(current_stats.finished_count as u64);
373
374                if let Some(running_tests) = &mut self.running_tests {
375                    running_tests.push(RunningTest {
376                        binary_id: test_instance.binary_id.clone(),
377                        test_name: test_instance.test_name.to_owned(),
378                        status: RunningTestStatus::Running,
379                        start_time: Instant::now(),
380                        paused_for: Duration::ZERO,
381                    });
382                }
383            }
384            TestEventKind::TestFinished {
385                current_stats,
386                running,
387                test_instance,
388                ..
389            } => {
390                self.running = *running;
391                self.stats = *current_stats;
392                self.remove_test(test_instance);
393
394                self.bar.set_prefix(progress_bar_prefix(
395                    current_stats,
396                    current_stats.cancel_reason,
397                    styles,
398                ));
399                self.bar.set_length(current_stats.initial_run_count as u64);
400                self.bar.set_position(current_stats.finished_count as u64);
401            }
402            TestEventKind::TestAttemptFailedWillRetry {
403                test_instance,
404                delay_before_next_attempt,
405                ..
406            } => {
407                self.remove_test(test_instance);
408                if let Some(running_tests) = &mut self.running_tests {
409                    running_tests.push(RunningTest {
410                        binary_id: test_instance.binary_id.clone(),
411                        test_name: test_instance.test_name.to_owned(),
412                        status: RunningTestStatus::Delay(*delay_before_next_attempt),
413                        start_time: Instant::now(),
414                        paused_for: Duration::ZERO,
415                    });
416                }
417            }
418            TestEventKind::TestRetryStarted { test_instance, .. } => {
419                self.remove_test(test_instance);
420                if let Some(running_tests) = &mut self.running_tests {
421                    running_tests.push(RunningTest {
422                        binary_id: test_instance.binary_id.clone(),
423                        test_name: test_instance.test_name.to_owned(),
424                        status: RunningTestStatus::Retry,
425                        start_time: Instant::now(),
426                        paused_for: Duration::ZERO,
427                    });
428                }
429            }
430            TestEventKind::TestSlow { test_instance, .. } => {
431                if let Some(running_tests) = &mut self.running_tests {
432                    running_tests
433                        .iter_mut()
434                        .find(|rt| {
435                            &rt.binary_id == test_instance.binary_id
436                                && &rt.test_name == test_instance.test_name
437                        })
438                        .expect("a slow test to be already running")
439                        .status = RunningTestStatus::Slow;
440                }
441            }
442            TestEventKind::InfoStarted { .. } => {
443                // While info is being displayed, hide the progress bar to avoid
444                // it interrupting the info display.
445                self.hidden_info_response = true;
446            }
447            TestEventKind::InfoFinished { .. } => {
448                // Restore the progress bar if it was hidden.
449                self.hidden_info_response = false;
450            }
451            TestEventKind::RunPaused { .. } => {
452                // Pausing the run should hide the progress bar since we'll exit
453                // to the terminal immediately after.
454                self.hidden_run_paused = true;
455            }
456            TestEventKind::RunContinued { .. } => {
457                // Continuing the run should show the progress bar since we'll
458                // continue to output to it.
459                self.hidden_run_paused = false;
460                let current_global_elapsed = self.bar.elapsed();
461                self.bar.set_elapsed(event.elapsed);
462
463                if let Some(running_tests) = &mut self.running_tests {
464                    let delta = current_global_elapsed.saturating_sub(event.elapsed);
465                    for running_test in running_tests {
466                        running_test.paused_for += delta;
467                    }
468                }
469            }
470            TestEventKind::RunBeginCancel {
471                current_stats,
472                running,
473                ..
474            }
475            | TestEventKind::RunBeginKill {
476                current_stats,
477                running,
478                ..
479            } => {
480                self.running = *running;
481                self.stats = *current_stats;
482                self.bar.set_prefix(progress_bar_cancel_prefix(
483                    current_stats.cancel_reason,
484                    styles,
485                ));
486            }
487            _ => {}
488        }
489
490        let after_should_hide = self.should_hide();
491
492        match (before_should_hide, after_should_hide) {
493            (false, true) => self.bar.set_draw_target(Self::hidden_target()),
494            (true, false) => self.bar.set_draw_target(Self::stderr_target()),
495            _ => {}
496        }
497    }
498
499    fn remove_test(&mut self, test_instance: &TestInstanceId) {
500        if let Some(running_tests) = &mut self.running_tests {
501            running_tests.remove(
502                running_tests
503                    .iter()
504                    .position(|e| {
505                        &e.binary_id == test_instance.binary_id
506                            && &e.test_name == test_instance.test_name
507                    })
508                    .expect("finished test to have started"),
509            );
510        }
511    }
512
513    pub(super) fn write_buf(&mut self, buf: &str) {
514        self.buffer.push_str(buf);
515    }
516
517    #[inline]
518    pub(super) fn finish_and_clear(&self) {
519        self.print_and_force_redraw();
520        self.bar.finish_and_clear();
521    }
522
523    fn stderr_target() -> ProgressDrawTarget {
524        ProgressDrawTarget::stderr_with_hz(PROGRESS_REFRESH_RATE_HZ)
525    }
526
527    fn hidden_target() -> ProgressDrawTarget {
528        ProgressDrawTarget::hidden()
529    }
530
531    fn should_hide(&self) -> bool {
532        self.hidden_no_capture || self.hidden_run_paused || self.hidden_info_response
533    }
534}
535
536/// Whether to show OSC 9;4 terminal progress.
537#[derive(Clone, Copy, Debug, Eq, PartialEq)]
538pub enum ShowTerminalProgress {
539    /// Show terminal progress.
540    Yes,
541
542    /// Do not show terminal progress.
543    No,
544}
545
546impl ShowTerminalProgress {
547    const ENV: &str = "CARGO_TERM_PROGRESS_TERM_INTEGRATION";
548
549    /// Determines whether to show terminal progress based on Cargo configs and
550    /// whether the output is a terminal.
551    pub fn from_cargo_configs(configs: &CargoConfigs, is_terminal: bool) -> Self {
552        // See whether terminal integration is enabled in Cargo.
553        for config in configs.discovered_configs() {
554            match config {
555                DiscoveredConfig::CliOption { config, source } => {
556                    if let Some(v) = config.term.progress.term_integration {
557                        if v {
558                            debug!("enabling terminal progress reporting based on {source:?}");
559                            return Self::Yes;
560                        } else {
561                            debug!("disabling terminal progress reporting based on {source:?}");
562                            return Self::No;
563                        }
564                    }
565                }
566                DiscoveredConfig::Env => {
567                    if let Some(v) = env::var_os(Self::ENV) {
568                        if v == "true" {
569                            debug!(
570                                "enabling terminal progress reporting based on \
571                                 CARGO_TERM_PROGRESS_TERM_INTEGRATION environment variable"
572                            );
573                            return Self::Yes;
574                        } else if v == "false" {
575                            debug!(
576                                "disabling terminal progress reporting based on \
577                                 CARGO_TERM_PROGRESS_TERM_INTEGRATION environment variable"
578                            );
579                            return Self::No;
580                        } else {
581                            debug!(
582                                "invalid value for CARGO_TERM_PROGRESS_TERM_INTEGRATION \
583                                 environment variable: {v:?}, ignoring"
584                            );
585                        }
586                    }
587                }
588                DiscoveredConfig::File { config, source } => {
589                    if let Some(v) = config.term.progress.term_integration {
590                        if v {
591                            debug!("enabling terminal progress reporting based on {source:?}");
592                            return Self::Yes;
593                        } else {
594                            debug!("disabling terminal progress reporting based on {source:?}");
595                            return Self::No;
596                        }
597                    }
598                }
599            }
600        }
601
602        if supports_osc_9_4(is_terminal) {
603            Self::Yes
604        } else {
605            Self::No
606        }
607    }
608}
609
610/// OSC 9 terminal progress reporting.
611#[derive(Default)]
612pub(super) struct TerminalProgress {
613    last_value: TerminalProgressValue,
614}
615
616impl TerminalProgress {
617    pub(super) fn new(show: ShowTerminalProgress) -> Option<Self> {
618        match show {
619            ShowTerminalProgress::Yes => Some(Self::default()),
620            ShowTerminalProgress::No => None,
621        }
622    }
623
624    pub(super) fn update_progress(&mut self, event: &TestEvent<'_>) {
625        let value = match &event.kind {
626            TestEventKind::RunStarted { .. }
627            | TestEventKind::StressSubRunStarted { .. }
628            | TestEventKind::StressSubRunFinished { .. }
629            | TestEventKind::SetupScriptStarted { .. }
630            | TestEventKind::SetupScriptSlow { .. }
631            | TestEventKind::SetupScriptFinished { .. } => TerminalProgressValue::None,
632            TestEventKind::TestStarted { current_stats, .. }
633            | TestEventKind::TestFinished { current_stats, .. } => {
634                let percentage = (current_stats.finished_count as f64
635                    / current_stats.initial_run_count as f64)
636                    * 100.0;
637                if current_stats.has_failures() || current_stats.cancel_reason.is_some() {
638                    TerminalProgressValue::Error(percentage)
639                } else {
640                    TerminalProgressValue::Value(percentage)
641                }
642            }
643            TestEventKind::TestSlow { .. }
644            | TestEventKind::TestAttemptFailedWillRetry { .. }
645            | TestEventKind::TestRetryStarted { .. }
646            | TestEventKind::TestSkipped { .. }
647            | TestEventKind::InfoStarted { .. }
648            | TestEventKind::InfoResponse { .. }
649            | TestEventKind::InfoFinished { .. }
650            | TestEventKind::InputEnter { .. } => TerminalProgressValue::None,
651            TestEventKind::RunBeginCancel { current_stats, .. }
652            | TestEventKind::RunBeginKill { current_stats, .. } => {
653                // In this case, always indicate an error.
654                let percentage = (current_stats.finished_count as f64
655                    / current_stats.initial_run_count as f64)
656                    * 100.0;
657                TerminalProgressValue::Error(percentage)
658            }
659            TestEventKind::RunPaused { .. }
660            | TestEventKind::RunContinued { .. }
661            | TestEventKind::RunFinished { .. } => {
662                // Reset the terminal state to nothing, since nextest is giving
663                // up control of the terminal at this point.
664                TerminalProgressValue::Remove
665            }
666        };
667
668        self.last_value = value;
669    }
670
671    pub(super) fn last_value(&self) -> &TerminalProgressValue {
672        &self.last_value
673    }
674}
675
676/// Determines whether the terminal supports ANSI OSC 9;4.
677fn supports_osc_9_4(is_terminal: bool) -> bool {
678    if !is_terminal {
679        debug!(
680            "autodetect terminal progress reporting: disabling since \
681             passed-in stream (usually stderr) is not a terminal"
682        );
683        return false;
684    }
685    if std::env::var_os("WT_SESSION").is_some() {
686        debug!("autodetect terminal progress reporting: enabling since WT_SESSION is set");
687        return true;
688    };
689    if std::env::var_os("ConEmuANSI").is_some_and(|term| term == "ON") {
690        debug!("autodetect terminal progress reporting: enabling since ConEmuANSI is ON");
691        return true;
692    }
693    if let Ok(term) = std::env::var("TERM_PROGRAM")
694        && (term == "WezTerm" || term == "ghostty" || term == "iTerm.app")
695    {
696        debug!("autodetect terminal progress reporting: enabling since TERM_PROGRAM is {term}");
697        return true;
698    }
699
700    false
701}
702
703/// A progress status value printable as an ANSI OSC 9;4 escape code.
704///
705/// Adapted from Cargo 1.87.
706#[derive(PartialEq, Debug, Default)]
707pub(super) enum TerminalProgressValue {
708    /// No output.
709    #[default]
710    None,
711    /// Remove progress.
712    Remove,
713    /// Progress value (0-100).
714    Value(f64),
715    /// Indeterminate state (no bar, just animation)
716    ///
717    /// We don't use this yet, but might in the future.
718    #[expect(dead_code)]
719    Indeterminate,
720    /// Progress value in an error state (0-100).
721    Error(f64),
722}
723
724impl fmt::Display for TerminalProgressValue {
725    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
726        // From https://conemu.github.io/en/AnsiEscapeCodes.html#ConEmu_specific_OSC
727        // ESC ] 9 ; 4 ; st ; pr ST
728        // When st is 0: remove progress.
729        // When st is 1: set progress value to pr (number, 0-100).
730        // When st is 2: set error state in taskbar, pr is optional.
731        // When st is 3: set indeterminate state, pr is ignored.
732        // When st is 4: set paused state, pr is optional.
733        let (state, progress) = match self {
734            Self::None => return Ok(()), // No output
735            Self::Remove => (0, 0.0),
736            Self::Value(v) => (1, *v),
737            Self::Indeterminate => (3, 0.0),
738            Self::Error(v) => (2, *v),
739        };
740        write!(f, "\x1b]9;4;{state};{progress:.0}\x1b\\")
741    }
742}
743
744/// Returns a summary of current progress.
745pub(super) fn progress_str(
746    elapsed: Duration,
747    current_stats: &RunStats,
748    running: usize,
749    styles: &Styles,
750) -> String {
751    // First, show the prefix.
752    let mut s = progress_bar_prefix(current_stats, current_stats.cancel_reason, styles);
753
754    // Then, the time elapsed, test counts, and message.
755    swrite!(
756        s,
757        " {}{}/{}: {}",
758        DisplayBracketedHhMmSs(elapsed),
759        current_stats.finished_count,
760        current_stats.initial_run_count,
761        progress_bar_msg(current_stats, running, styles)
762    );
763
764    s
765}
766
767pub(super) fn write_summary_str(run_stats: &RunStats, styles: &Styles, out: &mut String) {
768    // Written in this style to ensure new fields are accounted for.
769    let &RunStats {
770        initial_run_count: _,
771        finished_count: _,
772        setup_scripts_initial_count: _,
773        setup_scripts_finished_count: _,
774        setup_scripts_passed: _,
775        setup_scripts_failed: _,
776        setup_scripts_exec_failed: _,
777        setup_scripts_timed_out: _,
778        passed,
779        passed_slow,
780        passed_timed_out: _,
781        flaky,
782        failed,
783        failed_slow: _,
784        failed_timed_out,
785        leaky,
786        leaky_failed,
787        exec_failed,
788        skipped,
789        cancel_reason: _,
790    } = run_stats;
791
792    swrite!(
793        out,
794        "{} {}",
795        passed.style(styles.count),
796        "passed".style(styles.pass)
797    );
798
799    if passed_slow > 0 || flaky > 0 || leaky > 0 {
800        let mut text = Vec::with_capacity(3);
801        if passed_slow > 0 {
802            text.push(format!(
803                "{} {}",
804                passed_slow.style(styles.count),
805                "slow".style(styles.skip),
806            ));
807        }
808        if flaky > 0 {
809            text.push(format!(
810                "{} {}",
811                flaky.style(styles.count),
812                "flaky".style(styles.skip),
813            ));
814        }
815        if leaky > 0 {
816            text.push(format!(
817                "{} {}",
818                leaky.style(styles.count),
819                "leaky".style(styles.skip),
820            ));
821        }
822        swrite!(out, " ({})", text.join(", "));
823    }
824    swrite!(out, ", ");
825
826    if failed > 0 {
827        swrite!(
828            out,
829            "{} {}",
830            failed.style(styles.count),
831            "failed".style(styles.fail),
832        );
833        if leaky_failed > 0 {
834            swrite!(
835                out,
836                " ({} due to being {})",
837                leaky_failed.style(styles.count),
838                "leaky".style(styles.fail),
839            );
840        }
841        swrite!(out, ", ");
842    }
843
844    if exec_failed > 0 {
845        swrite!(
846            out,
847            "{} {}, ",
848            exec_failed.style(styles.count),
849            "exec failed".style(styles.fail),
850        );
851    }
852
853    if failed_timed_out > 0 {
854        swrite!(
855            out,
856            "{} {}, ",
857            failed_timed_out.style(styles.count),
858            "timed out".style(styles.fail),
859        );
860    }
861
862    swrite!(
863        out,
864        "{} {}",
865        skipped.style(styles.count),
866        "skipped".style(styles.skip),
867    );
868}
869
870fn progress_bar_cancel_prefix(reason: Option<CancelReason>, styles: &Styles) -> String {
871    let status = match reason {
872        Some(CancelReason::SetupScriptFailure)
873        | Some(CancelReason::TestFailure)
874        | Some(CancelReason::ReportError)
875        | Some(CancelReason::GlobalTimeout)
876        | Some(CancelReason::TestFailureImmediate)
877        | Some(CancelReason::Signal)
878        | Some(CancelReason::Interrupt)
879        | None => "Cancelling",
880        Some(CancelReason::SecondSignal) => "Killing",
881    };
882    format!("{:>12}", status.style(styles.fail))
883}
884
885fn progress_bar_prefix(
886    run_stats: &RunStats,
887    cancel_reason: Option<CancelReason>,
888    styles: &Styles,
889) -> String {
890    if let Some(reason) = cancel_reason {
891        return progress_bar_cancel_prefix(Some(reason), styles);
892    }
893
894    let style = if run_stats.has_failures() {
895        styles.fail
896    } else {
897        styles.pass
898    };
899
900    format!("{:>12}", "Running".style(style))
901}
902
903pub(super) fn progress_bar_msg(
904    current_stats: &RunStats,
905    running: usize,
906    styles: &Styles,
907) -> String {
908    let mut s = format!("{} running, ", running.style(styles.count));
909    write_summary_str(current_stats, styles, &mut s);
910    s
911}
912
913#[cfg(test)]
914mod tests {
915    use super::*;
916    use crate::{
917        output_spec::LiveSpec,
918        reporter::TestOutputDisplay,
919        test_output::{ChildExecutionOutput, ChildOutput, ChildSplitOutput},
920    };
921    use bytes::Bytes;
922    use chrono::Local;
923
924    #[test]
925    fn test_progress_bar_prefix() {
926        let mut styles = Styles::default();
927        styles.colorize();
928
929        for (name, stats) in run_stats_test_failure_examples() {
930            let prefix = progress_bar_prefix(&stats, Some(CancelReason::TestFailure), &styles);
931            assert_eq!(
932                prefix,
933                "  Cancelling".style(styles.fail).to_string(),
934                "{name} matches"
935            );
936        }
937        for (name, stats) in run_stats_setup_script_failure_examples() {
938            let prefix =
939                progress_bar_prefix(&stats, Some(CancelReason::SetupScriptFailure), &styles);
940            assert_eq!(
941                prefix,
942                "  Cancelling".style(styles.fail).to_string(),
943                "{name} matches"
944            );
945        }
946
947        let prefix = progress_bar_prefix(&RunStats::default(), Some(CancelReason::Signal), &styles);
948        assert_eq!(prefix, "  Cancelling".style(styles.fail).to_string());
949
950        let prefix = progress_bar_prefix(&RunStats::default(), None, &styles);
951        assert_eq!(prefix, "     Running".style(styles.pass).to_string());
952
953        for (name, stats) in run_stats_test_failure_examples() {
954            let prefix = progress_bar_prefix(&stats, None, &styles);
955            assert_eq!(
956                prefix,
957                "     Running".style(styles.fail).to_string(),
958                "{name} matches"
959            );
960        }
961        for (name, stats) in run_stats_setup_script_failure_examples() {
962            let prefix = progress_bar_prefix(&stats, None, &styles);
963            assert_eq!(
964                prefix,
965                "     Running".style(styles.fail).to_string(),
966                "{name} matches"
967            );
968        }
969    }
970
971    #[test]
972    fn progress_str_snapshots() {
973        let mut styles = Styles::default();
974        styles.colorize();
975
976        // This elapsed time is arbitrary but reasonably large.
977        let elapsed = Duration::from_secs(123456);
978        let running = 10;
979
980        for (name, stats) in run_stats_test_failure_examples() {
981            let s = progress_str(elapsed, &stats, running, &styles);
982            insta::assert_snapshot!(format!("{name}_with_cancel_reason"), s);
983
984            let mut stats = stats;
985            stats.cancel_reason = None;
986            let s = progress_str(elapsed, &stats, running, &styles);
987            insta::assert_snapshot!(format!("{name}_without_cancel_reason"), s);
988        }
989
990        for (name, stats) in run_stats_setup_script_failure_examples() {
991            let s = progress_str(elapsed, &stats, running, &styles);
992            insta::assert_snapshot!(format!("{name}_with_cancel_reason"), s);
993
994            let mut stats = stats;
995            stats.cancel_reason = None;
996            let s = progress_str(elapsed, &stats, running, &styles);
997            insta::assert_snapshot!(format!("{name}_without_cancel_reason"), s);
998        }
999    }
1000
1001    #[test]
1002    fn running_test_snapshots() {
1003        let styles = Styles::default();
1004        let now = Instant::now();
1005
1006        for (name, running_test) in running_test_examples(now) {
1007            let msg = running_test.message(now, 80, &styles);
1008            insta::assert_snapshot!(name, msg);
1009        }
1010    }
1011
1012    fn running_test_examples(now: Instant) -> Vec<(&'static str, RunningTest)> {
1013        let binary_id = RustBinaryId::new("my-binary");
1014        let test_name = TestCaseName::new("test::my_test");
1015        let start_time = now - Duration::from_secs(125); // 2 minutes 5 seconds ago
1016
1017        vec![
1018            (
1019                "running_status",
1020                RunningTest {
1021                    binary_id: binary_id.clone(),
1022                    test_name: test_name.clone(),
1023                    status: RunningTestStatus::Running,
1024                    start_time,
1025                    paused_for: Duration::ZERO,
1026                },
1027            ),
1028            (
1029                "slow_status",
1030                RunningTest {
1031                    binary_id: binary_id.clone(),
1032                    test_name: test_name.clone(),
1033                    status: RunningTestStatus::Slow,
1034                    start_time,
1035                    paused_for: Duration::ZERO,
1036                },
1037            ),
1038            (
1039                "delay_status",
1040                RunningTest {
1041                    binary_id: binary_id.clone(),
1042                    test_name: test_name.clone(),
1043                    status: RunningTestStatus::Delay(Duration::from_secs(130)),
1044                    start_time,
1045                    paused_for: Duration::ZERO,
1046                },
1047            ),
1048            (
1049                "delay_status_underflow",
1050                RunningTest {
1051                    binary_id: binary_id.clone(),
1052                    test_name: test_name.clone(),
1053                    status: RunningTestStatus::Delay(Duration::from_secs(124)),
1054                    start_time,
1055                    paused_for: Duration::ZERO,
1056                },
1057            ),
1058            (
1059                "retry_status",
1060                RunningTest {
1061                    binary_id: binary_id.clone(),
1062                    test_name: test_name.clone(),
1063                    status: RunningTestStatus::Retry,
1064                    start_time,
1065                    paused_for: Duration::ZERO,
1066                },
1067            ),
1068            (
1069                "with_paused_duration",
1070                RunningTest {
1071                    binary_id: binary_id.clone(),
1072                    test_name: test_name.clone(),
1073                    status: RunningTestStatus::Running,
1074                    start_time,
1075                    paused_for: Duration::from_secs(30),
1076                },
1077            ),
1078        ]
1079    }
1080
1081    fn run_stats_test_failure_examples() -> Vec<(&'static str, RunStats)> {
1082        vec![
1083            (
1084                "one_failed",
1085                RunStats {
1086                    initial_run_count: 20,
1087                    finished_count: 1,
1088                    failed: 1,
1089                    cancel_reason: Some(CancelReason::TestFailure),
1090                    ..RunStats::default()
1091                },
1092            ),
1093            (
1094                "one_failed_one_passed",
1095                RunStats {
1096                    initial_run_count: 20,
1097                    finished_count: 2,
1098                    failed: 1,
1099                    passed: 1,
1100                    cancel_reason: Some(CancelReason::TestFailure),
1101                    ..RunStats::default()
1102                },
1103            ),
1104            (
1105                "one_exec_failed",
1106                RunStats {
1107                    initial_run_count: 20,
1108                    finished_count: 10,
1109                    exec_failed: 1,
1110                    cancel_reason: Some(CancelReason::TestFailure),
1111                    ..RunStats::default()
1112                },
1113            ),
1114            (
1115                "one_timed_out",
1116                RunStats {
1117                    initial_run_count: 20,
1118                    finished_count: 10,
1119                    failed_timed_out: 1,
1120                    cancel_reason: Some(CancelReason::TestFailure),
1121                    ..RunStats::default()
1122                },
1123            ),
1124        ]
1125    }
1126
1127    fn run_stats_setup_script_failure_examples() -> Vec<(&'static str, RunStats)> {
1128        vec![
1129            (
1130                "one_setup_script_failed",
1131                RunStats {
1132                    initial_run_count: 30,
1133                    setup_scripts_failed: 1,
1134                    cancel_reason: Some(CancelReason::SetupScriptFailure),
1135                    ..RunStats::default()
1136                },
1137            ),
1138            (
1139                "one_setup_script_exec_failed",
1140                RunStats {
1141                    initial_run_count: 35,
1142                    setup_scripts_exec_failed: 1,
1143                    cancel_reason: Some(CancelReason::SetupScriptFailure),
1144                    ..RunStats::default()
1145                },
1146            ),
1147            (
1148                "one_setup_script_timed_out",
1149                RunStats {
1150                    initial_run_count: 40,
1151                    setup_scripts_timed_out: 1,
1152                    cancel_reason: Some(CancelReason::SetupScriptFailure),
1153                    ..RunStats::default()
1154                },
1155            ),
1156        ]
1157    }
1158
1159    /// Test that `update_progress_bar` correctly updates `self.stats` when
1160    /// processing `TestStarted` and `TestFinished` events.
1161    ///
1162    /// This test verifies both:
1163    ///
1164    /// 1. State: `self.stats` equals the event's `current_stats` after processing.
1165    /// 2. Output: `state.progress_bar_msg()` reflects the updated stats.
1166    #[test]
1167    fn update_progress_bar_updates_stats() {
1168        let styles = Styles::default();
1169        let binary_id = RustBinaryId::new("test-binary");
1170        let test_name = TestCaseName::new("test_name");
1171
1172        // Create ProgressBarState with initial (default) stats.
1173        let mut state = ProgressBarState::new(
1174            NextestRunMode::Test,
1175            10,
1176            "=> ",
1177            MaxProgressRunning::default(),
1178        );
1179
1180        // Verify the initial state.
1181        assert_eq!(state.stats, RunStats::default());
1182        assert_eq!(state.running, 0);
1183
1184        // Create a TestStarted event.
1185        let started_stats = RunStats {
1186            initial_run_count: 10,
1187            passed: 5,
1188            ..RunStats::default()
1189        };
1190        let started_event = TestEvent {
1191            timestamp: Local::now().fixed_offset(),
1192            elapsed: Duration::ZERO,
1193            kind: TestEventKind::TestStarted {
1194                stress_index: None,
1195                test_instance: TestInstanceId {
1196                    binary_id: &binary_id,
1197                    test_name: &test_name,
1198                },
1199                current_stats: started_stats,
1200                running: 3,
1201                command_line: vec![],
1202            },
1203        };
1204
1205        state.update_progress_bar(&started_event, &styles);
1206
1207        // Verify the state was updated.
1208        assert_eq!(
1209            state.stats, started_stats,
1210            "stats should be updated on TestStarted"
1211        );
1212        assert_eq!(state.running, 3, "running should be updated on TestStarted");
1213
1214        // Verify that the output reflects the updated stats.
1215        let msg = state.progress_bar_msg(&styles);
1216        insta::assert_snapshot!(msg, @"3 running, 5 passed, 0 skipped");
1217
1218        // Create a TestFinished event with different stats.
1219        let finished_stats = RunStats {
1220            initial_run_count: 10,
1221            finished_count: 1,
1222            passed: 8,
1223            ..RunStats::default()
1224        };
1225        let finished_event = TestEvent {
1226            timestamp: Local::now().fixed_offset(),
1227            elapsed: Duration::ZERO,
1228            kind: TestEventKind::TestFinished {
1229                stress_index: None,
1230                test_instance: TestInstanceId {
1231                    binary_id: &binary_id,
1232                    test_name: &test_name,
1233                },
1234                success_output: TestOutputDisplay::Never,
1235                failure_output: TestOutputDisplay::Never,
1236                junit_store_success_output: false,
1237                junit_store_failure_output: false,
1238                run_statuses: ExecutionStatuses::new(vec![ExecuteStatus {
1239                    retry_data: RetryData {
1240                        attempt: 1,
1241                        total_attempts: 1,
1242                    },
1243                    output: make_test_output(),
1244                    result: ExecutionResultDescription::Pass,
1245                    start_time: Local::now().fixed_offset(),
1246                    time_taken: Duration::from_secs(1),
1247                    is_slow: false,
1248                    delay_before_start: Duration::ZERO,
1249                    error_summary: None,
1250                    output_error_slice: None,
1251                }]),
1252                current_stats: finished_stats,
1253                running: 2,
1254            },
1255        };
1256
1257        state.update_progress_bar(&finished_event, &styles);
1258
1259        // Verify the state was updated.
1260        assert_eq!(
1261            state.stats, finished_stats,
1262            "stats should be updated on TestFinished"
1263        );
1264        assert_eq!(
1265            state.running, 2,
1266            "running should be updated on TestFinished"
1267        );
1268
1269        // Verify that the output reflects the updated stats.
1270        let msg = state.progress_bar_msg(&styles);
1271        insta::assert_snapshot!(msg, @"2 running, 8 passed, 0 skipped");
1272
1273        // Create a RunBeginCancel event.
1274        let cancel_stats = RunStats {
1275            initial_run_count: 10,
1276            finished_count: 3,
1277            passed: 2,
1278            failed: 1,
1279            cancel_reason: Some(CancelReason::TestFailure),
1280            ..RunStats::default()
1281        };
1282        let cancel_event = TestEvent {
1283            timestamp: Local::now().fixed_offset(),
1284            elapsed: Duration::ZERO,
1285            kind: TestEventKind::RunBeginCancel {
1286                setup_scripts_running: 0,
1287                current_stats: cancel_stats,
1288                running: 4,
1289            },
1290        };
1291
1292        state.update_progress_bar(&cancel_event, &styles);
1293
1294        // Verify the state was updated.
1295        assert_eq!(
1296            state.stats, cancel_stats,
1297            "stats should be updated on RunBeginCancel"
1298        );
1299        assert_eq!(
1300            state.running, 4,
1301            "running should be updated on RunBeginCancel"
1302        );
1303
1304        // Verify that the output reflects the updated stats.
1305        let msg = state.progress_bar_msg(&styles);
1306        insta::assert_snapshot!(msg, @"4 running, 2 passed, 1 failed, 0 skipped");
1307
1308        // Create a RunBeginKill event with different stats.
1309        let kill_stats = RunStats {
1310            initial_run_count: 10,
1311            finished_count: 5,
1312            passed: 3,
1313            failed: 2,
1314            cancel_reason: Some(CancelReason::Signal),
1315            ..RunStats::default()
1316        };
1317        let kill_event = TestEvent {
1318            timestamp: Local::now().fixed_offset(),
1319            elapsed: Duration::ZERO,
1320            kind: TestEventKind::RunBeginKill {
1321                setup_scripts_running: 0,
1322                current_stats: kill_stats,
1323                running: 2,
1324            },
1325        };
1326
1327        state.update_progress_bar(&kill_event, &styles);
1328
1329        // Verify the state was updated.
1330        assert_eq!(
1331            state.stats, kill_stats,
1332            "stats should be updated on RunBeginKill"
1333        );
1334        assert_eq!(
1335            state.running, 2,
1336            "running should be updated on RunBeginKill"
1337        );
1338
1339        // Verify that the output reflects the updated stats.
1340        let msg = state.progress_bar_msg(&styles);
1341        insta::assert_snapshot!(msg, @"2 running, 3 passed, 2 failed, 0 skipped");
1342    }
1343
1344    // Helper to create minimal output for ExecuteStatus.
1345    fn make_test_output() -> ChildExecutionOutputDescription<LiveSpec> {
1346        ChildExecutionOutput::Output {
1347            result: Some(ExecutionResult::Pass),
1348            output: ChildOutput::Split(ChildSplitOutput {
1349                stdout: Some(Bytes::new().into()),
1350                stderr: Some(Bytes::new().into()),
1351            }),
1352            errors: None,
1353        }
1354        .into()
1355    }
1356}