Skip to content

Commit

Permalink
Print buffer test tool (Philipp-M#11)
Browse files Browse the repository at this point in the history
An additional test helper to print snapshots on demand
  • Loading branch information
zoechi authored Feb 7, 2024
1 parent 2f8f29b commit 7d52e43
Show file tree
Hide file tree
Showing 7 changed files with 116 additions and 22 deletions.
54 changes: 52 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 10 additions & 10 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,25 @@ edition = "2021"
[dependencies]
# xilem_core = { path = "../xilem/xilem/crates/xilem_core" }
xilem_core = { git = "https://github.com/Philipp-M/xilem.git", branch = "personal" }
anyhow = "1.0"
bitflags = "2.4"
crossterm = "0.27"
directories = "5.0"
kurbo = "0.10"
futures-task = "0.3"
futures-util = "0.3"
ratatui = "0.26"
tokio = { version = "1.35", features = ["full"] }
anyhow = "1.0"
tracing = "0.1.40"
tracing = "0.1"
tracing-appender = "0.2"
tracing-subscriber = "0.3"
kurbo = "0.10.4"
# update this when a new release occurs
ratatui = "0.26"
bitflags = "2.4.2"
unicode-segmentation = "1.10.1"
unicode-width = "0.1.11"
unicode-segmentation = "1.11"
unicode-width = "0.1"

[dev-dependencies]
futures = "0.3"
insta = "1.34.0"
rand = "0.8.5"
insta = "1.34"
rand = "0.8"

[lints.clippy]
dbg_macro = "warn"
6 changes: 4 additions & 2 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,13 @@ use crossterm::{
};

use crossterm::event::{poll, read, Event as CxEvent, KeyCode, KeyEvent};
use directories::ProjectDirs;
use ratatui::Terminal;

#[cfg(not(test))]
use std::io::stdout;

use std::{collections::HashSet, path::PathBuf, sync::Arc, time::Duration};
use std::{collections::HashSet, sync::Arc, time::Duration};
use tokio::runtime::Runtime;
use tracing_subscriber::{fmt::writer::MakeWriterExt, layer::SubscriberExt, Registry};
use xilem_core::{AsyncWake, Id, IdPath, MessageResult};
Expand All @@ -40,7 +41,8 @@ use std::io::{Stdout, Write};

// TODO less hardcoding and cross-platform support
fn setup_logging(log_level: tracing::Level) -> Result<tracing_appender::non_blocking::WorkerGuard> {
let cache_dir = PathBuf::from(std::env::var_os("HOME").unwrap()).join(".cache/trui");
let proj_dirs = ProjectDirs::from("", "", "trui").expect("Opening cache directory");
let cache_dir = proj_dirs.cache_dir();
let tracing_file_appender = tracing_appender::rolling::never(cache_dir, "trui.log");
let (tracing_file_writer, guard) = tracing_appender::non_blocking(tracing_file_appender);

Expand Down
49 changes: 45 additions & 4 deletions src/test_helper.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
use std::env;
use std::io::stdout;
use std::marker::PhantomData;
use std::sync::Arc;

use crossterm::cursor::MoveToNextLine;
use crossterm::execute;
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use ratatui::backend::TestBackend;
use ratatui::layout::Size;
use ratatui::prelude::Buffer;
use ratatui::prelude::*;
use ratatui::style::Style;
use ratatui::Terminal;
use ratatui::{Terminal, TerminalOptions, Viewport};
use tokio::sync::mpsc;
use xilem_core::MessageResult;

Expand Down Expand Up @@ -49,14 +54,17 @@ pub fn render_view<T: Send + 'static>(

event_tx.blocking_send(Event::Quit).unwrap();
let _ = join_handle.join().unwrap();

print_buffer(&buffer).unwrap();

buffer
}

/// Render a widget and return the terminal to check the generated output
///
/// * `buffer_size` - The terminal output buffer is set to that size.
/// * `sut` - (system under test) The widget to render.
pub fn render_widget(buffer_size: Size, sut: &mut impl Widget) -> Terminal<TestBackend> {
pub fn render_widget(buffer_size: Size, sut: &mut impl Widget) -> Buffer {
let mut messages = vec![];
let mut cx_state = CxState::new(&mut messages);
let mut widget_state = WidgetState::new();
Expand Down Expand Up @@ -89,7 +97,10 @@ pub fn render_widget(buffer_size: Size, sut: &mut impl Widget) -> Terminal<TestB
sut.paint(&mut paint_cx);
terminal.flush().unwrap();

terminal
let buffer = terminal.backend().buffer().clone();
print_buffer(&buffer).unwrap();

buffer
}

/// This widget provides access to the terminal output of its children
Expand Down Expand Up @@ -190,3 +201,33 @@ impl Widget for DebugWidget {
self.content.lifecycle(cx, event);
}
}

/// Utility for visual snapshot test debugging
///
/// If the environment variable `DEBUG_SNAPSHOT` is set when tests are run, the terminal buffer is
/// dumped to stdout.
///
/// ```sh
/// DEBUG_SNAPSHOT=1 cargo test --lib -- --nocapture --test simple_block_test
/// ```
///
/// !!! The normal test output frequently interferes which results in scrambled output, especially
/// when multiple tests are run at once.
/// Running it multiple times might usually leads to good output (for now, with small widget output)
pub fn print_buffer(buffer: &Buffer) -> std::io::Result<()> {
if env::var("DEBUG_SNAPSHOT").is_ok() {
enable_raw_mode()?;
execute!(stdout(), MoveToNextLine(0))?;
let mut terminal = Terminal::with_options(
CrosstermBackend::new(stdout()),
TerminalOptions {
viewport: Viewport::Inline(buffer.area.height),
},
)?;
terminal.current_buffer_mut().clone_from(buffer);
terminal.flush()?;
execute!(stdout(), MoveToNextLine(0))?;
disable_raw_mode()?;
};
Ok(())
}
2 changes: 1 addition & 1 deletion src/view/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ mod tests {

#[test]
fn simple_block_test() {
let sut = Arc::new(block("some text"));
let sut = Arc::new(block("some text".fg(Color::Cyan)));
let buffer = render_view(
Size {
width: 15,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Buffer {
" ",
],
styles: [
x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
x: 0, y: 0, fg: Cyan, bg: Reset, underline: Reset, modifier: NONE,
x: 9, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
]
}
4 changes: 2 additions & 2 deletions src/widget/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,13 +234,13 @@ mod tests {
false,
);

let terminal = render_widget(
let buffer = render_widget(
Size {
width: 15,
height: 5,
},
&mut sut,
);
insta::assert_debug_snapshot!(terminal.backend().buffer());
insta::assert_debug_snapshot!(buffer);
}
}

0 comments on commit 7d52e43

Please sign in to comment.