繁体   English   中英

测试无法编译:“函数声明中缺少 async 关键字”

[英]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

这对我来说毫无意义,因为 async 在那里。

我原来的计划是这样的:

#[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 测试宏,但这会产生不明确的导入编译错误。

我查看了这篇文章Rust 单元测试中的错误:“函数声明中缺少 async 关键字”,但据我所知,它没有解决我的问题,我需要宏导出。

完全可重现的示例。 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在范围内,它会再次被调用 - 而且,由于新函数不是异步的,它会引发错误.

此提交修复了该问题,其中test替换为::core::prelude::v1::test ,即从core显式拉入。 但是相应的更改还没有进入发布版本,我怀疑这不会很快,因为这在技术上是一个突破性的更改 - 冲击最低支持的 Rust 版本。
目前,唯一的解决方法似乎不是明确地或通过macro_use使用通配符导入tokio ,而是use您需要明确的任何东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM