【发布时间】:2019-04-10 20:54:23
【问题描述】:
每次我运行$ make test(或$ctest)时,如何让 ctest 在单独的临时/临时目录中运行我的每个测试。
假设我有一个测试可执行文件mytest.cpp,它做了两件事:1) 它断言当前工作目录中不存在名为“foo.txt”的文件,然后 2) 创建一个名为“foo 。文本文件”。现在我希望能够多次运行make test 而不会导致mytest.cpp 失败。
我想通过让 cmake/ctest 在其自己的临时目录中运行每个测试(在本例中为一个测试)来实现这一点。
我已经在网上搜索了解决方案,并且已经阅读了ctest 文档。特别是 add_test 文档。我可以向add_test 提供“WORKING_DIRECTORY”。这将在“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
【问题讨论】: