【问题标题】:How to make ctest run test executables in a transient/temporary directory如何使 ctest 在临时/临时目录中运行测试可执行文件
【发布时间】: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

【问题讨论】:

    标签: cmake ctest


    【解决方案1】:

    通常,测试框架会提供某种类型的测试前(设置)和测试后(清理)任务。 And so does CTest.

    将以下CTestCustom.ctest 文件添加到您示例的构建目录中,每次测试都会成功:

    # CTestCustom.ctest
    set(CTEST_CUSTOM_POST_TEST "rm foo.txt")
    

    对于更复杂的任务,您可能想要创建一个自定义脚本,但这就是调用它的方式。

    【讨论】:

    • 谢谢,@Stanley F。我赞成并接受了这个,因为它肯定是最好的答案(:我会考虑使用预测试任务,看看我能走多远。如果有是如何让每个测试在临时目录中执行的任何很好的例子,那么我很想听听。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多