libmoost
/home/mhx/git/github/libmoost/include/moost/testing/test_directory_creator.hpp
Go to the documentation of this file.
00001 /* vim:set ts=3 sw=3 sts=3 et: */
00028 #ifndef MOOST_TEST_DIRECTORY_CREATOR_H_
00029 #define MOOST_TEST_DIRECTORY_CREATOR_H_
00030 
00031 #include <string>
00032 #include <iostream>
00033 #include <boost/filesystem/path.hpp>
00034 #include <boost/filesystem/operations.hpp>
00035 
00036 namespace moost { namespace testing {
00037 
00038    // Creates a directory (if it already exists it removes it then re-creates it
00039    // to ensure a steril environment) for testing purposes and removes it after.
00040 
00041    class test_directory_creator
00042    {
00043    public:
00044       test_directory_creator(std::string const & path = "Test_Directory_GUID_2E222A01_3D94_4360_968D_8957DD89417D") : path_(path)
00045       {
00046          remove_dir(); // just in case it already exists
00047          boost::filesystem::create_directory(path_);
00048       }
00049 
00050       virtual ~test_directory_creator()
00051       {
00052          remove_dir();
00053       }
00054 
00055       virtual std::string const & GetPath() const { return path_; }
00056 
00057       virtual std::string GetFilePath(std::string const & sFilename) const
00058       {
00059          return (boost::filesystem::path(path_) /= sFilename).string();
00060       }
00061 
00062       void remove_dir(bool throw_on_error = false) const
00063       {
00064          try
00065          {
00066             boost::filesystem::remove_all(path_);
00067          }
00068          catch(std::exception const & e)
00069          {
00070             // if it fails it'll (hopefully) be 'cos it never existed in the first place
00071             std::cerr << "Failed to remove path " << path_ << ": " << e.what() << "\n";
00072 
00073             if (throw_on_error) throw;
00074          }
00075       }
00076 
00077       void create_dir(bool throw_on_error = false) const
00078       {
00079          try
00080          {
00081             boost::filesystem::create_directory(path_);
00082          }
00083          catch(std::exception const & e)
00084          {
00085             std::cerr << "Failed to create path " << path_ << ": " << e.what() << "\n";
00086             if (throw_on_error) throw;
00087          }
00088       }
00089 
00090    private:
00091       std::string path_;
00092    };
00093 
00094 }}
00095 
00096 #endif // MOOST_TEST_DIRECTORY_CREATOR_H_