write! macro does not work properly with async function in Rust

142 views Asked by At

Here's a simplified version of my funciton:

async fn show_status(root_dir: &PathBuf, mut output: impl std::io::Write) -> Result<(), Error> {
    writeln!(output, "status:");

    let mut commponent_ids = walk_components(&StatusVisitor::new(), &root_dir, None).await?;
    writeln!(output, "ids: {:?}", commponent_ids);
    output.flush();

    Ok(())
}

And this is my test case:

#[cfg(test)]
mod tests {
    use super::show_status;

    #[tokio::test]
    async fn test_show_status() {
        let mut output = Vec::new();
        show_status(&main_repo_dir, &mut output).await;

        assert_eq!(std::str::from_utf8(output.as_slice()).unwrap(), "status:\nids: [0, 1]");
    }
}

I think the case may pass as expected, but the fact is that I got following failure:

assertion `left == right` failed
  left: "status:\n"
 right: "status:\nids: [0, 1]\n"

I have no idea why the second line can not be seen in the output. Can anyone give me some help?

I have asked chatgpt and it told me to use the traits tokio::io::AsyncWriteExt instead of std::io::Write. But when I tried the solution, nothing changed.

I have also tried that call the funciton in main funciton directly instead of calling it in a testcase. Unexpectedly, I works properly. I saw both 2 lines in the stdout.

So my problem is: What happened with the testcase? Why can't I seen the second line in the output in a async testcase?

0

There are 0 answers