test-utils.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. // SPDX-FileCopyrightText: 2019-2023 Ivan Baidakou
  3. #include "test-utils.h"
  4. #include "model/device_id.h"
  5. #include "structs.pb.h"
  6. #include "db/prefix.h"
  7. int main(int argc, char *argv[]) { return Catch::Session().run(argc, argv); }
  8. namespace syncspirit::test {
  9. bfs::path locate_path(const char *test_file) {
  10. auto path = bfs::path(test_file);
  11. if (bfs::exists(path)) {
  12. return path;
  13. }
  14. path = bfs::path("../") / path;
  15. if (bfs::exists(path)) {
  16. return path;
  17. }
  18. std::string err = "path not found: ";
  19. err += test_file;
  20. throw std::runtime_error(err);
  21. }
  22. std::string read_file(const bfs::path &path) {
  23. sys::error_code ec;
  24. auto filesize = bfs::file_size(path, ec);
  25. auto file_path = path.string();
  26. auto file_path_c = file_path.c_str();
  27. auto in = fopen(file_path_c, "rb");
  28. if (!in) {
  29. auto ec = sys::error_code{errno, sys::generic_category()};
  30. std::cout << "can't open " << file_path_c << " : " << ec.message() << "\n";
  31. return "";
  32. }
  33. assert(in);
  34. std::vector<char> buffer(filesize, 0);
  35. auto r = fread(buffer.data(), filesize, 1, in);
  36. assert(r == 1);
  37. fclose(in);
  38. return std::string(buffer.data(), filesize);
  39. }
  40. void write_file(const bfs::path &path, std::string_view content) {
  41. bfs::create_directories(path.parent_path());
  42. auto file_path = path.string();
  43. auto out = fopen(file_path.c_str(), "wb");
  44. if (!out) {
  45. auto ec = sys::error_code{errno, sys::generic_category()};
  46. std::cout << "can't open " << file_path << " : " << ec.message() << "\n";
  47. std::abort();
  48. }
  49. if (content.size()) {
  50. auto r = fwrite(content.data(), content.size(), 1, out);
  51. assert(r);
  52. }
  53. fclose(out);
  54. }
  55. std::string device_id2sha256(std::string_view device_id) {
  56. return std::string(model::device_id_t::from_string(device_id).value().get_sha256());
  57. }
  58. model::device_ptr_t make_device(std::string_view device_id, std::string_view name) {
  59. auto id = model::device_id_t::from_string(device_id).value();
  60. return model::device_t::create(id, name).assume_value();
  61. }
  62. std::string hash_string(const std::string_view &hash) noexcept {
  63. auto r = std::string();
  64. r.reserve(hash.size() * 2);
  65. for (size_t i = 0; i < hash.size(); ++i) {
  66. char buff[3];
  67. sprintf(buff, "%02x", (unsigned char)hash[i]);
  68. r += std::string_view(buff, 2);
  69. }
  70. return r;
  71. }
  72. } // namespace syncspirit::test