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 rocket;
#[cfg(test)] mod tests;
use crossbeam::sync::MsQueue;
use rocket::State;
@ -14,55 +16,23 @@ struct Event {
struct LogChannel(MsQueue<Event>);
#[get("/push?<event>")]
fn push(event: Event, queue: State<LogChannel>) -> &'static str {
#[put("/push?<event>")]
fn push(event: Event, queue: State<LogChannel>) {
queue.0.push(event);
"got it"
}
#[get("/pop")]
fn pop(queue: State<LogChannel>) -> String {
let e = queue.0.pop();
e.description
let queue = &queue.0;
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() {
let q:MsQueue<Event> = MsQueue::new();
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()));
}
rocket().launch();
}

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()));
}