Documentation/translations/zh_CN/rust/testing.rst

Source file repositories/reference/linux-study-clean/Documentation/translations/zh_CN/rust/testing.rst

File Facts

System
Linux kernel
Corpus path
Documentation/translations/zh_CN/rust/testing.rst
Extension
.rst
Size
7626 bytes
Lines
216
Domain
Support Tooling And Documentation
Bucket
Documentation
Inferred role
Support Tooling And Documentation: documentation
Status
atlas-only

Why This File Exists

Repository support layer: documentation, build tooling, samples, user-space helper tools, generated initramfs support, licenses, and validation utilities.

Dependency Surface

Detected Declarations

Annotated Snippet

fn test_f() {
	        assert_eq!(f(10, 20), 30);
	    }
	}

如果我们执行这段代码,内核日志会显示::

	    KTAP version 1
	    # Subtest: rust_kernel_mymod
	    # speed: normal
	    1..1
	    # test_f.speed: normal
	    ok 1 test_f
	ok 1 rust_kernel_mymod

与文档测试类似, ``assert!`` 和 ``assert_eq!`` 宏被映射回 KUnit 并且不会发生 panic。
同样,支持 `? <https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator>`_ 运算符,
测试函数可以什么都不返回(单元类型 ``()``)或 ``Result`` (任何 ``Result<T, E>``)。例如:

.. code-block:: rust

	#[kunit_tests(rust_kernel_mymod)]
	mod tests {
	    use super::*;

	    #[test]
	    fn test_g() -> Result {
	        let x = g()?;
	        assert_eq!(x, 30);
	        Ok(())
	    }
	}

如果我们运行测试并且调用 ``g`` 失败,那么内核日志会显示::

	    KTAP version 1
	    # Subtest: rust_kernel_mymod
	    # speed: normal
	    1..1
	    # test_g: ASSERTION FAILED at rust/kernel/lib.rs:335
	    Expected is_test_result_ok(test_g()) to be true, but is false
	    # test_g.speed: normal
	    not ok 1 test_g
	not ok 1 rust_kernel_mymod

如果 ``#[test]`` 测试可以对用户起到示例作用,那就应该改用文档测试。
即使是 API 的边界情况,例如错误或边界问题,放在示例中展示也同样有价值。

``rusttest`` 宿主机测试
-----------------------

这类测试运行在用户空间,可以通过 ``rusttest`` 目标在构建内核的宿主机中编译并运行::

	make LLVM=1 rusttest

当前操作需要内核 ``.config``。

目前,它们主要用于测试 ``macros`` crate 的示例。

Kselftests
----------

Kselftests 可以在 ``tools/testing/selftests/rust`` 文件夹中找到。

测试所需的内核配置选项列在 ``tools/testing/selftests/rust/config`` 文件中,
可以借助 ``merge_config.sh`` 脚本合并到现有配置中::

	./scripts/kconfig/merge_config.sh .config tools/testing/selftests/rust/config

Kselftests 会在内核源码树中构建,以便在运行相同版本内核的系统上执行测试。

Annotation

Implementation Notes