rust-tests-guidelines

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Guidelines for Writing Rust Tests

Rust测试编写指南

Guidelines for writing new tests for Rust code.
为Rust代码编写新测试的指南。

Guidelines

指南

  1. Test against the public API of the code under test.
  2. Test private APIs if and only if the private component is highly complex and difficult to test through the public API.
  3. Use
    insta
    whenever you are testing output that is difficult to predict or compare.
  4. Where appropriate, use
    proptest
    to add property-based tests for key invariants.
  5. Testing code should be written with the same care reserved to production code. Avoid unnecessary duplication, introduce helpers to reduce boilerplate and ensure readability. The intent of a test should be obvious or, if not possible, clearly documented.
  6. Do not reference exact line numbers in comments, as they may change over time.
  1. 针对被测代码的公开API进行测试。
  2. 仅当私有组件高度复杂且难以通过公开API测试时,才对私有API进行测试。
  3. 每当测试难以预测或比较的输出时,使用
    insta
  4. 适当时,使用
    proptest
    为关键不变量添加基于属性的测试。
  5. 测试代码的编写应与生产代码同样用心。 避免不必要的重复,引入辅助工具以减少样板代码并确保可读性。 测试的意图应清晰明了,若无法做到,则需明确记录。
  6. 不要在注释中引用确切的行号,因为这些行号可能会随时间变化。

Code organization

代码组织

  1. Put tests under the
    tests
    directory of the relevant crate if they don't rely on private APIs.
  2. The
    tests
    directory should be organized as a crate, with a
    main.rs
    file and all tests in modules. Refer to the
    trie_rs/tests
    directory as an example.
  3. If the test must rely on private APIs, co-locate them with the code they test, using a
    #[cfg(test)]
    module.
  1. 如果测试不依赖私有API,请将其放在相关crate的
    tests
    目录下。
  2. tests
    目录应作为一个crate进行组织,包含
    main.rs
    文件和所有测试模块。 可参考
    trie_rs/tests
    目录作为示例。
  3. 如果测试必须依赖私有API,请将它们与被测代码放在一起,使用
    #[cfg(test)]
    模块。

Dealing with extern C symbols

处理外部C符号

Check out CONTRIBUTING.md for instructions on how to deal with undefined C symbols in Rust tests.
有关如何在Rust测试中处理未定义C符号的说明,请查看CONTRIBUTING.md