有没有办法告诉 Cargo 运行 它在主线程上的测试?

Is there any way to tell Cargo to run its tests on the main thread?

我一直在尝试构建一个基于 OpenGL 的图像处理库,但存在 GLFW, and need it to be testable. Unfortunately, I ran into this 错误 - GLFW 需要从主线程调用其初始化函数,但 Cargo 测试 运行后台线程。

不,据我所知,目前还不容易。您可以将 --test-threads 参数传递给测试工具,但它设置了主线程之外的线程数。所以 --test-threads=1 仍然有两个线程。


所以你不能真正使用默认的测试工具。幸运的是,您可以在 Cargo.toml 中禁用它。可能最好的解决方案是创建一个新文件夹(例如 gltests)并将所有需要 运行 的测试放在主线程中。然后我们只需要在 Cargo.toml:

中声明这些测试
[[test]]
name = "gltests"
path = "gltests/main.rs"
harness = false

这意味着 cargo 将尝试将 gltests/main.rs 编译为可执行文件(期望 main() 函数)并在您说 cargo test 时执行此可执行文件。这样你就不会得到任何你通常从货物测试中得到的花哨的输出。您只需要 自己main.rs 中完成所有事情,但至少您可以在主线程中开始测试。