0

I am writing some unit tests for my Rust http server handlers. But when I am running one of the tests it get stuck at the end of the inner function. Here is relevant part of the code:

async fn generate(request: Request<Body>) -> Result<Response<Body>, hyper::Error> {

    let result = process_request(request).await;

    println!("This message doesn't get printed!!");
    
    let (spec, override) = match result {
        Ok((s, o)) => (s, o),
        Err(process_error) => {
            return Ok(Response::new(Body::from(format!("{}", process_error))));
        },
    };

    ...

    Ok(Response::new(Body::from(format!("{}", response))))
}
async fn process_request(request: Request<Body>) -> Result<(Spec, Option<Config>), Error> {
    let body = body::to_bytes(request.into_body()).await;
    let payload: Payload = serde_json::from_slice(&body.unwrap().to_vec()).unwrap();
    let spec_str = payload.spec.to_owned();
    ...
    
    println!("Function runs to this point and prints this message");

    Ok((spec, override))
}
#[tokio::test]
async fn test_gen() {

    let payload =  Payload {
        spec: a_spec(),
    };
        
    let payload_json = serde_json::to_string_pretty(&payload).unwrap();
    let request = Request::builder().body(Body::from(payload_json));
        
    let result = generate(request.unwrap()).await.unwrap();
    
    // Some asserts ...
}

I am wondering what I am doing wrong?

hagh
  • 507
  • 5
  • 13
  • how could we know ? – Stargateur Nov 03 '21 at 07:33
  • 5
    Values in scope are *dropped* at the end of the function, so there may be a `Drop` implementation that's blocking. But that's just a guess, please provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – kmdreko Nov 03 '21 at 08:07
  • 1
    Please don't *edit* your question to provide a solution. You are allowed and even encouraged to *answer* to your own question below. But in addition, you should update your question to be reproducible (I'm guessing even adding a stub for the thread call would suffice). That way the question and answer will be most helpful to future viewers. – kmdreko Nov 04 '21 at 03:37
  • @kmdreko: I am putting a http wrapper around an existing code. Just sharing the experience. – hagh Nov 04 '21 at 20:57

1 Answers1

2

Looks like the inner function starts another thread, so the solution was to decorate the test with:

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]

This resolved the issue for my unit tests.

hagh
  • 507
  • 5
  • 13