mirror of
https://github.com/orhun/systeroid
synced 2024-10-06 23:59:10 +00:00
test(event): add tests to tui event module
This commit is contained in:
parent
9017aabbad
commit
5bc968ee28
|
@ -1,5 +1,5 @@
|
|||
use std::io;
|
||||
use std::sync::mpsc::{self, Receiver, RecvError};
|
||||
use std::sync::mpsc::{self, Receiver, RecvError, Sender};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use termion::event::Key;
|
||||
|
@ -17,6 +17,9 @@ pub enum Event {
|
|||
/// [`Event`] handler.
|
||||
#[derive(Debug)]
|
||||
pub struct EventHandler {
|
||||
/// Sender channel for the events.
|
||||
#[allow(dead_code)]
|
||||
sender: Sender<Event>,
|
||||
/// Receiver channel for the events.
|
||||
receiver: Receiver<Event>,
|
||||
}
|
||||
|
@ -36,11 +39,14 @@ impl EventHandler {
|
|||
.expect("failed to send key input event");
|
||||
});
|
||||
}
|
||||
thread::spawn(move || loop {
|
||||
sender.send(Event::Tick).expect("failed to send tick event");
|
||||
thread::sleep(tick_rate);
|
||||
});
|
||||
Self { receiver }
|
||||
{
|
||||
let sender = sender.clone();
|
||||
thread::spawn(move || loop {
|
||||
sender.send(Event::Tick).expect("failed to send tick event");
|
||||
thread::sleep(tick_rate);
|
||||
});
|
||||
}
|
||||
Self { sender, receiver }
|
||||
}
|
||||
|
||||
/// Receives the next event from the channel.
|
||||
|
@ -48,3 +54,39 @@ impl EventHandler {
|
|||
self.receiver.recv()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::char;
|
||||
use std::time::Instant;
|
||||
|
||||
const TICK_RATE_MS: u64 = 100;
|
||||
|
||||
#[test]
|
||||
fn test_event() {
|
||||
let start_time = Instant::now();
|
||||
let event_handler = EventHandler::new(TICK_RATE_MS);
|
||||
let mut tick_count = 0;
|
||||
for i in 0..10 {
|
||||
let sender = event_handler.sender.clone();
|
||||
thread::spawn(move || {
|
||||
let key = Key::Char(char::from_digit(i, 10).unwrap_or('9'));
|
||||
let event = Event::KeyPress(key);
|
||||
sender.send(event).unwrap();
|
||||
});
|
||||
match event_handler.next().unwrap() {
|
||||
Event::KeyPress(key) => {
|
||||
if key == Key::Char('9') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Event::Tick => {
|
||||
thread::sleep(Duration::from_millis(TICK_RATE_MS));
|
||||
tick_count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(start_time.elapsed() > Duration::from_millis(tick_count * TICK_RATE_MS));
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue