Make handler.rs generic for anything that implements Read+Write, add unittest taking advantage of that.
Also, it'll work now for things other than UnixStreams, such as TcpStreams
This commit is contained in:
+39
-6
@@ -1,18 +1,17 @@
|
||||
use crate::repository::PasswordDirectory;
|
||||
use common::request::Request;
|
||||
use std::io::{Error, Write};
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::io::{Error, Read, Write};
|
||||
|
||||
pub const RESPONSE_NO: [u8; 4] = [0x0, 0x2, b'N', b'O'];
|
||||
pub const RESPONSE_OK: [u8; 4] = [0x0, 0x2, b'O', b'K'];
|
||||
|
||||
pub struct Handler {
|
||||
stream: UnixStream,
|
||||
pub struct Handler<S: Read + Write> {
|
||||
stream: S,
|
||||
handler: PasswordDirectory,
|
||||
}
|
||||
|
||||
impl Handler {
|
||||
pub fn new(stream: UnixStream, handler: PasswordDirectory) -> Handler {
|
||||
impl<S: Read + Write> Handler<S> {
|
||||
pub fn new(stream: S, handler: PasswordDirectory) -> Handler<S> {
|
||||
Handler { stream, handler }
|
||||
}
|
||||
|
||||
@@ -35,3 +34,37 @@ impl Handler {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::handler::{Handler, RESPONSE_OK};
|
||||
use crate::repository::PasswordDirectory;
|
||||
use common::request::Request;
|
||||
use std::io::Cursor;
|
||||
|
||||
const TEST_PATH: &str = "./test_passwords";
|
||||
|
||||
#[test]
|
||||
fn it_communicates_ok() {
|
||||
let repository = PasswordDirectory::new(TEST_PATH);
|
||||
|
||||
let request = Request::new("bp", "some-rad-password", "ignore-this", "also-ignore-this");
|
||||
|
||||
let mut cursor = Cursor::new(Vec::new());
|
||||
|
||||
request.write_to_stream(&mut cursor).unwrap();
|
||||
|
||||
// Figure out where the response should end up
|
||||
let response_position: usize = cursor.position().try_into().unwrap();
|
||||
|
||||
// Rewind and have the handler deal with the request
|
||||
cursor.set_position(0);
|
||||
Handler::new(&mut cursor, repository).handle_client();
|
||||
|
||||
// Extract the response, which should come after the
|
||||
// request in the cursor buffer
|
||||
let response = cursor.into_inner().split_off(response_position);
|
||||
|
||||
assert_eq!(response, RESPONSE_OK);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user