是否可以使用 Catch2 来测试 MPI 代码?

Sam*_*nut 4 c++ mpi catch2

我正在使用相当大的 MPI 代码。我开始将单元测试包含到现有的代码库中。但是,一旦被测单元使用 MPI 例程,测试可执行文件就会崩溃,并显示错误消息“之前调用 MPI 例程MPI_Init

  • 解决这个问题的最佳方法是什么?
  • 我可以使用多个 MPI 等级运行测试吗?

pwa*_*aul 7

对的,这是可能的。

https://github.com/catchorg/Catch2/issues/566 中所述,您必须提供自定义主函数。

#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include <mpi.h>

int main( int argc, char* argv[] ) {
    MPI_Init(&argc, &argv);
    int result = Catch::Session().run( argc, argv );
    MPI_Finalize();
    return result;
}
Run Code Online (Sandbox Code Playgroud)

为了增强将 Catch2 与 MPI 结合使用的体验,您可能希望避免冗余的控制台输出。这需要将一些代码注入到 catch.hpp 的 ConsoleReporter::testRunEnded 中。

#include <mpi.h>
void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
    int rank id = -1;
    MPI Comm rank(MPI COMM WORLD,&rank id);
    if(rank id != 0 && testRunStats.totals.testCases.allPassed())
        return;
    printTotalsDivider(_testRunStats.totals);
    printTotals(_testRunStats.totals);
    stream << std::endl;
    StreamingReporterBase::testRunEnded(_testRunStats);
}
Run Code Online (Sandbox Code Playgroud)

最后,您可能还想使用不同数量的 MPI 等级执行测试用例。我发现以下是一个简单且有效的解决方案:

SCENARIO("Sequential Testing", "[1rank]") {
    // Perform sequential tests here
}
SCENARIO("Parallel Testing", "[2ranks]") {
    // Perform parallel tests here
}
Run Code Online (Sandbox Code Playgroud)

然后你可以单独调用标签场景

mpiexec -1 ./application [1rank]
mpiexec -2 ./application [2rank]
Run Code Online (Sandbox Code Playgroud)