-
-
Save kolbma/b8bd787568e543ccaf7abe7b5ba1b8ee to your computer and use it in GitHub Desktop.
Integration testing for tiny_httpd
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![warn(clippy::pedantic)] | |
#![warn( | |
missing_debug_implementations, | |
missing_docs, | |
non_ascii_idents, | |
trivial_casts, | |
trivial_numeric_casts, | |
unreachable_pub, | |
unsafe_code, | |
unused_extern_crates, | |
unused_import_braces, | |
unused_qualifications, | |
unused_results | |
)] | |
#![forbid(unsafe_code)] | |
#![cfg(test)] | |
use std::{ | |
io::sink, | |
process::{self, Child}, | |
sync::{ | |
atomic::{AtomicU8, Ordering}, | |
Once, RwLock, | |
}, | |
thread, | |
time::Duration, | |
}; | |
static AFTER: Once = Once::new(); | |
static BEFORE: Once = Once::new(); | |
static BEFORE_COUNT: AtomicU8 = AtomicU8::new(0); | |
static PROC_CHILD: RwLock<Option<Child>> = RwLock::new(None); | |
fn before() { | |
let _ = BEFORE_COUNT.fetch_add(1, Ordering::Relaxed); | |
BEFORE.call_once(|| { | |
*PROC_CHILD.write().expect("lock") = Some( | |
process::Command::new("cargo") | |
.arg("r") | |
.env("RUST_LOG", "debug") | |
.spawn() | |
.expect("server start"), | |
); | |
let client = ureq::builder().timeout(Duration::from_secs(2)).build(); | |
while let Err(err) = client.get(&format!("http://localhost:8080{}", "/")).call() { | |
if let ureq::Error::Transport(t) = err { | |
assert!(!(t.kind() != ureq::ErrorKind::ConnectionFailed), "{:#?}", t); | |
} else { | |
break; | |
} | |
thread::sleep(Duration::from_millis(100)); | |
} | |
}); | |
} | |
fn after() { | |
let _ = BEFORE_COUNT.fetch_sub(1, Ordering::Relaxed); | |
if BEFORE_COUNT.load(Ordering::Relaxed) == 0 { | |
AFTER.call_once(|| { | |
PROC_CHILD | |
.write() | |
.expect("lock") | |
.as_mut() | |
.expect("child") | |
.kill() | |
.expect("kill"); | |
}); | |
} | |
} | |
fn get(path: &str) -> Result<ureq::Response, Box<ureq::Error>> { | |
let client = ureq::builder().timeout(Duration::from_secs(2)).build(); | |
let mut req = client.get(&format!("http://localhost:8080{}", path)); | |
req.call().map_err(Box::new) | |
} | |
#[test] | |
fn a_test() { | |
before(); | |
let path = "/css/main.css"; | |
let res = get(path).unwrap(); | |
assert_eq!(res.content_type(), "text/css"); | |
let mut reader = res.into_reader(); | |
let mut sink = sink(); | |
let size = std::io::copy(&mut reader, &mut sink).unwrap(); | |
assert_eq!(size, 30000); | |
after(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment