mirror of
https://github.com/actix/actix-web.git
synced 2024-11-18 07:35:36 +00:00
more tests
This commit is contained in:
parent
26989f5591
commit
5699af9795
10 changed files with 173 additions and 9 deletions
4
cov.sh
Normal file
4
cov.sh
Normal file
|
@ -0,0 +1,4 @@
|
|||
#!/bin/bash
|
||||
|
||||
for file in target/debug/actix_web-*[^\.d]; do mkdir -p "target/cov/$(basename $file)"; /usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --verify "target/cov/$(basename $file)" "$file"; done &&
|
||||
for file in target/debug/test_*[^\.d]; do mkdir -p "target/cov/$(basename $file)"; /usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --verify "target/cov/$(basename $file)" "$file"; done
|
|
@ -6,13 +6,13 @@ extern crate env_logger;
|
|||
use actix_web::*;
|
||||
|
||||
/// somple handle
|
||||
fn index(req: &mut HttpRequest, payload: Payload, state: &()) -> HttpResponse {
|
||||
fn index(req: &mut HttpRequest, _payload: Payload, state: &()) -> HttpResponse {
|
||||
println!("{:?}", req);
|
||||
httpcodes::HTTPOk.into()
|
||||
}
|
||||
|
||||
/// handle with path parameters like `/name/{name}/`
|
||||
fn with_param(req: &mut HttpRequest, payload: Payload, state: &()) -> HttpResponse {
|
||||
fn with_param(req: &mut HttpRequest, _payload: Payload, state: &()) -> HttpResponse {
|
||||
println!("{:?}", req);
|
||||
|
||||
HttpResponse::builder(StatusCode::OK)
|
||||
|
|
|
@ -19,7 +19,7 @@ impl Route for MyWebSocket {
|
|||
fn request(req: &mut HttpRequest,
|
||||
payload: Payload, ctx: &mut HttpContext<Self>) -> RouteResult<Self>
|
||||
{
|
||||
let resp = ws::handshake(&req)?;
|
||||
let resp = ws::handshake(req)?;
|
||||
ctx.start(resp);
|
||||
ctx.add_stream(ws::WsStream::new(payload));
|
||||
Reply::async(MyWebSocket)
|
||||
|
|
|
@ -107,6 +107,7 @@ impl HttpResponse {
|
|||
|
||||
/// The `error` which is responsible for this response
|
||||
#[inline]
|
||||
#[cfg_attr(feature="cargo-clippy", allow(borrowed_box))]
|
||||
pub fn error(&self) -> Option<&Box<Error>> {
|
||||
self.error.as_ref()
|
||||
}
|
||||
|
|
|
@ -197,7 +197,7 @@ impl<'a> Iterator for FormatParser<'a> {
|
|||
match chr.unwrap() {
|
||||
// Finished parsing, parse buffer.
|
||||
'}' => break,
|
||||
c => self.object_buffer.push(c.clone())
|
||||
c => self.object_buffer.push(c)
|
||||
}
|
||||
|
||||
chr = self.chars.next();
|
||||
|
|
|
@ -98,7 +98,7 @@ impl<A, S> RouteHandler<S> for RouteFactory<A, S>
|
|||
|
||||
// handle EXPECT header
|
||||
if req.headers().contains_key(header::EXPECT) {
|
||||
if let Err(resp) = A::expect(&req, &mut ctx) {
|
||||
if let Err(resp) = A::expect(req, &mut ctx) {
|
||||
return Task::reply(resp)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -46,7 +46,7 @@ impl<T, A, H> HttpServer<T, A, H> where H: HttpHandler
|
|||
{
|
||||
/// Create new http server with vec of http handlers
|
||||
pub fn new<U: IntoIterator<Item=H>>(handler: U) -> Self {
|
||||
let apps: Vec<_> = handler.into_iter().map(|h| h.into()).collect();
|
||||
let apps: Vec<_> = handler.into_iter().collect();
|
||||
|
||||
HttpServer {h: Rc::new(apps),
|
||||
io: PhantomData,
|
||||
|
|
101
src/ws.rs
101
src/ws.rs
|
@ -329,3 +329,104 @@ impl WsWriter {
|
|||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use http::{Method, HeaderMap, StatusCode, Uri, Version, HttpTryFrom, header};
|
||||
use super::{HttpRequest, SEC_WEBSOCKET_VERSION, SEC_WEBSOCKET_KEY, handshake};
|
||||
|
||||
#[test]
|
||||
fn test_handshake() {
|
||||
let req = HttpRequest::new(Method::POST, Uri::try_from("/").unwrap(),
|
||||
Version::HTTP_11, HeaderMap::new());
|
||||
match handshake(&req) {
|
||||
Err(err) => assert_eq!(err.status(), StatusCode::METHOD_NOT_ALLOWED),
|
||||
_ => panic!("should not happen"),
|
||||
}
|
||||
|
||||
let req = HttpRequest::new(Method::GET, Uri::try_from("/").unwrap(),
|
||||
Version::HTTP_11, HeaderMap::new());
|
||||
match handshake(&req) {
|
||||
Err(err) => assert_eq!(err.status(), StatusCode::METHOD_NOT_ALLOWED),
|
||||
_ => panic!("should not happen"),
|
||||
}
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(header::UPGRADE,
|
||||
header::HeaderValue::from_static("test"));
|
||||
let req = HttpRequest::new(Method::GET, Uri::try_from("/").unwrap(),
|
||||
Version::HTTP_11, headers);
|
||||
match handshake(&req) {
|
||||
Err(err) => assert_eq!(err.status(), StatusCode::METHOD_NOT_ALLOWED),
|
||||
_ => panic!("should not happen"),
|
||||
}
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(header::UPGRADE,
|
||||
header::HeaderValue::from_static("websocket"));
|
||||
let req = HttpRequest::new(Method::GET, Uri::try_from("/").unwrap(),
|
||||
Version::HTTP_11, headers);
|
||||
match handshake(&req) {
|
||||
Err(err) => assert_eq!(err.status(), StatusCode::BAD_REQUEST),
|
||||
_ => panic!("should not happen"),
|
||||
}
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(header::UPGRADE,
|
||||
header::HeaderValue::from_static("websocket"));
|
||||
headers.insert(header::CONNECTION,
|
||||
header::HeaderValue::from_static("upgrade"));
|
||||
let req = HttpRequest::new(Method::GET, Uri::try_from("/").unwrap(),
|
||||
Version::HTTP_11, headers);
|
||||
match handshake(&req) {
|
||||
Err(err) => assert_eq!(err.status(), StatusCode::BAD_REQUEST),
|
||||
_ => panic!("should not happen"),
|
||||
}
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(header::UPGRADE,
|
||||
header::HeaderValue::from_static("websocket"));
|
||||
headers.insert(header::CONNECTION,
|
||||
header::HeaderValue::from_static("upgrade"));
|
||||
headers.insert(SEC_WEBSOCKET_VERSION,
|
||||
header::HeaderValue::from_static("5"));
|
||||
let req = HttpRequest::new(Method::GET, Uri::try_from("/").unwrap(),
|
||||
Version::HTTP_11, headers);
|
||||
match handshake(&req) {
|
||||
Err(err) => assert_eq!(err.status(), StatusCode::BAD_REQUEST),
|
||||
_ => panic!("should not happen"),
|
||||
}
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(header::UPGRADE,
|
||||
header::HeaderValue::from_static("websocket"));
|
||||
headers.insert(header::CONNECTION,
|
||||
header::HeaderValue::from_static("upgrade"));
|
||||
headers.insert(SEC_WEBSOCKET_VERSION,
|
||||
header::HeaderValue::from_static("13"));
|
||||
let req = HttpRequest::new(Method::GET, Uri::try_from("/").unwrap(),
|
||||
Version::HTTP_11, headers);
|
||||
match handshake(&req) {
|
||||
Err(err) => assert_eq!(err.status(), StatusCode::BAD_REQUEST),
|
||||
_ => panic!("should not happen"),
|
||||
}
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(header::UPGRADE,
|
||||
header::HeaderValue::from_static("websocket"));
|
||||
headers.insert(header::CONNECTION,
|
||||
header::HeaderValue::from_static("upgrade"));
|
||||
headers.insert(SEC_WEBSOCKET_VERSION,
|
||||
header::HeaderValue::from_static("13"));
|
||||
headers.insert(SEC_WEBSOCKET_KEY,
|
||||
header::HeaderValue::from_static("13"));
|
||||
let req = HttpRequest::new(Method::GET, Uri::try_from("/").unwrap(),
|
||||
Version::HTTP_11, headers);
|
||||
match handshake(&req) {
|
||||
Ok(resp) => {
|
||||
assert_eq!(resp.status(), StatusCode::SWITCHING_PROTOCOLS)
|
||||
},
|
||||
_ => panic!("should not happen"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -245,6 +245,7 @@ fn encode_base64(data: &[u8]) -> String {
|
|||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
#![allow(unused_imports, unused_variables, dead_code)]
|
||||
use super::*;
|
||||
|
|
|
@ -5,10 +5,12 @@ extern crate reqwest;
|
|||
|
||||
use std::{net, thread};
|
||||
use std::str::FromStr;
|
||||
use actix::*;
|
||||
use actix_web::*;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use tokio_core::net::TcpListener;
|
||||
|
||||
use actix::*;
|
||||
use actix_web::*;
|
||||
|
||||
fn create_server<T, A>() -> HttpServer<T, A, Application<()>> {
|
||||
HttpServer::new(
|
||||
|
@ -24,7 +26,6 @@ fn create_server<T, A>() -> HttpServer<T, A, Application<()>> {
|
|||
fn test_serve() {
|
||||
thread::spawn(|| {
|
||||
let sys = System::new("test");
|
||||
|
||||
let srv = create_server();
|
||||
srv.serve::<_, ()>("127.0.0.1:58902").unwrap();
|
||||
sys.run();
|
||||
|
@ -47,3 +48,59 @@ fn test_serve_incoming() {
|
|||
|
||||
assert!(reqwest::get("http://localhost:58906/").unwrap().status().is_success());
|
||||
}
|
||||
|
||||
struct MiddlewareTest {
|
||||
start: Arc<AtomicUsize>,
|
||||
response: Arc<AtomicUsize>,
|
||||
finish: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl Middleware for MiddlewareTest {
|
||||
fn start(&self, _: &mut HttpRequest) -> Result<(), HttpResponse> {
|
||||
self.start.store(self.start.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn response(&self, _: &mut HttpRequest, resp: HttpResponse) -> HttpResponse {
|
||||
self.response.store(self.response.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
|
||||
resp
|
||||
}
|
||||
|
||||
fn finish(&self, _: &mut HttpRequest, _: &HttpResponse) {
|
||||
self.finish.store(self.finish.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_middlewares() {
|
||||
let num1 = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = Arc::new(AtomicUsize::new(0));
|
||||
let num3 = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let act_num1 = Arc::clone(&num1);
|
||||
let act_num2 = Arc::clone(&num2);
|
||||
let act_num3 = Arc::clone(&num3);
|
||||
|
||||
thread::spawn(move || {
|
||||
let sys = System::new("test");
|
||||
|
||||
HttpServer::new(
|
||||
vec![Application::default("/")
|
||||
.middleware(MiddlewareTest{start: act_num1,
|
||||
response: act_num2,
|
||||
finish: act_num3})
|
||||
.resource("/", |r|
|
||||
r.handler(Method::GET, |_, _, _| {
|
||||
httpcodes::HTTPOk
|
||||
}))
|
||||
.finish()])
|
||||
.serve::<_, ()>("127.0.0.1:58903").unwrap();
|
||||
sys.run();
|
||||
});
|
||||
|
||||
assert!(reqwest::get("http://localhost:58903/").unwrap().status().is_success());
|
||||
|
||||
assert_eq!(num1.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num2.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num3.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue