file_helpers.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "testing/base/file_helpers.h"
  5. #include <gtest/gtest.h>
  6. #include <cstdlib>
  7. #include <fstream>
  8. #include <sstream>
  9. #include <string>
  10. #include <system_error>
  11. namespace Carbon::Testing {
  12. auto ReadFile(std::filesystem::path path) -> ErrorOr<std::string> {
  13. std::ifstream file_stream(path);
  14. if (file_stream.fail()) {
  15. return Error(llvm::formatv("Error opening file: {0}", path));
  16. }
  17. std::stringstream buffer;
  18. buffer << file_stream.rdbuf();
  19. if (file_stream.fail()) {
  20. return Error(llvm::formatv("Error reading file: {0}", path));
  21. }
  22. return buffer.str();
  23. }
  24. auto WriteTestFile(llvm::StringRef name, llvm::StringRef contents)
  25. -> ErrorOr<std::filesystem::path> {
  26. std::filesystem::path test_tmpdir;
  27. if (char* tmpdir_env = getenv("TEST_TMPDIR"); tmpdir_env != nullptr) {
  28. test_tmpdir = std::string(tmpdir_env);
  29. } else {
  30. test_tmpdir = std::filesystem::temp_directory_path();
  31. }
  32. const auto* unit_test = ::testing::UnitTest::GetInstance();
  33. const auto* test_info = unit_test->current_test_info();
  34. std::filesystem::path test_file =
  35. test_tmpdir / llvm::formatv("{0}_{1}_{2}", test_info->test_suite_name(),
  36. test_info->name(), name)
  37. .str();
  38. // Make debugging a bit easier by cleaning up any files from previous runs.
  39. // This is only necessary when not run in Bazel's test environment.
  40. std::filesystem::remove(test_file);
  41. if (std::filesystem::exists(test_file)) {
  42. return Error(
  43. llvm::formatv("Unable to remove an existing file: {0}", test_file));
  44. }
  45. std::error_code ec;
  46. llvm::raw_fd_ostream test_file_stream(test_file.string(), ec);
  47. if (ec) {
  48. return Error(llvm::formatv("Test file error: {0}", ec.message()));
  49. }
  50. test_file_stream << contents;
  51. return test_file;
  52. }
  53. } // namespace Carbon::Testing