每次运行$ make test
(或$ctest
)时,如何让 ctest 在单独的瞬态/临时目录中运行我的每个测试。
假设我有一个测试可执行文件,mytest.cpp
它做了两件事:1) 它断言当前工作目录中不存在名为“foo.txt”的文件,然后 2) 创建一个名为“foo.txt”的文件。现在我希望能够make test
多次运行而不会mytest.cpp
失败。
我想通过要求 cmake/ctest 在它自己的临时目录中运行每个测试(在这个例子中,一个测试)来实现这一点。
我在网上搜索了解决方案,并通读了ctest
文档。特别是add_test
文档。我可以提供一个“WORKING_DIRECTORY”给add_test
. 这将在“WORKING_DIRECTORY”中运行我的测试。但是,对该文件夹所做的任何更改make test
都会在多次运行中保持不变。所以我第二次运行make test
测试失败了。
这是触发故障的最小的、可重复的方式。一个mytest.cpp
定义测试可执行文件的源文件和一个用于构建代码的 CMakeLists.txt 文件。
# CMakeLists.txt
cmake_minimum_required (VERSION 2.8)
project (CMakeHelloWorld)
enable_testing()
add_executable (mytest mytest.cpp)
add_test( testname mytest)
和
// mytest.cpp
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <fstream>
inline bool exists (const std::string& name) {
std::ifstream f(name.c_str());
return f.good();
}
int main() {
assert(exists("foo.txt") == false);
std::ofstream outfile ("foo.txt");
outfile.close();
}
产生故障的一系列命令
$ mkdir build
$ cd build
$ cmake ..
$ make
$ make test
$ make test
这会给
Running tests...
Test project /path/to/project
Start 1: testname
1/1 Test #1: testname .........................***Exception: Other 0.25 sec
0% tests passed, 1 tests failed out of 1
Total Test time (real) = 0.26 sec
The following tests FAILED:
1 - testname (OTHER_FAULT)
Errors while running CTest
make: *** [test] Error 8
通常,测试框架提供某种预测试(设置)和后测试(清理)任务。CTest 也是如此。
将以下CTestCustom.ctest
文件添加到示例的构建目录中,每次测试都会成功:
# CTestCustom.ctest
set(CTEST_CUSTOM_POST_TEST "rm foo.txt")
对于更复杂的任务,您可能想要创建自定义脚本,但这就是调用它的方式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句