测试不编译:"the async keyword is missing from the function declaration"

Test does not compile: "the async keyword is missing from the function declaration"

我正在尝试在我的项目中进行工作测试 (src/subdir/subdir2/file.rs):

#[cfg(test)]
mod tests {
    #[tokio::test]
    async fn test_format_str() {
        let src = "a";
        let expect = "a";
        assert_eq!(expect, src);
    }
}

编译时出现这个错误:

error: the async keyword is missing from the function declaration
   --> src\domain\models\product.rs:185:11
    |
185 |     async fn test_format_str() {
    |           ^^

error: aborting due to previous error

这对我来说毫无意义,因为存在异步。

我原来的计划是这样的:

#[cfg(test)]
mod tests {
    #[test]
    fn test_format_str() {
        let src = "a";
        let expect = "a";
        assert_eq!(expect, src);
    }
}

由于所有测试都不是异步的,但会产生相同的错误:

error: the async keyword is missing from the function declaration
   --> src\domain\models\product.rs:185:5
    |
185 |     fn test_format_str() {
    |     ^^

error: aborting due to previous error

我正在使用 tokio = { version = "0.2.22", features = ["full"]},从 src/main.rs.

导出宏

我试过使用test::test;获取 std 测试宏,但这会产生模棱两可的导入编译错误。

我检查了这个 post Error in Rust unit test: "The async keyword is missing from the function declaration" 但据我所知它没有解决我的问题,我需要宏导出。

完整的可重现示例。 Win10,rustc 1.46.0。 只是一个 main.rs:

#[macro_use]
extern crate tokio;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    Ok(())
}

#[cfg(test)]
mod tests {
    #[test]
    async fn test_format_str() {
        let src = "a";
        let expect = "a";
        assert_eq!(expect, src);
    }
}

具有单一依赖项:

[dependencies]
tokio = { version = "0.2.22", features = ["full"]}

删除

#[macro_use]
extern crate tokio;

并使用 tokio 宏作为 tokio:: ex。 tokio::try_join!解决了眼前的问题,虽然很高兴知道为什么会这样。

这是 tokio_macros 版本 0.2.4 和 0.2.5 中的错误。以下最小示例也无法构建:

use tokio::test;

#[test]
async fn it_works() {}

根本问题在于此测试宏扩展到的代码。在目前发布的版本中,大致是这样的:

#[test]
fn it_works() {
    tokio::runtime::Builder::new()
        .basic_scheduler()
        .enable_all()
        .build()
        .unwrap()
        .block_on(async { {} })
}

注意 #[test] 属性。它旨在引用标准 test 属性,即普通测试函数标记,但是,由于 tokio::test 在范围内,它被再次调用 - 而且,由于新函数不是异步的,它会引发错误。

问题已通过 this commit 修复,其中 test 被替换为 ::core::prelude::v1::test,即明确地从 core 拉入。但是相应的更改还没有进入发布的版本,我怀疑这不会很快,因为这在技术上是一个突破性的变化——增加了最低限度支持的 Rust 版本。
目前,唯一的解决方法似乎是不使用带有 tokio 的通配符导入,无论是显式还是通过 macro_use,以及 use 您显式需要的任何东西。