source_buffer_test.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 "toolchain/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::Testing {
  11. namespace {
  12. TEST(SourceBufferTest, StringRep) {
  13. auto buffer = SourceBuffer::CreateFromText(llvm::Twine("Hello") + " World");
  14. EXPECT_EQ("/text", buffer->filename());
  15. EXPECT_EQ("Hello World", buffer->text());
  16. }
  17. TEST(SourceBufferText, StringRepWithFilename) {
  18. // Give a custom filename.
  19. auto buffer =
  20. SourceBuffer::CreateFromText("Hello World Again!", "/custom/text");
  21. EXPECT_EQ("/custom/text", buffer->filename());
  22. EXPECT_EQ("Hello World Again!", buffer->text());
  23. }
  24. auto CreateTestFile(llvm::StringRef text) -> std::string {
  25. int fd = -1;
  26. llvm::SmallString<1024> path;
  27. auto error_code =
  28. llvm::sys::fs::createTemporaryFile("test_file", ".txt", fd, path);
  29. if (error_code) {
  30. llvm::report_fatal_error(llvm::Twine("Failed to create temporary file: ") +
  31. error_code.message());
  32. }
  33. llvm::raw_fd_ostream out_stream(fd, /*shouldClose=*/true);
  34. out_stream << text;
  35. out_stream.close();
  36. return path.str().str();
  37. }
  38. TEST(SourceBufferTest, FileRep) {
  39. auto test_file_path = CreateTestFile("Hello World");
  40. auto expected_buffer = SourceBuffer::CreateFromFile(test_file_path);
  41. ASSERT_TRUE(static_cast<bool>(expected_buffer))
  42. << "Error message: " << toString(expected_buffer.takeError());
  43. SourceBuffer& buffer = *expected_buffer;
  44. EXPECT_EQ(test_file_path, buffer.filename());
  45. EXPECT_EQ("Hello World", buffer.text());
  46. }
  47. TEST(SourceBufferTest, FileRepEmpty) {
  48. auto test_file_path = CreateTestFile("");
  49. auto expected_buffer = SourceBuffer::CreateFromFile(test_file_path);
  50. ASSERT_TRUE(static_cast<bool>(expected_buffer))
  51. << "Error message: " << toString(expected_buffer.takeError());
  52. SourceBuffer& buffer = *expected_buffer;
  53. EXPECT_EQ(test_file_path, buffer.filename());
  54. EXPECT_EQ("", buffer.text());
  55. }
  56. } // namespace
  57. } // namespace Carbon::Testing