Skip to content

re: Hyper Webapp Template VIEW POST


Great stuff - but Ben... where are the tests? :D

Actually, I'm not just trolling you. I've been dipping my toes back into Rust for a few days and started trying to write something in Hyper. I tried to do what I would normally do for this sort of thing: write a test for one of the handler functions.

I got to this:

use hyper::{Request, Body, Response, http};

pub async fn hello_world(_req: Request<Body>) -> Result<Response<Body>, http::Error> {
        .body(Body::from("Hello, world"))

mod tests {
    use crate::hello_world;
    use hyper::{Request, Body};
    use tokio::runtime::Runtime;

    fn hello_world_server() {
        let mut runtime = Runtime::new().unwrap();

        let request = Request::new(Body::from(""));
        let future = hello_world(request);
        let response = runtime.block_on(future).unwrap();
        let bytes = runtime.block_on(hyper::body::to_bytes(response)).unwrap();
        let string = String::from_utf8(bytes.to_vec()).unwrap();

        assert_eq!(string, String::from("Hello, world"))

Which I'm not crazy about - feels like I'm repeatedly unwinding a future then unwrapping a result. Gets the job done but feels a bit like I'm banging these rocks together. You know anything more elegant?


Heh - you nailed it with banging rocks together. I'm still playing with these, I don't know what to do either:

mod tests {
    use super::*;
    use flate2::read::ZlibDecoder;
    use hyper::body;
    use select::{
        predicate::{Name, Predicate},
    use tokio::runtime::Runtime;

    fn test_four_oh_four() {
        let mut rt = Runtime::new().unwrap();
        let response = rt.block_on(four_oh_four()).unwrap();
        let bytes = rt.block_on(body::to_bytes(response)).unwrap();
        let mut d = ZlibDecoder::new(&bytes[..]);
        let mut html = String::new();
        d.read_to_string(&mut html).unwrap();
        let document = Document::from(html.as_str());
        let node = document
        assert_eq!(node.text(), "NOT FOUND!");


That made me feel better - misery loves company!

I'm planning to include a fuller set with the forthcoming CRUD template, I'll copy the relevant ones back over.

They may not be pretty, but at least they'll be there...

code of conduct - report abuse