admin管理员组

文章数量:1129459

I created a Tokio test to catch a regression which manifests as an incomplete packet causing timeout. Pseudo code.

#[tokio:test]
async fn test() {
   start_server().await;
   receive_packet();
}

pub async fn receive_packet() -> anyhow::Result<()> {
    let mut buffer = BytesMut::new();
    let timestamp = std::time::Instant::now();

    let message_size = loop {
        read(socket, &mut buffer);
        if buffer.len() >= 4 {
            break buffer.get_u32();
        }
    };

    loop {
        if timestamp.elapsed().as_secs() > 1 {
            panic!("Timeout");
            return anyhow::Result::Err(anyhow::anyhow!("Timeout"));
        }
        if buffer.len() == message_size as usize {
            return Ok(());
        }
        // This function gets called many times without affecting the buffer 
        // when the server sends a truncated response.
        read(socket, &mut buffer);
    }
}

Unfortunately when running under cargo test even if the code panics, the test will not stop. My goal is to make the test fail instead. I tried replacing the panic with process::exit(1) without success. I tried to wrap the main test code with timeout() and place a yield_now() call before the last read call.

I've also tried this in the main test code:

            panic::set_hook(Box::new(move |panic_info| {
                println!("Panic occurred: {:?}", panic_info);
                process::exit(1);
            }));

What is the canonical way to express "if this test takes more than 2 secs to run, fail" in a tokio::test?

本文标签: rustFaling a tokio test due to timeoutStack Overflow