1 //===- TempPathTest.cpp ---------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/Support/FileSystem.h" 10 #include "llvm/Support/MemoryBuffer.h" 11 #include "llvm/Testing/Support/SupportHelpers.h" 12 #include "gtest/gtest.h" 13 14 using namespace llvm; 15 using llvm::unittest::TempDir; 16 using llvm::unittest::TempFile; 17 using llvm::unittest::TempLink; 18 19 namespace { 20 21 TEST(TempPathTest, TempDir) { 22 Optional<TempDir> Dir1, Dir2; 23 StringRef Prefix = "temp-path-test"; 24 Dir1.emplace(Prefix, /*Unique=*/true); 25 EXPECT_EQ(Prefix, 26 sys::path::filename(Dir1->path()).take_front(Prefix.size())); 27 EXPECT_NE(Prefix, sys::path::filename(Dir1->path())); 28 29 std::string Path = Dir1->path().str(); 30 ASSERT_TRUE(sys::fs::exists(Path)); 31 32 Dir2 = std::move(*Dir1); 33 ASSERT_EQ(Path, Dir2->path()); 34 ASSERT_TRUE(sys::fs::exists(Path)); 35 36 Dir1 = std::nullopt; 37 ASSERT_TRUE(sys::fs::exists(Path)); 38 39 Dir2 = std::nullopt; 40 ASSERT_FALSE(sys::fs::exists(Path)); 41 } 42 43 TEST(TempPathTest, TempFile) { 44 TempDir D("temp-path-test", /*Unique=*/true); 45 ASSERT_TRUE(sys::fs::exists(D.path())); 46 47 Optional<TempFile> File1, File2; 48 File1.emplace(D.path("file"), "suffix", "content"); 49 EXPECT_EQ("file.suffix", sys::path::filename(File1->path())); 50 { 51 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = 52 MemoryBuffer::getFile(File1->path()); 53 ASSERT_TRUE(Buffer); 54 ASSERT_EQ("content", (*Buffer)->getBuffer()); 55 } 56 57 std::string Path = File1->path().str(); 58 ASSERT_TRUE(sys::fs::exists(Path)); 59 60 File2 = std::move(*File1); 61 ASSERT_EQ(Path, File2->path()); 62 ASSERT_TRUE(sys::fs::exists(Path)); 63 64 File1 = std::nullopt; 65 ASSERT_TRUE(sys::fs::exists(Path)); 66 67 File2 = std::nullopt; 68 ASSERT_FALSE(sys::fs::exists(Path)); 69 } 70 71 TEST(TempPathTest, TempLink) { 72 TempDir D("temp-path-test", /*Unique=*/true); 73 ASSERT_TRUE(sys::fs::exists(D.path())); 74 TempFile File(D.path("file"), "suffix", "content"); 75 76 Optional<TempLink> Link1, Link2; 77 Link1.emplace(File.path(), D.path("link")); 78 EXPECT_EQ("link", sys::path::filename(Link1->path())); 79 { 80 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = 81 MemoryBuffer::getFile(Link1->path()); 82 ASSERT_TRUE(Buffer); 83 ASSERT_EQ("content", (*Buffer)->getBuffer()); 84 } 85 86 std::string Path = Link1->path().str(); 87 ASSERT_TRUE(sys::fs::exists(Path)); 88 89 Link2 = std::move(*Link1); 90 ASSERT_EQ(Path, Link2->path()); 91 ASSERT_TRUE(sys::fs::exists(Path)); 92 93 Link1 = std::nullopt; 94 ASSERT_TRUE(sys::fs::exists(Path)); 95 96 Link2 = std::nullopt; 97 ASSERT_FALSE(sys::fs::exists(Path)); 98 } 99 100 } // namespace 101