首页 > 解决方案 > 如何在Makefile中循环n个测试用例?

问题描述

我希望我的 Makefile 为我自动化测试。基本上我会有一堆运行我的代码的测试用例。我希望用户指定测试用例的数量,而不是硬编码。

基本上我想要这样的东西:

gcc main.c -o main

./main < test1.txt > output1.txt
./main < test2.txt > output2.txt
./main < test3.txt > output3.txt
./main < test4.txt > output4.txt
.
.
.
./main < test<n>.txt > output<n>.txt #for some value n

并把它变成这样的东西:

gcc main.c -o main

#of course this wouldn't be the syntax, but I just need the Makefile version of a loop, where all one has to do is change the n value 
for(int i = 0; i < n+1; i++){
   ./main < test<i>.txt > output<i>.txt;
}

谢谢 :)

标签: cshellloopsmakefile

解决方案


现在更新以正确回答问题

您可能想要做的(从外观上看)是让您的 makefile 为您做各种事情:

# Target to build "main" its the first target and therefore the default 
# call "make" to run
main:
    @gcc main.c -o main

# Arbitrary max number of tests, can be overwritten by passing the variable in
NUM_TESTS=100
# Find all the tests, put them into an ordered list, then take the first 
# 1 to NUM_TESTS of them. Finally substitute test* for output*
TEST_OUTPUTS=$(subst test,output,$(wordlist 1,$(NUM_TESTS),$(sort $(wildcard test*.txt))))

# Target to do your testing, call "make test NUM_TESTS=3" or "make test" 
# to run all tests (up to 100).
.PHONY: test
test: $(TEST_OUTPUTS)

# Pattern rule to run each test - you don't call this directly
# Note: this has a dependency on main so if main is not built it 
# will get built first
output%.txt: test%.txt main
    @./main < $< > $@

# Target to clean up output files, call "make clean"
.PHONY: clean
clean:
    rm -f main
    rm -f $(TEST_OUTPUTS)

使用者:

  • make build- 构建主要
  • make test- 运行找到的所有测试,最多 100 个(可以更改最大值)
  • make test NUM_TESTS=3- 运行前 3 个测试(如果存在)
  • make test NUM_TESTS=3 -j6- 与以前相同,但运行 6 个并行作业(或-j用于尽可能多的并行作业) - 即并行运行测试

说明:模式规则会根据文件 test*.txt 生成文件 output*.txt。但是我们想为此调用规则outputX.txt,我们通过搜索所有输出文件(在变量中TEST_OUTPUTS)然后选择我们想要的测试数量来生成输出文件列表。我们可以通过传入一个变量来做到这一点,或者如果我们不传入一个变量,那么它最多可以进行 100 次测试(或者任何你设置的最大值。

注意:我没有运行这个,所以我认为是伪代码,但它应该非常接近)


推荐阅读