Add ChangeToTempDir to TestUtil
authorAlexey Spiridonov <lesha@fb.com>
Sat, 21 Mar 2015 04:58:14 +0000 (21:58 -0700)
committerNoam Lerner <noamler@fb.com>
Wed, 25 Mar 2015 22:35:37 +0000 (15:35 -0700)
Summary: It's convenient to be able to write tempfiles in the current directory. This provides a one-liner way of doing that in tests.

Test Plan: unit test

Reviewed By: yfeldblum@fb.com

Subscribers: simpkins, folly-diffs@, yfeldblum

FB internal diff: D1931918

Signature: t1:1931918:1426913634:f988fb3c5061f5909e309dcaf42742d9b2ed18c6

folly/experimental/TestUtil.cpp
folly/experimental/TestUtil.h
folly/experimental/test/TestUtilTest.cpp

index 5b2c43484673246f8769595e89f690ba0319f369..788e36287fea2d759999c9fac365324bd7cb8ac7 100644 (file)
@@ -107,5 +107,15 @@ TemporaryDirectory::~TemporaryDirectory() {
   }
 }
 
+ChangeToTempDir::ChangeToTempDir() : initialPath_(fs::current_path()) {
+  std::string p = dir_.path().native();
+  ::chdir(p.c_str());
+}
+
+ChangeToTempDir::~ChangeToTempDir() {
+  std::string p = initialPath_.native();
+  ::chdir(p.c_str());
+}
+
 }  // namespace test
 }  // namespace folly
index 2a736c96ad923d8ae10d835805a9dcb523fbb9e3..adf8be39578eed9d86a1b58bb397cf18c361350a 100644 (file)
@@ -88,6 +88,22 @@ class TemporaryDirectory {
   fs::path path_;
 };
 
+/**
+ * Changes into a temporary directory, and deletes it with all its contents
+ * upon destruction, also changing back to the original working directory.
+ */
+class ChangeToTempDir {
+public:
+  ChangeToTempDir();
+  ~ChangeToTempDir();
+
+  const fs::path& path() const { return dir_.path(); }
+
+private:
+  fs::path initialPath_;
+  TemporaryDirectory dir_;
+};
+
 }  // namespace test
 }  // namespace folly
 
index eee1515a5020f4e9a1ba2758b0ae83d10ff31aaf..4239c94c394a5b152a3970b253f118c32a5c0bfe 100644 (file)
@@ -100,6 +100,15 @@ TEST(TemporaryDirectory, DeleteOnDestruction) {
   testTemporaryDirectory(TemporaryDirectory::Scope::DELETE_ON_DESTRUCTION);
 }
 
+TEST(ChangeToTempDir, ChangeDir) {
+  auto pwd1 = fs::current_path();
+  {
+    ChangeToTempDir d;
+    EXPECT_NE(pwd1, fs::current_path());
+  }
+  EXPECT_EQ(pwd1, fs::current_path());
+}
+
 int main(int argc, char *argv[]) {
   testing::InitGoogleTest(&argc, argv);
   gflags::ParseCommandLineFlags(&argc, &argv, true);