我想为目录中的每个文件创建一个BATS测试,但我不确定完成这项工作的最佳方法是什么。即使目录中有很多文件,下面的方法也只会创建一个测试。
#!/usr/bin/env bats
for i in ./*;do
@test "testing $i" {
pwd
}
done
我想为目录中的每个文件创建一个BATS测试,但我不确定完成这项工作的最佳方法是什么。即使目录中有很多文件,下面的方法也只会创建一个测试。
#!/usr/bin/env bats
for i in ./*;do
@test "testing $i" {
pwd
}
done
When a test is run by BATS, the file is first preprocessed.1
This replaces the @test
block with an actual function and adds a call to
that function.
The result is then stored in the BATS_TMPDIR
as bats.${PID}.src
.
Any programmatically added tests would need to be added to the preprocessed file.
The test names would also have to be added to BATS_TEST_NAMES
.
Putting all of this together we get:2
#!/usr/bin/env bats
declare sFile sSourceFile sTestFunction sTestName
readonly sSourceFile="${BATS_TMPDIR}/bats.$$.src"
if [[ -f "${sSourceFile}" ]];then
for sFile in ./*;do
sTestFunction="test_${sFile}"
sTestName="Testing ${sFile}"
cat <<EOT >> "${sSourceFile}"
$sTestFunction() { bats_test_begin '$sTestName' 0;
return 0
}
bats_test_function "${sTestFunction}"
EOT
BATS_TEST_NAMES+=("${sTestFunction}")
done
fi
#EOF
The preprocessed version of your example looks like this:
#!/usr/bin/env bats
for i in ./*; do
test_testing_-24i() { bats_test_begin "testing $i" 4;
pwd
}
done
bats_test_function test_testing_-24i
So effectively, the test function is declared as many times as there are files present. The test function, however, is only called once.3
这个怎么样?
#!/usr/bin/env bash
declare -r BATS=`mktemp`
trap "rm -f $BATS" EXIT
for i in $(ls)
do
cat > $BATS <<EOF
@test "testing $i" {
pwd
}
EOF
done
bats $BATS