【问题标题】:How do I test crates with #![no_std]?如何使用 #![no_std] 测试 crate?
【发布时间】:2015-01-28 06:14:56
【问题描述】:

我正在为 Rust 中的编程语言实现编写运行时。我计划在这个运行时中链接我生成的编译代码,所以为了保持二进制小,我不想依赖std

当我尝试 cargo test 我的运行时时,我收到错误消息说找不到 std::slice::AsSlice,我发现这是因为某些测试工具需要标准库代码。

我该如何测试这段代码?有没有办法有条件地包含#![no_std] pragma,即在测试时仍然包含 std 库?我还尝试创建一个包含 std 库的单独测试包,extern crate将运行时包放入其中并在那里运行我的测试,但这带来了一系列全新的问题。

【问题讨论】:

    标签: testing rust


    【解决方案1】:

    您可以通过cfg_attr 有条件地设置no_std。

    #![cfg_attr(not(test), no_std)]
    

    【讨论】:

      【解决方案2】:
      #[cfg(test)]
      #[macro_use]
      extern crate std;
      

      #[macro_use] 部分是可选的。)

      【讨论】:

      • 这似乎应该是正确的方法,但是当我尝试运行 cargo test 时,我仍然收到以下错误:error: attempt to implement a nonexistent trait std::cmp::PartialEqerror: failed to resolve. Maybe a missing extern crate std?
      • 另外我应该提一下,只需删除 #[cfg(test)] 行就可以了。
      • 如果您将其设为无条件的extern crate std;,那么您就有点失去了#![no_std] 的全部意义。在这种情况下,您应该提供自己的模块标准,例如:mod std { pub use core::cmp; }
      • 我发现了我的问题所在。除了#[cfg(test)] extern crate std; 行之外,我还需要#[cfg(test)] use std::prelude::*;,因为不再自动导入前奏曲。如果你不介意的话,还有一个快速的问题:有没有办法在这个设置中仍然使用像 #[derive(Debug, PartialEq)] 这样的指令?
      • @ZachSmith:mod std { pub use core::fmt; pub use core::cmp; } &c。 &C。会成功的。
      猜你喜欢
      • 1970-01-01
      • 2018-09-30
      • 2021-10-27
      • 2019-01-21
      • 1970-01-01
      • 2019-04-09
      • 2023-01-09
      • 1970-01-01
      • 2015-01-17
      相关资源
      最近更新 更多