xref: /aosp_15_r20/external/pytorch/c10/test/util/tempfile_test.cpp (revision da0073e96a02ea20f0ac840b70461e3646d07c45)
1 #include <c10/util/tempfile.h>
2 #include <gtest/gtest.h>
3 #include <sys/stat.h>
4 #include <optional>
5 
6 #if !defined(_WIN32)
file_exists(const char * path)7 static bool file_exists(const char* path) {
8   struct stat st {};
9   return stat(path, &st) == 0 && S_ISREG(st.st_mode);
10 }
directory_exists(const char * path)11 static bool directory_exists(const char* path) {
12   struct stat st {};
13   return stat(path, &st) == 0 && S_ISDIR(st.st_mode);
14 }
15 #else
file_exists(const char * path)16 static bool file_exists(const char* path) {
17   struct _stat st {};
18   return _stat(path, &st) == 0 && ((st.st_mode & _S_IFMT) == _S_IFREG);
19 }
directory_exists(const char * path)20 static bool directory_exists(const char* path) {
21   struct _stat st {};
22   return _stat(path, &st) == 0 && ((st.st_mode & _S_IFMT) == _S_IFDIR);
23 }
24 #endif // !defined(_WIN32)
25 
TEST(TempFileTest,MatchesExpectedPattern)26 TEST(TempFileTest, MatchesExpectedPattern) {
27   c10::TempFile file = c10::make_tempfile("test-pattern-");
28 
29 #if defined(_WIN32)
30   ASSERT_TRUE(file.open());
31 #endif
32   ASSERT_TRUE(file_exists(file.name.c_str()));
33 #if !defined(_WIN32)
34   ASSERT_NE(file.name.find("test-pattern-"), std::string::npos);
35 #endif // !defined(_WIN32)
36 }
37 
TEST(TempDirTest,tryMakeTempdir)38 TEST(TempDirTest, tryMakeTempdir) {
39   std::optional<c10::TempDir> tempdir = c10::make_tempdir("test-dir-");
40   std::string tempdir_name = tempdir->name;
41 
42   // directory should exist while tempdir is alive
43   ASSERT_TRUE(directory_exists(tempdir_name.c_str()));
44 
45   // directory should not exist after tempdir destroyed
46   tempdir.reset();
47   ASSERT_FALSE(directory_exists(tempdir_name.c_str()));
48 }
49