生成临时文件/文件夹 c++ GTEST

Generate temporary file/folder c++ GTEST

本文关键字:c++ GTEST 文件夹 临时文件      更新时间:2023-10-16

>我需要为测试生成临时文件。看起来我不能使用mkstemp因为我需要文件名具有特定的后缀,但文件名的其余部分我不在乎。GTest中是否有办法创建一个临时文件来处理文件的创建以及测试结束时的删除。

另一种方法是创建我自己的类来做到这一点。

虽然它不构建临时文件,但googletest提供了两个不同的测试宏,TEST和TEST_F,后者是固定的。 请参阅标题为"测试夹具:使用相同的数据配置..."在入门中了解有关夹具的更多信息。

我对这个问题的解决方案是使用带有固定测试的Boost.Filesystem。 我希望能够拥有一个为所有测试共享的命名临时子目录。 在这种情况下,我正在调整我的情况以适应 OP 对指定后缀的请求。

包括:

// Boost.Filesystem VERSION 3 required
#include <string>
#include <boost/filesystem.hpp>

测试类定义:

class ArchiveTest : public ::testing::Test {
protected:
    boost::filesystem::path mTempFileRel;
    boost::filesystem::path mTempFileAbs;
    std::ofstream mExampleStream;
    ArchiveTest() {
         mTempFileRel = boost::filesystem::unique_path("%%%%_%%%%_%%%%_%%%%.your_suffix");
         mTempFileAbs = boost::filesystem::temp_directory_path() / mTempFileRel;
         mExampleStream.open(mTempFileAbs);
    }
    ~ArchiveTest() {
        if(mExampleStream.is_open())
        {
            mExampleStream.close();
        }
    }
    // Note there are SetUp() and TearDown() that are probably better for
    // actually opening/closing in case something throws
};

注意:虽然你可以在构造函数或 SetUp() 中创建文件对象并在析构函数或 TearDown() 中关闭,但我更喜欢在测试中这样做,因为我不使用在所有固定测试中创建的文件名。 因此,在使用流示例时要格外小心。

这是我对文件名的使用:

// Tests that an ArchiveFile can be written
TEST_F(ArchiveTest, TestWritingArchive) {
    try
    {
        TheInfo info_;  // some metadata for the archive
        MyArchive archive_; // Custom class for an archive
        archive_.attachToFile(mTempFile, info_);
        ...
    }
    catch(const std::exception& e_)
    {
        FAIL() << "Caught an exception in " << typeid(*this).name()
               << ": " << e_.what();
    }
}

如果您对"%"字符感到好奇,请从unique_path上的参考中:

unique_path函数生成适合创建的路径名 临时文件,包括目录。名称基于模型 使用百分号字符指定替换为 随机十六进制数字。

笔记:

  1. 感谢罗比·莫里森(Robbie Morrison)对临时文件的简明回答,让我开始了
  2. 我从更长的类定义和一组测试中复制/粘贴了摘录,所以如果有任何不清楚或是否存在印刷(复制/粘贴)错误,请告诉我。

Googletest现在包含testing::TempDir(),但是它只返回/tmp/或特定于平台的等效项,它不进行任何清理。

你可以在某些系统上使用 mkstemps,尽管它是非标准的。从 mkstemp 的手册页:

mkstemps() 函数类似于 mkstemp(),只是模板中的字符串包含后缀字符。因此,模板的形式前缀XXXXXX后缀,字符串XXXXXX被修改为mkstemp()。

因此,你可以像这样使用 mkstemps:

// The template in use. Replace '.suffix' with your needed suffix.
char temp[] = "XXXXXX.suffix";
// strlen is used for ease of illistration.
int fd = mkstemps(temp, strlen(".suffix"));
// Since the template is modified, you now have the name of the file.
puts(temp);

您需要跟踪文件名,以便在程序结束时将其删除。如果您希望能够将所有这些文件放入/tmp中,您应该能够添加"/tmp/"作为前缀。但是,似乎没有办法创建临时目录。

创建文件和文件夹不在任何测试框架(包括 Google 测试)的范围内。为此,将其他一些库链接到测试二进制文件。