Program Listing for File files.hpp

Return to documentation for file (include/eat/testing/files.hpp)

#pragma once

#include <algorithm>
#include <catch2/internal/catch_context.hpp>
#include <filesystem>
#include <fstream>

namespace eat::testing {

inline bool files_equal(const std::string &fname_a, const std::string &fname_b) {
  std::fstream file_a(fname_a, std::ios_base::in | std::ios_base::binary);
  std::fstream file_b(fname_a, std::ios_base::in | std::ios_base::binary);

  if (!file_a.is_open()) throw std::runtime_error("could not open " + fname_a);
  if (!file_b.is_open()) throw std::runtime_error("could not open " + fname_b);

  std::istreambuf_iterator<char> it_a(file_a), it_b(file_b), end;

  return std::equal(it_a, end, it_b, end);
}

namespace detail {

inline std::string current_test_name() { return Catch::getResultCapture().getCurrentTestName(); }

}  // namespace detail

class TempDir {
 public:
  TempDir() : path(std::filesystem::path{"test_tmp"} / detail::current_test_name()) {
    std::filesystem::create_directories(path);
  }

  std::filesystem::path operator/(const std::string &fname) { return path / fname; }

 private:
  std::filesystem::path path;
};

};  // namespace eat::testing