From: Alexey Spiridonov Date: Sat, 21 Mar 2015 04:58:14 +0000 (-0700) Subject: Add ChangeToTempDir to TestUtil X-Git-Tag: v0.32.0~4 X-Git-Url: http://plrg.eecs.uci.edu/git/?a=commitdiff_plain;h=87a4b661d610545a18f8d743c5d7b5df1c6bcfcd;p=folly.git Add ChangeToTempDir to TestUtil 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 --- diff --git a/folly/experimental/TestUtil.cpp b/folly/experimental/TestUtil.cpp index 5b2c4348..788e3628 100644 --- a/folly/experimental/TestUtil.cpp +++ b/folly/experimental/TestUtil.cpp @@ -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 diff --git a/folly/experimental/TestUtil.h b/folly/experimental/TestUtil.h index 2a736c96..adf8be39 100644 --- a/folly/experimental/TestUtil.h +++ b/folly/experimental/TestUtil.h @@ -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 diff --git a/folly/experimental/test/TestUtilTest.cpp b/folly/experimental/test/TestUtilTest.cpp index eee1515a..4239c94c 100644 --- a/folly/experimental/test/TestUtilTest.cpp +++ b/folly/experimental/test/TestUtilTest.cpp @@ -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);