source_buffer_test.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 "source/source_buffer.h"
  5. #include "gtest/gtest.h"
  6. #include "llvm/ADT/SmallString.h"
  7. #include "llvm/ADT/Twine.h"
  8. #include "llvm/Support/FileSystem.h"
  9. #include "llvm/Support/raw_ostream.h"
  10. namespace Carbon {
  11. namespace {
  12. TEST(SourceBufferTest, StringRep) {
  13. SourceBuffer buffer =
  14. SourceBuffer::CreateFromText(llvm::Twine("Hello") + " World");
  15. EXPECT_EQ("/text", buffer.Filename());
  16. EXPECT_EQ("Hello World", buffer.Text());
  17. // Give a custom filename.
  18. auto buffer2 =
  19. SourceBuffer::CreateFromText("Hello World Again!", "/custom/text");
  20. EXPECT_EQ("/custom/text", buffer2.Filename());
  21. EXPECT_EQ("Hello World Again!", buffer2.Text());
  22. }
  23. auto CreateTestFile(llvm::StringRef text) -> std::string {
  24. int fd = -1;
  25. llvm::SmallString<1024> path;
  26. auto error_code =
  27. llvm::sys::fs::createTemporaryFile("test_file", ".txt", fd, path);
  28. if (error_code) {
  29. llvm::report_fatal_error(llvm::Twine("Failed to create temporary file: ") +
  30. error_code.message());
  31. }
  32. llvm::raw_fd_ostream out_stream(fd, /*shouldClose=*/true);
  33. out_stream << text;
  34. out_stream.close();
  35. return path.str().str();
  36. }
  37. TEST(SourceBufferTest, FileRep) {
  38. auto test_file_path = CreateTestFile("Hello World");
  39. auto expected_buffer = SourceBuffer::CreateFromFile(test_file_path);
  40. ASSERT_TRUE(static_cast<bool>(expected_buffer))
  41. << "Error message: " << expected_buffer.takeError();
  42. SourceBuffer& buffer = *expected_buffer;
  43. EXPECT_EQ(test_file_path, buffer.Filename());
  44. EXPECT_EQ("Hello World", buffer.Text());
  45. }
  46. } // namespace
  47. } // namespace Carbon