-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmod.rs
More file actions
737 lines (672 loc) · 26.4 KB
/
mod.rs
File metadata and controls
737 lines (672 loc) · 26.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
//! Progress Reporting for Long-Running Operations
//!
//! This module provides progress reporting functionality for multi-step operations
//! that take significant time to complete. It builds on top of `UserOutput` to
//! provide standardized progress updates with timing information.
//!
//! ## Sub-modules
//!
//! - `verbose_listener` - `CommandProgressListener` implementation that translates
//! application-layer progress events into user-facing output
pub mod verbose_listener;
pub use verbose_listener::VerboseProgressListener;
use std::cell::RefCell;
use std::sync::Arc;
use std::time::{Duration, Instant};
use parking_lot::ReentrantMutex;
use thiserror::Error;
use crate::presentation::cli::views::UserOutput;
/// Errors that can occur during progress reporting
#[derive(Debug, Error)]
pub enum ProgressReporterError {
/// `UserOutput` mutex was poisoned
///
/// The shared `UserOutput` mutex was poisoned by a panic in another thread.
/// This indicates a critical internal error.
#[error(
"Internal error: UserOutput mutex was poisoned
Tip: This is a critical bug - please report it with full logs using --log-output file-and-stderr"
)]
UserOutputMutexPoisoned,
}
/// Progress reporter for multi-step operations
///
/// Tracks progress through multiple steps of a long-running operation,
/// providing clear feedback with step numbers, descriptions, and timing.
///
/// # Examples
///
/// ```rust
/// use std::sync::Arc;
/// use std::cell::RefCell;
/// use parking_lot::ReentrantMutex;
/// use torrust_tracker_deployer_lib::presentation::cli::views::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::cli::views::{UserOutput, VerbosityLevel};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let output = Arc::new(ReentrantMutex::new(RefCell::new(UserOutput::new(VerbosityLevel::Normal))));
/// let mut progress = ProgressReporter::new(output, 2);
///
/// progress.start_step("Step 1")?;
/// progress.complete_step(Some("Step 1 done"))?;
///
/// progress.start_step("Step 2")?;
/// progress.complete_step(None)?;
///
/// progress.complete("All done!")?;
/// # Ok(())
/// # }
/// ```
pub struct ProgressReporter {
output: Arc<ReentrantMutex<RefCell<UserOutput>>>,
total_steps: usize,
current_step: usize,
step_start: Option<Instant>,
}
impl ProgressReporter {
/// Create a new progress reporter
///
/// # Arguments
///
/// * `output` - Shared user output handler for displaying messages
/// * `total_steps` - Total number of steps in the operation
///
/// # Examples
///
/// ```rust
/// use std::sync::Arc;
/// use std::cell::RefCell;
/// use parking_lot::ReentrantMutex;
/// use torrust_tracker_deployer_lib::presentation::cli::views::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::cli::views::{UserOutput, VerbosityLevel};
///
/// let output = Arc::new(ReentrantMutex::new(RefCell::new(UserOutput::new(VerbosityLevel::Normal))));
/// let progress = ProgressReporter::new(output, 5);
/// ```
#[must_use]
pub fn new(output: Arc<ReentrantMutex<RefCell<UserOutput>>>, total_steps: usize) -> Self {
Self {
output,
total_steps,
current_step: 0,
step_start: None,
}
}
/// Execute a function with the locked `UserOutput`
///
/// With `ReentrantMutex`, we can safely lock multiple times on the same thread.
/// The `RefCell` provides interior mutability.
fn with_output<F, R>(&self, f: F) -> Result<R, ProgressReporterError>
where
F: FnOnce(&mut UserOutput) -> R,
{
let guard = self.output.lock();
let mut user_output = guard
.try_borrow_mut()
.map_err(|_| ProgressReporterError::UserOutputMutexPoisoned)?;
Ok(f(&mut user_output))
}
/// Start a new step with a description
///
/// Increments the current step counter and displays a progress message
/// in the format `[current/total] description...`.
///
/// # Arguments
///
/// * `description` - Human-readable description of what this step does
///
/// # Errors
///
/// Returns `ProgressReporterError::UserOutputMutexPoisoned` if the mutex is poisoned.
///
/// # Examples
///
/// ```rust
/// use std::sync::Arc;
/// use std::cell::RefCell;
/// use parking_lot::ReentrantMutex;
/// use torrust_tracker_deployer_lib::presentation::cli::views::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::cli::views::{UserOutput, VerbosityLevel};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let output = Arc::new(ReentrantMutex::new(RefCell::new(UserOutput::new(VerbosityLevel::Normal))));
/// let mut progress = ProgressReporter::new(output, 3);
///
/// progress.start_step("Loading configuration")?;
/// // Output: ⏳ [1/3] Loading configuration...
/// # Ok(())
/// # }
/// ```
pub fn start_step(&mut self, description: &str) -> Result<(), ProgressReporterError> {
self.current_step += 1;
self.step_start = Some(Instant::now());
self.with_output(|output| {
output.progress(&format!(
"[{}/{}] {}...",
self.current_step, self.total_steps, description
));
})?;
Ok(())
}
/// Complete the current step with optional result message
///
/// Displays a completion message with timing information.
/// The message shows either the provided result or a generic "Done" message.
///
/// # Arguments
///
/// * `result` - Optional description of what was accomplished
///
/// # Errors
///
/// Returns `ProgressReporterError::UserOutputMutexPoisoned` if the mutex is poisoned.
///
/// # Examples
///
/// ```rust
/// use std::sync::Arc;
/// use std::cell::RefCell;
/// use parking_lot::ReentrantMutex;
/// use torrust_tracker_deployer_lib::presentation::cli::views::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::cli::views::{UserOutput, VerbosityLevel};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let output = Arc::new(ReentrantMutex::new(RefCell::new(UserOutput::new(VerbosityLevel::Normal))));
/// let mut progress = ProgressReporter::new(output, 2);
///
/// progress.start_step("Loading data")?;
/// progress.complete_step(Some("Data loaded successfully"))?;
/// // Output: ✓ Data loaded successfully (took 150ms)
///
/// progress.start_step("Processing")?;
/// progress.complete_step(None)?;
/// // Output: ✓ Done (took 2.3s)
/// # Ok(())
/// # }
/// ```
pub fn complete_step(&mut self, result: Option<&str>) -> Result<(), ProgressReporterError> {
if let Some(start) = self.step_start {
let duration = start.elapsed();
self.with_output(|output| {
if let Some(msg) = result {
output.progress(&format!(" ✓ {} (took {})", msg, format_duration(duration)));
} else {
output.progress(&format!(" ✓ Done (took {})", format_duration(duration)));
}
})?;
}
self.step_start = None;
Ok(())
}
/// Report a sub-step within the current step
///
/// Displays an indented message indicating progress within the current step.
/// Useful for showing detailed progress without starting a new numbered step.
///
/// # Arguments
///
/// * `description` - What is currently happening within this step
///
/// # Errors
///
/// Returns `ProgressReporterError::UserOutputMutexPoisoned` if the mutex is poisoned.
///
/// # Examples
///
/// ```rust
/// use std::sync::Arc;
/// use std::cell::RefCell;
/// use parking_lot::ReentrantMutex;
/// use torrust_tracker_deployer_lib::presentation::cli::views::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::cli::views::{UserOutput, VerbosityLevel};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let output = Arc::new(ReentrantMutex::new(RefCell::new(UserOutput::new(VerbosityLevel::Normal))));
/// let mut progress = ProgressReporter::new(output.clone(), 1);
///
/// progress.start_step("Provisioning infrastructure")?;
/// progress.sub_step("Creating virtual machine")?;
/// progress.sub_step("Configuring network")?;
/// progress.sub_step("Setting up storage")?;
/// progress.complete_step(Some("Infrastructure ready"))?;
/// # Ok(())
/// # }
/// ```
pub fn sub_step(&mut self, description: &str) -> Result<(), ProgressReporterError> {
self.with_output(|output| {
output.progress(&format!(" → {description}"));
})?;
Ok(())
}
/// Complete all steps and show summary
///
/// Displays a final success message indicating the entire operation completed.
/// This should be called after all steps are done.
///
/// # Arguments
///
/// * `summary` - Final success message describing what was accomplished
///
/// # Errors
///
/// Returns `ProgressReporterError::UserOutputMutexPoisoned` if the mutex is poisoned.
///
/// # Examples
///
/// ```rust
/// use std::sync::Arc;
/// use std::cell::RefCell;
/// use parking_lot::ReentrantMutex;
/// use torrust_tracker_deployer_lib::presentation::cli::views::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::cli::views::{UserOutput, VerbosityLevel};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let output = Arc::new(ReentrantMutex::new(RefCell::new(UserOutput::new(VerbosityLevel::Normal))));
/// let mut progress = ProgressReporter::new(output.clone(), 1);
///
/// progress.start_step("Creating environment")?;
/// progress.complete_step(None)?;
/// progress.complete("Environment 'test-env' created successfully")?;
/// // Output: ✅ Environment 'test-env' created successfully
/// # Ok(())
/// # }
/// ```
pub fn complete(&mut self, summary: &str) -> Result<(), ProgressReporterError> {
self.with_output(|output| output.success(summary))?;
Ok(())
}
/// Get a reference to the shared `UserOutput`
///
/// This allows using other output methods (like `error`, `warn`)
/// while progress is being tracked.
///
/// # Examples
///
/// ```rust
/// use std::sync::Arc;
/// use std::cell::RefCell;
/// use parking_lot::ReentrantMutex;
/// use torrust_tracker_deployer_lib::presentation::cli::views::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::cli::views::{UserOutput, VerbosityLevel};
///
/// let output = Arc::new(ReentrantMutex::new(RefCell::new(UserOutput::new(VerbosityLevel::Normal))));
/// let mut progress = ProgressReporter::new(output.clone(), 1);
///
/// progress.start_step("Checking conditions");
/// progress.output().lock().borrow_mut().warn("Some non-critical warning");
/// progress.complete_step(None);
/// ```
#[must_use]
pub fn output(&self) -> &Arc<ReentrantMutex<RefCell<UserOutput>>> {
&self.output
}
/// Add a blank line to the output
///
/// This is a wrapper around `UserOutput::blank_line()` that handles
/// mutex acquisition with timeout protection.
///
/// # Errors
///
/// Returns `ProgressReporterError::UserOutputMutexPoisoned` if the mutex is poisoned.
/// Returns `ProgressReporterError::UserOutputMutexTimeout` if the mutex cannot be acquired within the timeout.
///
/// # Examples
///
/// ```rust
/// use std::sync::Arc;
/// use std::cell::RefCell;
/// use parking_lot::ReentrantMutex;
/// use torrust_tracker_deployer_lib::presentation::cli::views::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::cli::views::{UserOutput, VerbosityLevel};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let output = Arc::new(ReentrantMutex::new(RefCell::new(UserOutput::new(VerbosityLevel::Normal))));
/// let mut progress = ProgressReporter::new(output, 3);
///
/// progress.blank_line()?;
/// # Ok(())
/// # }
/// ```
pub fn blank_line(&self) -> Result<(), ProgressReporterError> {
self.with_output(UserOutput::blank_line)?;
Ok(())
}
/// Display a list of steps with a title
///
/// This is a wrapper around `UserOutput::steps()` that handles
/// mutex acquisition with timeout protection.
///
/// # Arguments
///
/// * `title` - The title for the steps list
/// * `steps` - Array of step descriptions
///
/// # Errors
///
/// Returns `ProgressReporterError::UserOutputMutexPoisoned` if the mutex is poisoned.
/// Returns `ProgressReporterError::UserOutputMutexTimeout` if the mutex cannot be acquired within the timeout.
///
/// # Examples
///
/// ```rust
/// use std::sync::Arc;
/// use std::cell::RefCell;
/// use parking_lot::ReentrantMutex;
/// use torrust_tracker_deployer_lib::presentation::cli::views::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::cli::views::{UserOutput, VerbosityLevel};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let output = Arc::new(ReentrantMutex::new(RefCell::new(UserOutput::new(VerbosityLevel::Normal))));
/// let mut progress = ProgressReporter::new(output, 3);
///
/// progress.steps("Next steps:", &[
/// "Edit the configuration file",
/// "Review the settings",
/// "Run the deploy command"
/// ])?;
/// # Ok(())
/// # }
/// ```
pub fn steps(&self, title: &str, steps: &[&str]) -> Result<(), ProgressReporterError> {
self.with_output(|output| output.steps(title, steps))?;
Ok(())
}
/// Output result data to stdout
///
/// Wraps `UserOutput::result()` to write result data to stdout.
/// Result data goes to stdout (not stderr) so it can be piped or redirected.
///
/// # Arguments ///
/// * `message` - The result data to output
///
/// # Errors
///
/// Returns error if the user output mutex is poisoned
///
/// # Examples
///
/// ```rust
/// use std::sync::Arc;
/// use std::cell::RefCell;
/// use parking_lot::ReentrantMutex;
/// use torrust_tracker_deployer_lib::presentation::cli::views::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::cli::views::{UserOutput, VerbosityLevel};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let output = Arc::new(ReentrantMutex::new(RefCell::new(UserOutput::new(VerbosityLevel::Normal))));
/// let progress = ProgressReporter::new(output, 1);
///
/// progress.result(r#"{"schema": "..."}"#)?;
/// # Ok(())
/// # }
/// ```
pub fn result(&self, message: &str) -> Result<(), ProgressReporterError> {
self.with_output(|output| output.result(message))?;
Ok(())
}
/// Display a warning message to stderr
///
/// Wraps `UserOutput::warn()` for use during progress-tracked workflows.
/// Warnings are non-blocking — they do not stop the current operation.
///
/// # Arguments
///
/// * `message` - Warning text (may contain newlines for multi-line warnings)
///
/// # Errors
///
/// Returns `ProgressReporterError::UserOutputMutexPoisoned` if the mutex is poisoned.
///
/// # Examples
///
/// ```rust
/// use std::sync::Arc;
/// use std::cell::RefCell;
/// use parking_lot::ReentrantMutex;
/// use torrust_tracker_deployer_lib::presentation::cli::views::progress::ProgressReporter;
/// use torrust_tracker_deployer_lib::presentation::cli::views::{UserOutput, VerbosityLevel};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let output = Arc::new(ReentrantMutex::new(RefCell::new(UserOutput::new(VerbosityLevel::Normal))));
/// let progress = ProgressReporter::new(output, 1);
///
/// progress.warn("SSH key appears to be passphrase-protected")?;
/// # Ok(())
/// # }
/// ```
pub fn warn(&self, message: &str) -> Result<(), ProgressReporterError> {
self.with_output(|output| output.warn(message))?;
Ok(())
}
}
/// Format duration in a human-readable way
///
/// Converts durations to appropriate units:
/// - Less than 1 second: milliseconds (e.g., "150ms")
/// - 1 second or more: seconds with 1 decimal place (e.g., "2.3s")
///
/// # Arguments
///
/// * `duration` - The duration to format
///
/// # Returns
///
/// A human-readable string representation of the duration
fn format_duration(duration: Duration) -> String {
let millis = duration.as_millis();
if millis < 1000 {
format!("{millis}ms")
} else {
format!("{:.1}s", duration.as_secs_f64())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::presentation::cli::views::testing::TestUserOutput;
use crate::presentation::cli::views::VerbosityLevel;
#[test]
fn it_should_create_progress_reporter_with_total_steps() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, _stdout, _stderr) = test_output.into_reentrant_wrapped();
let progress = ProgressReporter::new(output, 5);
assert_eq!(progress.total_steps, 5);
assert_eq!(progress.current_step, 0);
assert!(progress.step_start.is_none());
}
#[test]
fn it_should_start_step_and_increment_counter() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, _stdout, stderr) = test_output.into_reentrant_wrapped();
let mut progress = ProgressReporter::new(output, 3);
progress
.start_step("Loading configuration")
.expect("Failed to start step");
assert_eq!(progress.current_step, 1);
assert!(progress.step_start.is_some());
let stderr_content = String::from_utf8(stderr.lock().clone()).unwrap();
assert!(stderr_content.contains("[1/3] Loading configuration..."));
}
#[test]
fn it_should_track_multiple_steps() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, _stdout, stderr) = test_output.into_reentrant_wrapped();
let mut progress = ProgressReporter::new(output, 3);
progress
.start_step("Step 1")
.expect("Failed to start step 1");
assert_eq!(progress.current_step, 1);
progress
.start_step("Step 2")
.expect("Failed to start step 2");
assert_eq!(progress.current_step, 2);
progress
.start_step("Step 3")
.expect("Failed to start step 3");
assert_eq!(progress.current_step, 3);
let stderr_content = String::from_utf8(stderr.lock().clone()).unwrap();
assert!(stderr_content.contains("[1/3] Step 1..."));
assert!(stderr_content.contains("[2/3] Step 2..."));
assert!(stderr_content.contains("[3/3] Step 3..."));
}
#[test]
fn it_should_complete_step_with_result_message() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, _stdout, stderr) = test_output.into_reentrant_wrapped();
let mut progress = ProgressReporter::new(output, 1);
progress
.start_step("Loading data")
.expect("Failed to start step");
progress
.complete_step(Some("Data loaded successfully"))
.expect("Failed to complete step");
let stderr_content = String::from_utf8(stderr.lock().clone()).unwrap();
assert!(stderr_content.contains("✓ Data loaded successfully"));
assert!(stderr_content.contains("took"));
assert!(progress.step_start.is_none());
}
#[test]
fn it_should_complete_step_without_result_message() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, _stdout, stderr) = test_output.into_reentrant_wrapped();
let mut progress = ProgressReporter::new(output, 1);
progress
.start_step("Processing")
.expect("Failed to start step");
progress
.complete_step(None)
.expect("Failed to complete step");
let stderr_content = String::from_utf8(stderr.lock().clone()).unwrap();
assert!(stderr_content.contains("✓ Done"));
assert!(stderr_content.contains("took"));
assert!(progress.step_start.is_none());
}
#[test]
fn it_should_report_sub_steps() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, _stdout, stderr) = test_output.into_reentrant_wrapped();
let mut progress = ProgressReporter::new(output, 1);
progress
.start_step("Provisioning")
.expect("Failed to start step");
progress
.sub_step("Creating VM")
.expect("Failed to report sub-step");
progress
.sub_step("Configuring network")
.expect("Failed to report sub-step");
progress
.complete_step(None)
.expect("Failed to complete step");
let stderr_content = String::from_utf8(stderr.lock().clone()).unwrap();
assert!(stderr_content.contains("→ Creating VM"));
assert!(stderr_content.contains("→ Configuring network"));
}
#[test]
fn it_should_display_completion_summary() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, _stdout, stderr) = test_output.into_reentrant_wrapped();
let mut progress = ProgressReporter::new(output, 1);
progress
.start_step("Creating environment")
.expect("Failed to start step");
progress
.complete_step(None)
.expect("Failed to complete step");
progress
.complete("Environment created successfully")
.expect("Failed to complete");
let stderr_content = String::from_utf8(stderr.lock().clone()).unwrap();
assert!(stderr_content.contains("✅ Environment created successfully"));
}
#[test]
fn it_should_provide_access_to_output() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, _stdout, stderr) = test_output.into_reentrant_wrapped();
let progress = ProgressReporter::new(output.clone(), 1);
progress
.with_output(|user_output| user_output.warn("Test warning"))
.expect("Failed to write to output");
let stderr_content = String::from_utf8(stderr.lock().clone()).expect("Invalid UTF-8");
assert!(stderr_content.contains("⚠️ Test warning"));
}
#[test]
fn it_should_respect_verbosity_levels() {
let test_output = TestUserOutput::new(VerbosityLevel::Quiet);
let (output, _stdout, stderr) = test_output.into_reentrant_wrapped();
let mut progress = ProgressReporter::new(output, 1);
progress.start_step("Step 1").expect("Failed to start step");
progress
.complete_step(Some("Done"))
.expect("Failed to complete step");
// At Quiet level, progress messages should not appear
let stderr_content = String::from_utf8(stderr.lock().clone()).expect("Invalid UTF-8");
assert_eq!(stderr_content, "");
}
#[test]
fn it_should_format_milliseconds_correctly() {
let duration = Duration::from_millis(150);
assert_eq!(format_duration(duration), "150ms");
let duration = Duration::from_millis(999);
assert_eq!(format_duration(duration), "999ms");
}
#[test]
fn it_should_format_seconds_correctly() {
let duration = Duration::from_secs(1);
assert_eq!(format_duration(duration), "1.0s");
let duration = Duration::from_millis(2345);
assert_eq!(format_duration(duration), "2.3s");
let duration = Duration::from_secs(10);
assert_eq!(format_duration(duration), "10.0s");
}
#[test]
fn it_should_handle_full_workflow() {
let test_output = TestUserOutput::new(VerbosityLevel::Normal);
let (output, stdout, stderr) = test_output.into_reentrant_wrapped();
let mut progress = ProgressReporter::new(output, 3);
// Step 1
progress
.start_step("Loading configuration")
.expect("Failed to start step 1");
progress
.complete_step(Some("Configuration loaded: test-env"))
.expect("Failed to complete step 1");
// Step 2 with sub-steps
progress
.start_step("Provisioning infrastructure")
.expect("Failed to start step 2");
progress
.sub_step("Creating virtual machine")
.expect("Failed to report sub-step");
progress
.sub_step("Configuring network")
.expect("Failed to report sub-step");
progress
.complete_step(Some("Instance created: test-instance"))
.expect("Failed to complete step 2");
// Step 3
progress
.start_step("Finalizing environment")
.expect("Failed to start step 3");
progress
.complete_step(None)
.expect("Failed to complete step 3");
// Complete
progress
.complete("Environment 'test-env' created successfully")
.expect("Failed to complete");
let stderr_content = String::from_utf8(stderr.lock().clone()).expect("Invalid UTF-8");
assert!(stderr_content.contains("[1/3] Loading configuration..."));
assert!(stderr_content.contains("[2/3] Provisioning infrastructure..."));
assert!(stderr_content.contains("[3/3] Finalizing environment..."));
assert!(stderr_content.contains("✅ Environment 'test-env' created successfully"));
assert!(stderr_content.contains("✓ Configuration loaded: test-env"));
assert!(stderr_content.contains("→ Creating virtual machine"));
assert!(stderr_content.contains("→ Configuring network"));
assert!(stderr_content.contains("✓ Instance created: test-instance"));
assert!(stderr_content.contains("✓ Done"));
let stdout_content = String::from_utf8(stdout.lock().clone()).expect("Invalid UTF-8");
// stdout should be empty - all progress goes to stderr
assert!(stdout_content.is_empty());
}
}