2016-07-15 100 views
2

我需要爲測試生成臨時文件。它看起來像我不能使用mkstemp,因爲我需要文件名具有特定的後綴,但其餘的文件名我不在乎。 GTest有沒有辦法創建一個臨時文件來處理文件的創建以及測試結束時的刪除。生成臨時文件/文件夾C++ GTEST

另一種方法是創建我自己的類來做到這一點。

+0

谷歌測試AFAIK沒有內置。 –

回答

1

創建文件和文件夾不在任何測試框架的範圍內,包括Google測試。爲了這個目的,將一些其他庫鏈接到您的測試二進制文件。

2

儘管它不構建臨時文件,但googletest提供了兩種不同的測試宏,TEST和TEST_F,後者是固定的。請參閱the Primer標題爲「測試夾具:使用相同的數據配置...」以獲取更多有關夾具的信息。

我對這個問題的解決方案是使用Boost.Filesystem和fixtured測試。我希望能夠擁有一個名爲temp的子目錄,該目錄是爲所有測試共享的。在這種情況下,我正在調整我的情況以適應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 
}; 

注意:雖然你可以在構造或設置(),並關閉在析構函數或拆除創建文件對象()我更喜歡在測試中這樣做,因爲我不使用在所有固定測試中創建的文件名。因此,在使用流示例時要格外小心。

這是我使用的文件名:

// 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(); 
    } 
} 

如果你是好奇「%」字符,從the reference on unique_path

的unique_path函數生成適合創建的路徑名臨時文件,包括目錄。該名稱基於型號 ,該型號使用百分號符號指定替換爲 隨機十六進制數字。

注:

  1. 感謝Robbie Morrisonconcise answer上讓我開始
  2. 我複製/粘貼摘錄從一個更長的類定義和設置的測試臨時文件,所以不要讓我知道有什麼不清楚或是否有印刷(複製/粘貼)錯誤。
0

可以在某些系統上使用mkstemps,儘管它是非標準的。從man page爲mkstemp:

的mkstemps()函數就像mkstemp(),除了在模板中的字符串中包含的字符suffixlen後綴。因此,模板的形式爲prefixXXXXXXsuffix,字符串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 /」添加爲前綴。但是,似乎沒有辦法讓它創建一個臨時目錄。