From: Gerd von Egidy Date: Wed, 16 Dec 2015 23:57:29 +0000 (+0100) Subject: implement pipe_to_string() and use it to shorten the test case sourcecode X-Git-Tag: v2.8~7 X-Git-Url: http://developer.intra2net.com/git/?a=commitdiff_plain;h=05b4f5e89afc0d161aed7dcf83400e038c06c601;p=libi2ncommon implement pipe_to_string() and use it to shorten the test case sourcecode --- diff --git a/src/pipestream.hxx b/src/pipestream.hxx index 1fca37e..734b99c 100644 --- a/src/pipestream.hxx +++ b/src/pipestream.hxx @@ -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 * diff --git a/test/test_filefunc.cpp b/test/test_filefunc.cpp index 237e8b2..d982b5a 100644 --- a/test/test_filefunc.cpp +++ b/test/test_filefunc.cpp @@ -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(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(dustr,duout); - BOOST_CHECK_EQUAL( string_to(dustr), du(unique_dir) ); + BOOST_CHECK_EQUAL( duout, du(unique_dir) ); // Unlink it BOOST_CHECK_EQUAL(true, I2n::recursive_delete(unique_dir));