file_helpers.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 GetTempDirectory() -> std::filesystem::path {
  13. if (char* tmpdir_env = getenv("TEST_TMPDIR"); tmpdir_env != nullptr) {
  14. return tmpdir_env;
  15. } else {
  16. return std::filesystem::temp_directory_path();
  17. }
  18. }
  19. auto ReadFile(std::filesystem::path path) -> ErrorOr<std::string> {
  20. std::ifstream file_stream(path);
  21. if (file_stream.fail()) {
  22. return Error(llvm::formatv("Error opening file: {0}", path));
  23. }
  24. std::stringstream buffer;
  25. buffer << file_stream.rdbuf();
  26. if (file_stream.fail()) {
  27. return Error(llvm::formatv("Error reading file: {0}", path));
  28. }
  29. return buffer.str();
  30. }
  31. auto WriteTestFile(llvm::StringRef name, llvm::StringRef contents)
  32. -> ErrorOr<std::filesystem::path> {
  33. std::filesystem::path test_tmpdir = GetTempDirectory();
  34. const auto* unit_test = ::testing::UnitTest::GetInstance();
  35. const auto* test_info = unit_test->current_test_info();
  36. std::filesystem::path test_file =
  37. test_tmpdir / llvm::formatv("{0}_{1}_{2}", test_info->test_suite_name(),
  38. test_info->name(), name)
  39. .str();
  40. // Make debugging a bit easier by cleaning up any files from previous runs.
  41. // This is only necessary when not run in Bazel's test environment.
  42. std::filesystem::remove(test_file);
  43. if (std::filesystem::exists(test_file)) {
  44. return Error(
  45. llvm::formatv("Unable to remove an existing file: {0}", test_file));
  46. }
  47. std::error_code ec;
  48. llvm::raw_fd_ostream test_file_stream(test_file.string(), ec);
  49. if (ec) {
  50. return Error(llvm::formatv("Test file error: {0}", ec.message()));
  51. }
  52. test_file_stream << contents;
  53. return test_file;
  54. }
  55. } // namespace Carbon::Testing