implement pipe_to_string() and use it to shorten the test case sourcecode
authorGerd von Egidy <gerd.von.egidy@intra2net.com>
Wed, 16 Dec 2015 23:57:29 +0000 (00:57 +0100)
committerGerd von Egidy <gerd.von.egidy@intra2net.com>
Wed, 16 Dec 2015 23:57:29 +0000 (00:57 +0100)
src/pipestream.hxx
test/test_filefunc.cpp

index 1fca37e..734b99c 100644 (file)
@@ -122,6 +122,42 @@ public:
     { buf.store_exit_status(_status_set, _exit_status); }
 };
 
+/** @brief runs command and returns it's output as string
+ *  @param command the full command with all parameters
+ *  @param exit_status the full exit status, use WEXITSTATUS to get the "regular" return code
+ *  @returns the output (stderr) of the called program
+ */
+std::string pipe_to_string(const std::string& command, std::string *error=NULL, int *_exit_status=NULL)
+{
+    std::string result;
+    bool exit_set;
+
+    try
+    {
+        inpipestream ips(command);
+
+        ips.store_exit_status(&exit_set, _exit_status);
+
+        char buffer[2048];
+        while (ips.good())
+        {
+            ips.read(buffer, sizeof(buffer));
+            result.append(buffer, ips.gcount());
+        }
+    }
+    catch (pipestream_error &e)
+    {
+        if (error)
+            *error=e.what();
+        return "";
+    }
+    catch(...)
+    {
+        throw;
+    }
+
+    return result;
+}
 
 /** @brief runs command and provides buffered ouptput from it through pipe
  *
index 237e8b2..d982b5a 100644 (file)
@@ -592,10 +592,7 @@ BOOST_AUTO_TEST_CASE(FileContentDiffersEqualSize)
 
 BOOST_AUTO_TEST_CASE(FreeDiskSpace1)
 {
-    inpipestream cmd_df("df -B 1 --output=avail /tmp | tail -n 1");
-    string dfstr;
-    if (cmd_df)
-        getline(cmd_df, dfstr);
+    string dfstr=pipe_to_string("df -B 1 --output=avail /tmp | tail -n 1");
 
     long long dfout=-1;
     string_to<long long>(dfstr,dfout);
@@ -623,12 +620,11 @@ BOOST_AUTO_TEST_CASE(TestDu)
     BOOST_CHECK_EQUAL(true, I2n::mkdir(sub_dir));
     BOOST_CHECK_EQUAL(true, write_file(some_file, "foobar and some more data, even more that Tom would like to see in one line without linebreak but I still want to have it all here"));
 
-    inpipestream cmd_du(string("du --block-size=1 --sum ")+unique_dir+" | cut -f 1");
-    string dustr;
-    if (cmd_du)
-        getline(cmd_du, dustr);
+    string dustr=pipe_to_string(string("du --block-size=1 --sum ")+unique_dir+" | cut -f 1");
+    long long duout=-1;
+    string_to<long long>(dustr,duout);
 
-    BOOST_CHECK_EQUAL( string_to<long long>(dustr), du(unique_dir) );
+    BOOST_CHECK_EQUAL( duout, du(unique_dir) );
 
     // Unlink it
     BOOST_CHECK_EQUAL(true, I2n::recursive_delete(unique_dir));