morethantext/src/session2.rs

126 lines
3.1 KiB
Rust
Raw Normal View History

use crate::{
Field,
queue::Message,
};
use std::{
sync::mpsc::{channel, Receiver, Sender},
thread::spawn,
};
use uuid::Uuid;
#[derive(Clone)]
pub enum SessionMessage {
New(Field),
Validate(Option<Field>),
}
impl From<Option<Field>> for SessionMessage {
fn from(value: Option<Field>) -> Self {
SessionMessage::Validate(value)
}
}
#[cfg(test)]
pub mod crete_session_message {
use super::*;
fn create_session_new() -> SessionMessage {
SessionMessage::New(Uuid::new_v4().into())
}
}
#[cfg(test)]
mod sessionmessages {
use super::*;
#[test]
fn from_optional_field() {
let text = "afield";
let id = Some(text.into());
match id.into() {
SessionMessage::Validate(result) => {
match result {
Some(data) => {
match data {
Field::Static(output) => assert_eq!(output, text),
_ => unreachable!("should have returned static text"),
}
},
None => unreachable!("shoulf have returned data"),
}
},
_ => unreachable!("should have been a vaqlidate"),
}
}
}
struct Session {
tx: Sender<Message>,
rx: Receiver<Message>,
}
impl Session {
fn new(tx: Sender<Message>, rx: Receiver<Message>) -> Self {
Self {
tx: tx,
rx: rx,
}
}
fn start(queue_tx: Sender<Message>) {
spawn(move || {
let (tx, rx) = channel();
let session = Session::new(queue_tx.clone(), rx);
queue_tx.send(tx.clone().into()).unwrap();
session.listen();
});
}
fn listen(&self) {
loop {
self.rx.recv().unwrap();
let res = Uuid::nil();
self.tx.send(SessionMessage::New(res.into()).into());
}
}
}
#[cfg(test)]
mod sessions {
use std::time::Duration;
use super::*;
#[test]
fn gets_registered() {
let (tx, rx) = channel();
Session::start(tx);
match rx.recv().unwrap() {
Message::Register(_) => {},
_ => unreachable!("should register the service"),
}
}
#[test]
fn validate_none_returns_new_id() {
let (tx, rx) = channel();
let sender: Sender<Message>;
Session::start(tx);
match rx.recv().unwrap() {
Message::Register(result) => sender = result,
_ => unreachable!("should register the service"),
}
let data: Option<Field> = None;
let req: SessionMessage = data.into();
sender.send(req.into()).unwrap();
match rx.recv_timeout(Duration::from_millis(500)).unwrap() {
Message::SessMsg(data) => {
match data {
SessionMessage::New(_) => {},
_ => unreachable!("should have been a new session"),
}
},
_ => unreachable!("should have been a session message response"),
}
}
}