c - 在多个 C 文件上运行自动化测试

标签 c bash algorithm automated-tests software-design

结构中有几个文件

/algorithms
    /a1
        a1.c
    /a2
        a2.c
    /a3
        a3.c

这些文件中的每一个都包含一个同名的函数。除了名称(与文件名相同)外,每个文件都具有相同的签名。从本质上讲,每种算法都是对同一事物的不同实现——以不同的方式达到相同的目的。然而,可能会有一些小的辅助函数。

文件的内容(注释、功能、布局等)不能更改。 我想创建一些方法来测试每个算法。此方法并不只能在 C 中实现。

我有一个主要包含三个函数的 C 文件:

// Runs the algorithm, which modifies the given integer array.
void run(void (*algorithm) (int*, size_t));

// Checks that the algorithm successfully completed and
// the array is correct.
int check(int*, size_t);

// Should call run() with appropriate algorithm and a random data set
// and then call check() to make sure it worked.
int main(int, char**);

我需要一种自动包含适当文件然后调用的方法 它们内部的功能。目前,我有一个获取所有算法的 bash 文件,复制测试程序文件,在开头添加一个 #include 语句,并生成一个被调用的 injected_main() 函数通过实际的 main() 函数。它运行复制的测试器,然后将其删除。

function testC() {

    local tempout=temptest.c
    local filename="$(basename -- $1)"
    local functionname="${filename%.*}"
    local main="void injectedMain() {test(&$functionname);}"
    local include="#include\"$1\"\n$main"

    touch $tempout
    chmod +x $tempout
    printf "$filename: "
    cp $TESTER_C $tempout
    printf "$include" >> $tempout
    gcc $tempout -o tempout -Wall -Wextra -pedantic
    ./tempout
    rm $tempout tempout

}

函数在每个算法 C 文件的循环中运行。 然而,这种方法容易出错,不可扩展,而且非常丑陋。有更好的方法吗?

最佳答案

结合您现有的代码和@Herve 的回答。

您可以让 bash 脚本只收集所有算法并构建一个像 @Herve 所建议的那样的 C 源代码。这样就不会有容易出错的手动步骤。

要运行所有测试,请编译这个自动生成的源并将其链接到您的测试运行器。让后者循环遍历 all

关于c - 在多个 C 文件上运行自动化测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57301225/

相关文章:

c# - 垂直翻转字节数组中位图的算法

C 指向数组的指针;到原始

c - 在C中使用字符串作为数组中的索引

java - 在具有内存限制的未排序输入中查找缺失的数字

python - 从文件中的列表自动完成命令行参数

linux - 如何从用户提供的输入中打印偶数

c++ - 面试算法查询

c - 文件格式无法识别;视为链接器脚本 - 为 arm 处理器编译 c 代码

c - 来自 ifconfig 和 libpcap 的接口(interface) ip 不匹配

bash - 使用 awk 从特定行获取第 n 个字段