-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcore.rs
More file actions
2538 lines (2091 loc) · 92.1 KB
/
Copy pathcore.rs
File metadata and controls
2538 lines (2091 loc) · 92.1 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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Core `UserOutput` struct and implementation
use std::io::Write;
use super::messages::{
ErrorMessage, InfoBlockMessage, ProgressMessage, ResultMessage, StepsMessage, SuccessMessage,
WarningMessage,
};
use super::sinks::StandardSink;
use super::verbosity::VerbosityFilter;
use super::{Channel, FormatterOverride, OutputMessage, OutputSink, Theme, VerbosityLevel};
pub struct UserOutput {
theme: Theme,
verbosity_filter: VerbosityFilter,
sink: Box<dyn OutputSink>,
formatter_override: Option<Box<dyn FormatterOverride>>,
}
impl UserOutput {
/// Create new `UserOutput` with default stdout/stderr channels and emoji theme
///
/// Uses `StandardSink` for backward compatibility with existing console output.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// let output = UserOutput::new(VerbosityLevel::Normal);
/// ```
#[must_use]
pub fn new(verbosity: VerbosityLevel) -> Self {
Self::with_theme(verbosity, Theme::default())
}
/// Create `UserOutput` with a specific theme
///
/// Allows customization of output symbols while using default stdout/stderr channels.
/// Uses `StandardSink` internally for backward compatibility.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel, Theme};
///
/// // Use plain text theme for CI/CD
/// let output = UserOutput::with_theme(VerbosityLevel::Normal, Theme::plain());
///
/// // Use ASCII theme for limited terminals
/// let output = UserOutput::with_theme(VerbosityLevel::Normal, Theme::ascii());
/// ```
#[must_use]
pub fn with_theme(verbosity: VerbosityLevel, theme: Theme) -> Self {
Self::with_sink(verbosity, Box::new(StandardSink::default_console()))
.with_theme_applied(theme)
}
/// Create `UserOutput` with a custom sink
///
/// This constructor enables the use of alternative output destinations,
/// including composite sinks for multi-destination output.
///
/// # Examples
///
/// ```rust,ignore
/// use torrust_tracker_deployer_lib::presentation::user_output::{
/// UserOutput, VerbosityLevel, CompositeSink, StandardSink, FileSink
/// };
///
/// // Console + File output
/// let composite = CompositeSink::new(vec![
/// Box::new(StandardSink::default_console()),
/// Box::new(FileSink::new("output.log").unwrap()),
/// ]);
/// let output = UserOutput::with_sink(VerbosityLevel::Normal, Box::new(composite));
/// ```
#[must_use]
pub fn with_sink(verbosity: VerbosityLevel, sink: Box<dyn OutputSink>) -> Self {
Self {
theme: Theme::default(),
verbosity_filter: VerbosityFilter::new(verbosity),
sink,
formatter_override: None,
}
}
/// Internal helper to apply theme to an existing `UserOutput`
fn with_theme_applied(mut self, theme: Theme) -> Self {
self.theme = theme;
self
}
/// Create `UserOutput` with theme and custom writers (for testing)
///
/// This constructor allows full customization including theme and writers,
/// primarily used for testing where output needs to be captured.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel, Theme};
/// use std::io::Cursor;
///
/// let stdout_buf = Vec::new();
/// let stderr_buf = Vec::new();
///
/// let output = UserOutput::with_theme_and_writers(
/// VerbosityLevel::Normal,
/// Theme::plain(),
/// Box::new(Cursor::new(stdout_buf)),
/// Box::new(Cursor::new(stderr_buf)),
/// );
/// ```
#[must_use]
pub fn with_theme_and_writers(
verbosity: VerbosityLevel,
theme: Theme,
stdout_writer: Box<dyn Write + Send + Sync>,
stderr_writer: Box<dyn Write + Send + Sync>,
) -> Self {
Self {
theme,
verbosity_filter: VerbosityFilter::new(verbosity),
sink: Box::new(StandardSink::new(stdout_writer, stderr_writer)),
formatter_override: None,
}
}
/// Create `UserOutput` with an optional formatter override
///
/// This allows applying custom formatting (e.g., JSON, colored output)
/// on top of the theme-based formatting.
///
/// # Examples
///
/// ```rust,ignore
/// use torrust_tracker_deployer_lib::presentation::user_output::{
/// UserOutput, VerbosityLevel, JsonFormatter
/// };
///
/// let mut output = UserOutput::with_formatter_override(
/// VerbosityLevel::Normal,
/// Box::new(JsonFormatter),
/// );
///
/// output.progress("Processing");
/// // Output: {"type":"ProgressMessage","channel":"Stderr","content":"⏳ Processing","timestamp":"..."}
/// ```
#[must_use]
pub fn with_formatter_override(
verbosity: VerbosityLevel,
formatter_override: Box<dyn FormatterOverride>,
) -> Self {
Self {
theme: Theme::default(),
verbosity_filter: VerbosityFilter::new(verbosity),
sink: Box::new(StandardSink::default_console()),
formatter_override: Some(formatter_override),
}
}
/// Create `UserOutput` with theme and optional formatter override
///
/// Combines theme selection with optional formatter override.
///
/// # Examples
///
/// ```rust,ignore
/// use torrust_tracker_deployer_lib::presentation::user_output::{
/// UserOutput, VerbosityLevel, Theme, JsonFormatter
/// };
///
/// let mut output = UserOutput::with_theme_and_formatter(
/// VerbosityLevel::Normal,
/// Theme::plain(),
/// Some(Box::new(JsonFormatter)),
/// );
/// ```
#[must_use]
pub fn with_theme_and_formatter(
verbosity: VerbosityLevel,
theme: Theme,
formatter_override: Option<Box<dyn FormatterOverride>>,
) -> Self {
Self {
theme,
verbosity_filter: VerbosityFilter::new(verbosity),
sink: Box::new(StandardSink::default_console()),
formatter_override,
}
}
/// Create `UserOutput` for testing with custom writers (uses default emoji theme)
///
/// This constructor allows injecting custom writers for testing,
/// enabling output capture and assertion. Uses the default emoji theme.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
/// use std::io::Cursor;
///
/// let stdout_buf = Vec::new();
/// let stderr_buf = Vec::new();
///
/// let output = UserOutput::with_writers(
/// VerbosityLevel::Normal,
/// Box::new(Cursor::new(stdout_buf)),
/// Box::new(Cursor::new(stderr_buf)),
/// );
/// ```
#[must_use]
pub fn with_writers(
verbosity: VerbosityLevel,
stdout_writer: Box<dyn Write + Send + Sync>,
stderr_writer: Box<dyn Write + Send + Sync>,
) -> Self {
Self::with_theme_and_writers(verbosity, Theme::default(), stdout_writer, stderr_writer)
}
/// Write a message to the appropriate channel using trait dispatch
///
/// This is the core method for extensible message handling. It uses the
/// `OutputMessage` trait to determine formatting, verbosity requirements,
/// and channel routing. Messages are routed through the configured sink,
/// enabling multi-destination output.
///
/// # Examples
///
/// ```rust,ignore
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel, ProgressMessage};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.write(&ProgressMessage {
/// text: "Processing...".to_string(),
/// });
/// ```
pub fn write(&mut self, message: &dyn OutputMessage) {
if !self
.verbosity_filter
.should_show(message.required_verbosity())
{
return;
}
let mut formatted = message.format(&self.theme);
// Apply optional format override
if let Some(override_formatter) = &self.formatter_override {
formatted = override_formatter.transform(&formatted, message);
}
// Write through sink
self.sink.write_message(message, &formatted);
}
/// Flush all pending output to stdout and stderr
///
/// **Note**: With the `OutputSink` abstraction, flush behavior depends on the
/// sink implementation. `StandardSink` does not support explicit flushing.
/// This method is kept for API compatibility but is currently a no-op.
///
/// For `StandardSink` (default), writes are typically line-buffered by the OS.
///
/// # Errors
///
/// Currently always returns `Ok(())` as flush is not supported through sinks.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.progress("Starting long operation...");
/// output.flush().expect("Failed to flush output");
/// // Now perform long operation...
/// ```
pub fn flush(&mut self) -> std::io::Result<()> {
// Note: Flush is not supported through the OutputSink abstraction.
// This is a known limitation. StandardSink relies on OS line-buffering.
Ok(())
}
/// Display progress message to stderr (Normal level and above)
///
/// Progress messages go to stderr following cargo/docker patterns.
/// This keeps stdout clean for result data that may be piped.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.progress("Destroying environment...");
/// // Output to stderr: ⏳ Destroying environment...
/// ```
pub fn progress(&mut self, message: &str) {
self.write(&ProgressMessage {
text: message.to_string(),
});
}
/// Display success message to stderr (Normal level and above)
///
/// Success status goes to stderr to allow clean result piping.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.success("Environment destroyed successfully");
/// // Output to stderr: ✅ Environment destroyed successfully
/// ```
pub fn success(&mut self, message: &str) {
self.write(&SuccessMessage {
text: message.to_string(),
});
}
/// Display warning message to stderr (Normal level and above)
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.warn("Infrastructure may already be destroyed");
/// // Output to stderr: ⚠️ Infrastructure may already be destroyed
/// ```
pub fn warn(&mut self, message: &str) {
self.write(&WarningMessage {
text: message.to_string(),
});
}
/// Display error message to stderr (all levels)
///
/// Errors are always shown regardless of verbosity level.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Quiet);
/// output.error("Failed to destroy environment");
/// // Output to stderr: ❌ Failed to destroy environment
/// ```
pub fn error(&mut self, message: &str) {
self.write(&ErrorMessage {
text: message.to_string(),
});
}
/// Output final results to stdout for piping/redirection
///
/// This is where deployment results, configuration summaries, etc. go.
/// Since this goes to stdout, it can be cleanly piped to other commands.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.result("Deployment complete");
/// // Output to stdout: Deployment complete
/// ```
pub fn result(&mut self, message: &str) {
self.write(&ResultMessage {
text: message.to_string(),
});
}
/// Output structured data to stdout (JSON, etc.)
///
/// For machine-readable output that should be piped or processed.
/// This is equivalent to `result()` but exists for semantic clarity.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.data(r#"{"status": "destroyed", "environment": "test"}"#);
/// // Output to stdout: {"status": "destroyed", "environment": "test"}
/// ```
pub fn data(&mut self, data: &str) {
self.result(data);
}
/// Display a blank line to stderr (Normal level and above)
///
/// Used for spacing between sections of output to improve readability.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.success("Configuration template generated");
/// output.blank_line();
/// output.progress("Starting next steps...");
/// ```
pub fn blank_line(&mut self) {
if self.verbosity_filter.should_show_blank_lines() {
// Create a simple message that just outputs a newline
struct BlankLineMessage;
impl OutputMessage for BlankLineMessage {
fn format(&self, _theme: &Theme) -> String {
"\n".to_string()
}
fn required_verbosity(&self) -> VerbosityLevel {
VerbosityLevel::Normal
}
fn channel(&self) -> Channel {
Channel::Stderr
}
fn type_name(&self) -> &'static str {
"BlankLineMessage"
}
}
self.write(&BlankLineMessage);
}
}
/// Display a numbered list of steps to stderr (Normal level and above)
///
/// Useful for displaying sequential instructions or action items.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.steps("Next steps:", &[
/// "Edit the configuration file",
/// "Review the settings",
/// "Run the deploy command",
/// ]);
/// // Output to stderr:
/// // Next steps:
/// // 1. Edit the configuration file
/// // 2. Review the settings
/// // 3. Run the deploy command
/// ```
pub fn steps(&mut self, title: &str, steps: &[&str]) {
self.write(&StepsMessage {
title: title.to_string(),
items: steps.iter().map(|s| (*s).to_string()).collect(),
});
}
/// Display a multi-line information block to stderr (Normal level and above)
///
/// Useful for displaying grouped information or detailed messages.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.info_block("Configuration options:", &[
/// " - username: 'torrust' (default)",
/// " - port: 22 (default SSH port)",
/// " - key_path: path/to/key",
/// ]);
/// // Output to stderr:
/// // Configuration options:
/// // - username: 'torrust' (default)
/// // - port: 22 (default SSH port)
/// // - key_path: path/to/key
/// ```
pub fn info_block(&mut self, title: &str, lines: &[&str]) {
self.write(&InfoBlockMessage {
title: title.to_string(),
lines: lines.iter().map(|s| (*s).to_string()).collect(),
});
}
}
#[cfg(test)]
mod tests {
use super::*;
// These imports are used by nested test modules
#[allow(unused_imports)]
use crate::presentation::user_output::formatters::JsonFormatter;
#[allow(unused_imports)]
use crate::presentation::user_output::sinks::writers::{StderrWriter, StdoutWriter};
#[allow(unused_imports)]
use crate::presentation::user_output::sinks::{CompositeSink, FileSink, TelemetrySink};
#[allow(unused_imports)]
use crate::presentation::user_output::test_support::{self, TestUserOutput, TestWriter};
// ============================================================================
// Type-Safe Writer Wrapper Tests
// ============================================================================
mod type_safe_wrappers {
use super::*;
use std::sync::{Arc, Mutex};
#[test]
fn stdout_writer_should_wrap_writer() {
let buffer = Arc::new(Mutex::new(Vec::new()));
let writer = Box::new(test_support::TestWriter::new(Arc::clone(&buffer)));
let mut stdout = StdoutWriter::new(writer);
stdout.write_line("Test output");
let output = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
assert_eq!(output, "Test output");
}
#[test]
fn stderr_writer_should_wrap_writer() {
let buffer = Arc::new(Mutex::new(Vec::new()));
let writer = Box::new(test_support::TestWriter::new(Arc::clone(&buffer)));
let mut stderr = StderrWriter::new(writer);
stderr.write_line("Test error");
let output = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
assert_eq!(output, "Test error");
}
#[test]
fn stdout_writer_should_write_multiple_lines() {
let buffer = Arc::new(Mutex::new(Vec::new()));
let writer = Box::new(test_support::TestWriter::new(Arc::clone(&buffer)));
let mut stdout = StdoutWriter::new(writer);
stdout.write_line("Line 1\n");
stdout.write_line("Line 2\n");
let output = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
assert_eq!(output, "Line 1\nLine 2\n");
}
#[test]
fn stderr_writer_should_write_multiple_lines() {
let buffer = Arc::new(Mutex::new(Vec::new()));
let writer = Box::new(test_support::TestWriter::new(Arc::clone(&buffer)));
let mut stderr = StderrWriter::new(writer);
stderr.write_line("Error 1\n");
stderr.write_line("Error 2\n");
let output = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
assert_eq!(output, "Error 1\nError 2\n");
}
#[test]
fn type_safe_dispatch_prevents_channel_confusion() {
// This test demonstrates that the type system prevents channel confusion
let stdout_buffer = Arc::new(Mutex::new(Vec::new()));
let stderr_buffer = Arc::new(Mutex::new(Vec::new()));
let stdout_writer = Box::new(test_support::TestWriter::new(Arc::clone(&stdout_buffer)));
let stderr_writer = Box::new(test_support::TestWriter::new(Arc::clone(&stderr_buffer)));
let mut stdout = StdoutWriter::new(stdout_writer);
let mut stderr = StderrWriter::new(stderr_writer);
// Type-safe: These methods can only be called on the correct writer type
stdout.write_line("stdout data");
stderr.write_line("stderr message");
let stdout_output = String::from_utf8(stdout_buffer.lock().unwrap().clone()).unwrap();
let stderr_output = String::from_utf8(stderr_buffer.lock().unwrap().clone()).unwrap();
assert_eq!(stdout_output, "stdout data");
assert_eq!(stderr_output, "stderr message");
// The following would not compile (demonstrating compile-time safety):
// stderr.write_line("this should go to stdout"); // Type mismatch!
// stdout.write_line("this should go to stderr"); // Type mismatch!
}
#[test]
fn user_output_uses_typed_wrappers_internally() {
// This test verifies that UserOutput uses typed wrappers internally
// and that channel routing is type-safe
let mut test_output = test_support::TestUserOutput::new(VerbosityLevel::Normal);
// These calls go through type-safe dispatch
test_output.output.progress("Progress message");
test_output.output.result("Result data");
// Verify correct channel routing via type system
assert!(test_output.stderr().contains("Progress message"));
assert!(test_output.stdout().contains("Result data"));
}
#[test]
fn stdout_writer_writeln_adds_newline() {
let buffer = Arc::new(Mutex::new(Vec::new()));
let writer = Box::new(test_support::TestWriter::new(Arc::clone(&buffer)));
let mut stdout = StdoutWriter::new(writer);
stdout.writeln("Test");
let output = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
assert_eq!(output, "Test\n");
}
#[test]
fn stderr_writer_writeln_adds_newline() {
let buffer = Arc::new(Mutex::new(Vec::new()));
let writer = Box::new(test_support::TestWriter::new(Arc::clone(&buffer)));
let mut stderr = StderrWriter::new(writer);
stderr.writeln("Error");
let output = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
assert_eq!(output, "Error\n");
}
}
// ============================================================================
// Theme Tests
// ============================================================================
mod theme {
use super::*;
#[test]
fn it_should_create_emoji_theme_with_correct_symbols() {
let theme = Theme::emoji();
assert_eq!(theme.progress_symbol(), "⏳");
assert_eq!(theme.success_symbol(), "✅");
assert_eq!(theme.warning_symbol(), "⚠️");
assert_eq!(theme.error_symbol(), "❌");
}
#[test]
fn it_should_create_plain_theme_with_text_labels() {
let theme = Theme::plain();
assert_eq!(theme.progress_symbol(), "[INFO]");
assert_eq!(theme.success_symbol(), "[OK]");
assert_eq!(theme.warning_symbol(), "[WARN]");
assert_eq!(theme.error_symbol(), "[ERROR]");
}
#[test]
fn it_should_create_ascii_theme_with_ascii_characters() {
let theme = Theme::ascii();
assert_eq!(theme.progress_symbol(), "=>");
assert_eq!(theme.success_symbol(), "[+]");
assert_eq!(theme.warning_symbol(), "[!]");
assert_eq!(theme.error_symbol(), "[x]");
}
#[test]
fn it_should_use_emoji_theme_as_default() {
let theme = Theme::default();
let emoji_theme = Theme::emoji();
assert_eq!(theme, emoji_theme);
}
#[test]
fn it_should_support_clone() {
let theme = Theme::plain();
let cloned = theme.clone();
assert_eq!(theme, cloned);
}
#[test]
fn it_should_support_equality_comparison() {
let theme1 = Theme::emoji();
let theme2 = Theme::emoji();
let theme3 = Theme::plain();
assert_eq!(theme1, theme2);
assert_ne!(theme1, theme3);
}
#[test]
fn it_should_support_debug_formatting() {
let theme = Theme::emoji();
let debug_output = format!("{theme:?}");
assert!(debug_output.contains("Theme"));
}
}
// ============================================================================
// UserOutput Tests - Parameterized Tests
// ============================================================================
//
// These tests use rstest for parameterized testing to reduce duplication
// and make the test matrix clear and maintainable.
//
// Test Matrix:
// Message Type | Symbol | Min Verbosity | Channel | Always Shown
// -------------|--------|---------------|---------|-------------
// progress | ⏳ | Normal | stderr | No
// success | ✅ | Normal | stderr | No
// warning | ⚠️ | Normal | stderr | No
// error | ❌ | Quiet | stderr | Yes
// result | (none) | Quiet | stdout | Yes
// data | (none) | Quiet | stdout | Yes
mod parameterized_tests {
use super::*;
use rstest::rstest;
/// Test that each message type routes to the correct output channel
///
/// Verifies stdout vs stderr routing for all message types.
/// This replaces 5 individual channel routing tests with one parameterized test.
#[rstest]
#[case("progress", "⏳ Test message\n", VerbosityLevel::Normal, "stderr")]
#[case("success", "✅ Test message\n", VerbosityLevel::Normal, "stderr")]
#[case("warning", "⚠️ Test message\n", VerbosityLevel::Normal, "stderr")]
#[case("error", "❌ Test message\n", VerbosityLevel::Normal, "stderr")]
#[case("result", "Test message\n", VerbosityLevel::Normal, "stdout")]
fn it_should_route_message_to_correct_channel(
#[case] method: &str,
#[case] expected_output: &str,
#[case] verbosity: VerbosityLevel,
#[case] expected_channel: &str,
) {
let mut test_output = test_support::TestUserOutput::new(verbosity);
// Call the appropriate method
match method {
"progress" => test_output.output.progress("Test message"),
"success" => test_output.output.success("Test message"),
"warning" => test_output.output.warn("Test message"),
"error" => test_output.output.error("Test message"),
"result" => test_output.output.result("Test message"),
_ => panic!("Unknown method: {method}"),
}
// Verify output went to the correct channel
match expected_channel {
"stdout" => {
assert_eq!(test_output.stdout(), expected_output);
assert_eq!(test_output.stderr(), "");
}
"stderr" => {
assert_eq!(test_output.stderr(), expected_output);
assert_eq!(test_output.stdout(), "");
}
_ => panic!("Unknown channel: {expected_channel}"),
}
}
/// Test that normal-level messages respect verbosity settings
///
/// Progress, success, and warning messages should only appear at Normal or higher.
/// This replaces 3 individual verbosity tests with one parameterized test.
#[rstest]
#[case("progress", VerbosityLevel::Quiet, false)]
#[case("progress", VerbosityLevel::Normal, true)]
#[case("progress", VerbosityLevel::Verbose, true)]
#[case("success", VerbosityLevel::Quiet, false)]
#[case("success", VerbosityLevel::Normal, true)]
#[case("success", VerbosityLevel::Verbose, true)]
#[case("warning", VerbosityLevel::Quiet, false)]
#[case("warning", VerbosityLevel::Normal, true)]
#[case("warning", VerbosityLevel::Verbose, true)]
fn it_should_respect_verbosity_for_normal_level_messages(
#[case] method: &str,
#[case] verbosity: VerbosityLevel,
#[case] should_show: bool,
) {
let mut test_output = test_support::TestUserOutput::new(verbosity);
match method {
"progress" => test_output.output.progress("Test"),
"success" => test_output.output.success("Test"),
"warning" => test_output.output.warn("Test"),
_ => panic!("Unknown method: {method}"),
}
if should_show {
assert!(!test_output.stderr().is_empty());
} else {
assert_eq!(test_output.stderr(), "");
}
}
/// Test that error messages are always shown regardless of verbosity
///
/// Errors are critical and must be shown at all verbosity levels.
#[rstest]
#[case(VerbosityLevel::Quiet)]
#[case(VerbosityLevel::Normal)]
#[case(VerbosityLevel::Verbose)]
#[case(VerbosityLevel::VeryVerbose)]
#[case(VerbosityLevel::Debug)]
fn it_should_always_show_errors_at_all_verbosity_levels(#[case] verbosity: VerbosityLevel) {
let mut test_output = test_support::TestUserOutput::new(verbosity);
test_output.output.error("Critical error");
assert!(!test_output.stderr().is_empty());
assert!(test_output.stderr().contains("Critical error"));
}
/// Test that result messages are always shown at all verbosity levels
///
/// Results are final outputs and must be shown at all verbosity levels.
#[rstest]
#[case(VerbosityLevel::Quiet)]
#[case(VerbosityLevel::Normal)]
#[case(VerbosityLevel::Verbose)]
#[case(VerbosityLevel::VeryVerbose)]
#[case(VerbosityLevel::Debug)]
fn it_should_always_show_results_at_all_verbosity_levels(
#[case] verbosity: VerbosityLevel,
) {
let mut test_output = test_support::TestUserOutput::new(verbosity);
test_output.output.result("Result data");
assert_eq!(test_output.stdout(), "Result data\n");
assert_eq!(test_output.stderr(), "");
}
}
// ============================================================================
// UserOutput Tests - Basic Output (Non-parameterized)
// ============================================================================
//
// These tests cover specific functionality not included in parameterized tests:
#[test]
fn it_should_write_data_to_stdout() {
let mut test_output = test_support::TestUserOutput::new(VerbosityLevel::Normal);
test_output.output.data(r#"{"status": "destroyed"}"#);
// Verify message went to stdout
assert_eq!(test_output.stdout(), "{\"status\": \"destroyed\"}\n");
// Verify stderr is empty
assert_eq!(test_output.stderr(), "");
}
#[test]
fn it_should_use_normal_as_default_verbosity() {
let default = VerbosityLevel::default();
assert_eq!(default, VerbosityLevel::Normal);
}
#[test]
fn it_should_order_verbosity_levels_correctly() {
assert!(VerbosityLevel::Quiet < VerbosityLevel::Normal);
assert!(VerbosityLevel::Normal < VerbosityLevel::Verbose);
assert!(VerbosityLevel::Verbose < VerbosityLevel::VeryVerbose);
assert!(VerbosityLevel::VeryVerbose < VerbosityLevel::Debug);
}
#[test]
fn it_should_support_equality_comparison() {
assert_eq!(VerbosityLevel::Normal, VerbosityLevel::Normal);
assert_ne!(VerbosityLevel::Normal, VerbosityLevel::Verbose);
}
#[test]
fn it_should_support_ordering_comparison() {
let normal = VerbosityLevel::Normal;
assert!(normal >= VerbosityLevel::Quiet);
assert!(normal >= VerbosityLevel::Normal);
assert!(normal < VerbosityLevel::Verbose);
}
#[test]
fn it_should_write_blank_line_to_stderr() {
let mut test_output = test_support::TestUserOutput::new(VerbosityLevel::Normal);
test_output.output.blank_line();
// Verify blank line went to stderr
assert_eq!(test_output.stderr(), "\n");
// Verify stdout is empty
assert_eq!(test_output.stdout(), "");
}
#[test]
fn it_should_not_write_blank_line_at_quiet_level() {
let mut test_output = test_support::TestUserOutput::new(VerbosityLevel::Quiet);
test_output.output.blank_line();
// Verify no output at Quiet level
assert_eq!(test_output.stderr(), "");
}
#[test]
fn it_should_write_steps_to_stderr() {
let mut test_output = test_support::TestUserOutput::new(VerbosityLevel::Normal);
test_output.output.steps(
"Next steps:",
&[
"Edit the configuration file",
"Review the settings",
"Run the deploy command",
],
);
// Verify steps went to stderr with correct formatting
assert_eq!(
test_output.stderr(),
"Next steps:\n1. Edit the configuration file\n2. Review the settings\n3. Run the deploy command\n"
);
// Verify stdout is empty
assert_eq!(test_output.stdout(), "");
}
#[test]
fn it_should_not_write_steps_at_quiet_level() {
let mut test_output = test_support::TestUserOutput::new(VerbosityLevel::Quiet);
test_output
.output
.steps("Next steps:", &["Step 1", "Step 2"]);
// Verify no output at Quiet level
assert_eq!(test_output.stderr(), "");
}
#[test]
fn it_should_write_info_block_to_stderr() {
let mut test_output = test_support::TestUserOutput::new(VerbosityLevel::Normal);
test_output.output.info_block(
"Configuration options:",
&[
" - username: 'torrust' (default)",
" - port: 22 (default SSH port)",
],
);
// Verify info block went to stderr
assert_eq!(
test_output.stderr(),
"Configuration options:\n - username: 'torrust' (default)\n - port: 22 (default SSH port)\n"
);
// Verify stdout is empty
assert_eq!(test_output.stdout(), "");
}
#[test]
fn it_should_not_write_info_block_at_quiet_level() {
let mut test_output = test_support::TestUserOutput::new(VerbosityLevel::Quiet);
test_output
.output
.info_block("Info:", &["Line 1", "Line 2"]);
// Verify no output at Quiet level
assert_eq!(test_output.stderr(), "");
}
// VerbosityFilter tests
mod verbosity_filter {
use super::super::*;
#[test]
fn it_should_show_progress_at_normal_level() {
let filter = VerbosityFilter::new(VerbosityLevel::Normal);
assert!(filter.should_show_progress());
}
#[test]
fn it_should_not_show_progress_at_quiet_level() {
let filter = VerbosityFilter::new(VerbosityLevel::Quiet);
assert!(!filter.should_show_progress());
}
#[test]
fn it_should_show_progress_at_verbose_level() {
let filter = VerbosityFilter::new(VerbosityLevel::Verbose);
assert!(filter.should_show_progress());
}