Tidy up managed_queue example.

This commit is contained in:
Sergio Benitez 2017-04-14 14:53:41 -07:00
parent b4586f62ee
commit 8d14cd571c
2 changed files with 30 additions and 42 deletions

View File

@ -4,6 +4,8 @@
extern crate crossbeam; extern crate crossbeam;
extern crate rocket; extern crate rocket;
#[cfg(test)] mod tests;
use crossbeam::sync::MsQueue; use crossbeam::sync::MsQueue;
use rocket::State; use rocket::State;
@ -14,55 +16,23 @@ struct Event {
struct LogChannel(MsQueue<Event>); struct LogChannel(MsQueue<Event>);
#[get("/push?<event>")] #[put("/push?<event>")]
fn push(event: Event, queue: State<LogChannel>) -> &'static str { fn push(event: Event, queue: State<LogChannel>) {
queue.0.push(event); queue.0.push(event);
"got it"
} }
#[get("/pop")] #[get("/pop")]
fn pop(queue: State<LogChannel>) -> String { fn pop(queue: State<LogChannel>) -> String {
let e = queue.0.pop(); let queue = &queue.0;
e.description queue.pop().description
} }
// Use with: curl http://<rocket ip>:8000/test?foo=bar fn rocket() -> rocket::Rocket {
rocket::ignite()
.mount("/", routes![push, pop])
.manage(LogChannel(MsQueue::new()))
}
fn main() { fn main() {
let q:MsQueue<Event> = MsQueue::new(); rocket().launch();
rocket::ignite()
.mount("/", routes![push,pop])
.manage(LogChannel(q))
.launch();
} }
#[cfg(test)]
mod test {
use super::rocket;
use rocket::testing::MockRequest;
use rocket::http::Status;
use rocket::http::Method::*;
use crossbeam::sync::MsQueue;
use std::{thread, time};
use super::LogChannel;
use super::Event;
#[test]
fn test_get() {
let q: MsQueue<Event> = MsQueue::new();
let rocket = rocket::ignite().manage(LogChannel(q)).mount("/", routes![super::push, super::pop]);
let mut req = MockRequest::new(Get, "/push?description=test1");
let response = req.dispatch_with(&rocket);
assert_eq!(response.status(), Status::Ok);
let ten_millis = time::Duration::from_millis(10);
thread::sleep(ten_millis);
let mut req = MockRequest::new(Get, "/pop");
let mut response = req.dispatch_with(&rocket);
let body_str = response.body().and_then(|body| body.into_string());
assert_eq!(body_str, Some("test1".to_string()));
}
}

View File

@ -0,0 +1,18 @@
use super::rocket;
use rocket::testing::MockRequest;
use rocket::http::Status;
use rocket::http::Method::*;
#[test]
fn test_push_pop() {
let rocket = rocket();
let mut req = MockRequest::new(Put, "/push?description=test1");
let response = req.dispatch_with(&rocket);
assert_eq!(response.status(), Status::Ok);
let mut req = MockRequest::new(Get, "/pop");
let mut response = req.dispatch_with(&rocket);
assert_eq!(response.body_string(), Some("test1".to_string()));
}