#include "cptest.h" #include #include #include #include #include "gtest/gtest.h" #include "debug.h" using namespace std; void cptestPrepareToDie() { Debug::setNewDefaultStdout(&std::cerr); // EXPECT_DEATH checks cerror for messages, so send them there. } CPTestTempfile::CPTestTempfile(const std::vector &lines) { // Create the file char temp_file_template[] = "/tmp/cptest_temp_file_XXXXXX"; int fd = mkstemp(temp_file_template); if (fd < 0) { // LCOV_EXCL_START - mkstemp rarely fails, can't cause it. ADD_FAILURE() << "Failed to open tempfile"; return; // LCOV_EXCL_STOP } fname = temp_file_template; // Template was modified to actual file name // Fill it with the requested lines for (const auto &l : lines) { EXPECT_EQ((unsigned long)write(fd, l.c_str(), l.size()), l.size()); EXPECT_EQ(write(fd, "\n", 1), 1); } close(fd); } CPTestTempfile::CPTestTempfile() : CPTestTempfile(std::vector{}) { } CPTestTempfile::~CPTestTempfile() { if (!fname.empty()) { unlink(fname.c_str()); } } string CPTestTempfile::readFile() const { int fd = open(fname.c_str(), 0); EXPECT_NE(fd, -1); string result; char buf[100]; while (true) { auto bytes_read = read(fd, buf, 100); if (bytes_read <= 0) break; result += string(buf, bytes_read); } return result; } // Parse Hex data, e.g. what's generated by "tcpdump -xx", into a vector vector cptestParseHex(const string &hex_text) { vector v; // Use stringstream and istream_iterator to break the input into whitespace separated strings stringstream str(hex_text); for (auto it = istream_iterator(str); it != istream_iterator(); it++) { const string &t = *it; size_t l = t.size(); if (l==0) continue; if (t[l-1]==':') continue; // tcpdump uses xxxx: to mark offsets, not data. So ignore it. dbgAssert(t.size() %2 == 0) << AlertInfo(AlertTeam::CORE, "testing") << "Expecting an even number of hex digits, " << t << " is invalid"; for (uint i=0; i &vec, bool print_offsets) { std::string res; int total_hex_groups_emitted = 0; int num_hex_groups_emitted_in_cur_line = 0; for (size_t i = 0; i