Belle II Software  release-05-02-19
FileSystem.cc
1 #include <framework/utilities/FileSystem.h>
2 #include <framework/utilities/ScopeGuard.h>
3 #include <boost/filesystem.hpp>
4 
5 #include <gtest/gtest.h>
6 
7 #include <sys/wait.h>
8 
9 #include <unistd.h>
10 
11 using namespace std;
12 using namespace Belle2;
13 namespace fs = boost::filesystem;
14 
15 namespace {
16  TEST(Utilities, TemporaryFile)
17  {
18  std::string filename;
19  {
21  filename = temp.getName();
22  ASSERT_TRUE(temp.is_open());
23  ASSERT_TRUE(fs::exists(filename));
24  }
25  ASSERT_FALSE(fs::exists(filename));
26  }
27  TEST(Utilities, FileSystem)
28  {
29  std::string filename;
30  {
32  filename = temp.getName();
33  ASSERT_TRUE(FileSystem::fileExists(filename));
34  ASSERT_FALSE(FileSystem::isDir(filename));
35  ASSERT_TRUE(FileSystem::fileDirExists(filename));
36 
37  {
38  //check relative filenames
39  auto pwd = ScopeGuard::guardWorkingDirectory("/tmp"); //don't influence other tests by changing pwd
40  std::string relname = fs::relative(filename, "/tmp").string();
41  ASSERT_TRUE(FileSystem::fileExists(relname));
42  chdir("/");
43  ASSERT_FALSE(FileSystem::fileExists(relname));
44  }
45  }
46  ASSERT_FALSE(FileSystem::fileExists(filename));
47  ASSERT_FALSE(FileSystem::isDir(filename));
48  ASSERT_TRUE(FileSystem::fileDirExists(filename));
49 
50  ASSERT_TRUE(FileSystem::isDir("/"));
51  }
52  TEST(Utilities, Lock)
53  {
55  std::string filename = temp.getName();
56 
57  //check 0-timeout locks work
58  FileSystem::Lock lk(filename);
59  EXPECT_TRUE(lk.lock(0));
60 
61  if (pid_t pid = fork()) {
62  //mother process
63 
64  //NOTE: in same process, the lock is NOT exclusive!
65  EXPECT_TRUE(lk.lock(0));
66  int status = 0;
67  waitpid(pid, &status, 0);
68  EXPECT_TRUE(WIFEXITED(status));
69  EXPECT_EQ(0, WEXITSTATUS(status));
70  } else {
71  //child process
72  //do not use an ASSERT_TRUE or something here, or we'll run tests twice
73  if (lk.lock(0))
74  exit(1);
75 
76  FileSystem::Lock lk2(filename);
77  if (lk2.lock(0))
78  exit(1);
79 
80  exit(0);
81  }
82  }
83 } // namespace
Belle2::FileSystem::TemporaryFile::getName
std::string getName() const
get filename of the temporary file
Definition: FileSystem.h:151
Belle2::FileSystem
Utility functions related to filename validation and filesystem access.
Definition: FileSystem.h:30
Belle2
Abstract base class for different kinds of events.
Definition: MillepedeAlgorithm.h:19
Belle2::FileSystem::TemporaryFile
Helper file to create a temporary file and ensure deletion if object goes out of scope.
Definition: FileSystem.h:138
Belle2::TEST
TEST(TestgetDetectorRegion, TestgetDetectorRegion)
Test Constructors.
Definition: utilityFunctions.cc:18
Belle2::FileSystem::Lock
Helper class for locking a file.
Definition: FileSystem.h:107
alignment.constraints_generator.filename
filename
File name.
Definition: constraints_generator.py:224