如何在precheck测试失败时跳过CTest中的其他测试?
How to halt subsequent tests when a precheck test fails in CMake?
我来帮你解决这个CMake测试的问题——确实,DEPENDS属性仅能控制测试的执行顺序,无法在前置测试失败时终止后续测试的运行。这里有几个实用的方案,你可以根据自己的需求选择:
方案1:用CTest的--stop-on-failure参数(快速生效)
如果你希望只要有任何测试失败就立即终止所有后续测试,直接在运行测试时加上这个参数即可:
# 直接用ctest命令 ctest --stop-on-failure # 或者通过make test传递参数 make test CTEST_FLAGS="--stop-on-failure"
(注:CMake 3.10及以上版本也支持--fail-fast参数,功能和--stop-on-failure完全一致)
这样当precheck测试失败后,CTest会立刻停止执行,不会再运行test-1和test-2,完全符合你“立即停止”的需求。
方案2:使用CMake测试夹具(更精细的控制,CMake 3.7+)
如果你只想在**precheck失败时跳过依赖它的测试**(而不是全局停止所有失败测试),可以用CMake的测试夹具(Fixtures)功能。这种方式会把依赖测试标记为“未运行”,而不是强行终止整个测试流程:
修改你的CMake代码如下:
add_test(NAME precheck COMMAND false) # 将precheck标记为一个SETUP类型的夹具 set_tests_properties(precheck PROPERTIES FIXTURES_SETUP precheck_fixture) add_test(NAME test-1 COMMAND true) add_test(NAME test-2 COMMAND true) # 让test-1和test-2要求precheck_fixture set_tests_properties(test-1 test-2 PROPERTIES FIXTURES_REQUIRED precheck_fixture)
执行后结果会变成这样:
$ make test Running tests... Test project /root/ibvq/frkcrpg/b Start 1: precheck 1/3 Test #1: precheck .........................***Failed 0.00 sec Start 2: test-1 2/3 Test #2: test-1 ...........................***Not Run 0.00 sec Start 3: test-2 3/3 Test #3: test-2 ...........................***Not Run 0.00 sec 33% tests passed, 1 tests failed out of 3 Total Test time (real) = 0.02 sec The following tests FAILED: 1 - precheck (Failed) The following tests were not run: 2 - test-1 3 - test-2 Errors while running CTest Makefile:83: recipe for target 'test' failed make: *** [test] Error 8
这种方式的优势是不会影响其他不依赖precheck的测试,仅跳过指定的依赖测试。
方案3:自定义命令封装(特殊场景备选)
如果你需要更灵活的控制逻辑,也可以把precheck的检查直接封装到每个测试的命令里(以Unix-like系统为例):
add_test(NAME precheck COMMAND false) # 封装测试逻辑:先检查precheck的结果,失败则直接退出 add_test(NAME test-1 COMMAND bash -c "ctest -R ^precheck$ --output-on-failure || exit 1; true") add_test(NAME test-2 COMMAND bash -c "ctest -R ^precheck$ --output-on-failure || exit 1; true")
不过这种方式会重复执行precheck,测试效率较低,一般只推荐在前面两种方案不适用的特殊场景下使用。
内容的提问来源于stack exchange,提问作者pynexj
相关产品推荐
相关产品推荐

