file_helpers.cpp 2.0 KB

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