Aktualizr
C++ SOTA Client
test_utils.cc
1 #include "test_utils.h"
2 
3 #include <signal.h>
4 
5 #if defined(OS_LINUX)
6 #include <sys/prctl.h>
7 #endif
8 #include <fstream>
9 #include <string>
10 
11 #include <boost/filesystem.hpp>
12 
13 std::string TestUtils::getFreePort() {
14  int s = socket(AF_INET, SOCK_STREAM, 0);
15  if (s == -1) {
16  std::cout << "socket() failed: " << errno;
17  throw std::runtime_error("Could not open socket");
18  }
19  struct sockaddr_in soc_addr;
20  memset(&soc_addr, 0, sizeof(struct sockaddr_in));
21  soc_addr.sin_family = AF_INET;
22  soc_addr.sin_addr.s_addr = INADDR_ANY;
23  soc_addr.sin_port = htons(INADDR_ANY);
24 
25  if (bind(s, (struct sockaddr *)&soc_addr, sizeof(soc_addr)) == -1) {
26  std::cout << "bind() failed: " << errno;
27  throw std::runtime_error("Could not bind socket");
28  }
29 
30  struct sockaddr_in sa;
31  unsigned int sa_len = sizeof(sa);
32  if (getsockname(s, (struct sockaddr *)&sa, &sa_len) == -1) {
33  throw std::runtime_error("getsockname failed");
34  }
35  close(s);
36  return std::to_string(ntohs(sa.sin_port));
37 }
38 
39 void TestUtils::writePathToConfig(const boost::filesystem::path &toml_in, const boost::filesystem::path &toml_out,
40  const boost::filesystem::path &storage_path) {
41  // Append our temp_dir path as storage.path to the config file. This is a hack
42  // but less annoying than the alternatives.
43  boost::filesystem::copy_file(toml_in, toml_out);
44  std::string conf_path_str = toml_out.string();
45  std::ofstream cs(conf_path_str.c_str(), std::ofstream::app);
46  cs << "\n[storage]\npath = " << storage_path.string() << "\n";
47 }
48 
49 TestHelperProcess::TestHelperProcess(const std::string &argv0, const std::string &argv1) {
50  pid_ = fork();
51  if (pid_ == -1) {
52  throw std::runtime_error("Failed to execute process:" + argv0);
53  }
54  if (pid_ == 0) {
55 #if defined(OS_LINUX)
56  prctl(PR_SET_PDEATHSIG, SIGTERM);
57 #endif
58  execlp(argv0.c_str(), argv0.c_str(), argv1.c_str(), (char *)0);
59  }
60 }
61 
62 TestHelperProcess::~TestHelperProcess() {
63  assert(pid_);
64  kill(pid_, SIGINT);
65 }