【问题标题】:How to get 100% coverage with gcovr with ifdef code?如何使用 ifdef 代码使用 gcovr 获得 100% 的覆盖率?
【发布时间】:2020-02-26 04:08:57
【问题描述】:

我喜欢在我的 Linux 机器上使用 gcovr 来了解测试的内容和未测试的内容。 我掉进了一个看不到解决方案的坑里。

我有如下所示的 C 代码(另存为 main.c)。代码非常简单 - 实际上重点只是 #if 构造以及如何针对不同编译设置进行覆盖分析。

/* Save as main.c */
#include <stdio.h>

void fct(int a)
{
// Define PRINTSTYLE to 0 or 1 when compiling
#if PRINTSTYLE==0
    if (a<0) {
        printf("%i is negative\n", a);
    } else {
        printf("%i is ... sorta not negative\n", a);
    }
#else
    if (a<0) {
        printf("%i<0\n", a);
    } else {
        printf("%i>=0\n", a);
    }
#endif
}


int main(void)
{
    fct(1);
    fct(-1);
    return 0;
}

我可以使用例如在 Linux 上编译和进行覆盖测试

$ rm -f testprogram *.html *.gc??
$ gcc -o testprogram main.c \
  -g --coverage -fprofile-arcs -ftest-coverage --coverage \
  -DPRINTSTYLE=0
$ ./testprogram
$ gcovr -r . --html --html-details -o index.html
$ firefox index.main.c.html

这几乎是超级的——但我想做的是结合-DPRINTSTYLE=0(见ahove)和-DPRINTSTYLE=1的测试结果——然后我逻辑上应该在生成的index.main.c中获得100%的覆盖率。 html

我完全明白中间需要重新编译。

如何通过 ifdef 代码使用 gcovr 获得 100% 的覆盖率?

【问题讨论】:

    标签: linux code-coverage gcov test-coverage gcovr


    【解决方案1】:

    这是可行的 - 但需要 gcovr 4.2(或更高版本),如 https://gcovr.com/en/stable/guide.html#combining-tracefiles 所示

    首先安装或升级 gcovr,例如与

    pip install -U gcovr
    

    然后确保 ~/.local/bin/ 在 $PATH 中。

    接下来为每个配置运行一次 gcovr,并生成 JSON 报告:

    gcc -o testprogram main.c -g --coverage -DPRINTSTYLE=0
    ./testprogram
    gcovr -r . --json run-1.json
    
    gcc -o testprogram main.c -g --coverage -DPRINTSTYLE=1
    ./testprogram
    gcovr -r . --json run-2.json
    

    最后,使用 -a/--add-tracefile 模式组合 JSON 报告并生成所需的报告:

    gcovr --add-tracefile run-1.json --add-tracefile run-2.json --html-details coverage.html
    

    参考:https://github.com/gcovr/gcovr/issues/338

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-15
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 2019-11-06
      • 2021-08-19
      • 1970-01-01
      相关资源
      最近更新 更多