From 4d70463e46b75c75dda3797a459c0f4c8621c58c Mon Sep 17 00:00:00 2001 From: Barry Pederson Date: Sun, 3 Nov 2024 12:19:02 -0800 Subject: [PATCH] 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 --- server/src/handler.rs | 45 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/server/src/handler.rs b/server/src/handler.rs index 49dc409..9121022 100644 --- a/server/src/handler.rs +++ b/server/src/handler.rs @@ -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 { + stream: S, handler: PasswordDirectory, } -impl Handler { - pub fn new(stream: UnixStream, handler: PasswordDirectory) -> Handler { +impl Handler { + pub fn new(stream: S, handler: PasswordDirectory) -> Handler { 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); + } +}