1

Rust单元测试完成后自动执行覆盖率测试

 11 months ago
source link: https://www.wyr.me/post/753
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在本文将探讨如何在Rust项目中自动完成单元测试并执行覆盖率测试。我们将使用rust-analyzer插件、配置.vscode/settings.json文件以及编写一个Python脚本变相实现cargo命令的hook。最终效果按下“Run Test”按钮后自动完成单元测试及覆盖率测试,实现搭配Coverage Gutters插件实时显示覆盖率结果。

使用 rust-analyzer 插件

要实现在VSCode中开发Rust及执行Rust单元测试,我们需要安装rust-analyzer插件。它可以通过扩展面板搜索并安装。

几乎所有支持Rust开发的编辑器都使用了rust-analyzer

配置 .vscode/settings.json

接下来,在项目目录下创建.vscode/settings.json文件并填入以下内容:

{
    "rust-analyzer.runnables.command": "python3 ${workspaceFolder}/bin/cargo.py"
}

这里,我们设置了一个新的运行命令,用于执行我们将要创建的Python脚本。当用户点击#[test]下方的“Run Test”时,会执行该命令。

创建 bin/cargo.py 文件

现在,我们将在项目目录下创建一个名为bin/cargo.py的新文件。请将以下代码粘贴到文件中:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
import subprocess
import re

def main():
    test_name = None
    for idx, arg in enumerate(sys.argv):
        if arg == "--" and len(sys.argv) > idx + 1:
            test_name = sys.argv[idx + 1]
            break

    cmd = ["cargo"] + sys.argv[1:]
    print("Executing command:", " ".join(cmd))
    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    print(result.stdout)

    test_result_pattern = re.compile(r"test result: ok.*failed;")

    if test_result_pattern.search(result.stdout):
        coverage_cmd = ["cargo", "xtask", "coverage"]
        if test_name:
            coverage_cmd.extend(["name="+test_name])
        print("Executing command:", " ".join(coverage_cmd))
        coverage_result = subprocess.run(coverage_cmd)
    else:
        print("Failed test cases found. Skipping cargo xtask coverage.")

if __name__ == "__main__":
    main()

这个脚本实现了一个cargo_wrapper,用于在执行cargo test命令后运行覆盖率测试命令(这里使用的是cargo xtask coverage name=单元测试名称)。使用Python脚本的好处是它具有跨平台性。

整合 Coverage Gutters 插件

我们还可以安装和配置Coverage Gutters插件,以便在VSCode中实时查看覆盖率结果。只需在扩展面板中搜索并安装即可。

这样,在点击单元测试方法上方的“Run Test”按钮后,自动完成单元测试并测试其覆盖率。搭配Coverage Gutters插件可以在VSCode中Watch单元覆盖率的变化并实时显示在界面上。

rusttest.png

以上涉及的代码已经在开源仓库https://github.com/yi-ge/rust-practice中可以看到 ,您可以尝试修改该项目来适配你的测试需求。

通过本文的方法,咱们可以非常方便的在Rust项目中实现自动执行单元测试并进行覆盖率测试。祝您开发愉快!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK