1 //===-- TestUtilities.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 "TestUtilities.h" 10 #include "llvm/ADT/SmallString.h" 11 #include "llvm/ObjectYAML/yaml2obj.h" 12 #include "llvm/Support/FileSystem.h" 13 #include "llvm/Support/Path.h" 14 #include "llvm/Support/Program.h" 15 #include "llvm/Support/YAMLTraits.h" 16 #include "gtest/gtest.h" 17 18 using namespace lldb_private; 19 20 extern const char *TestMainArgv0; 21 22 std::string lldb_private::GetInputFilePath(const llvm::Twine &name) { 23 llvm::SmallString<128> result = llvm::sys::path::parent_path(TestMainArgv0); 24 llvm::sys::fs::make_absolute(result); 25 llvm::sys::path::append(result, "Inputs", name); 26 return std::string(result.str()); 27 } 28 29 llvm::Expected<TestFile> TestFile::fromYaml(llvm::StringRef Yaml) { 30 const auto *Info = testing::UnitTest::GetInstance()->current_test_info(); 31 assert(Info); 32 llvm::SmallString<128> Name; 33 int FD; 34 if (std::error_code EC = llvm::sys::fs::createTemporaryFile( 35 llvm::Twine(Info->test_case_name()) + "-" + Info->name(), "test", FD, 36 Name)) 37 return llvm::errorCodeToError(EC); 38 llvm::FileRemover Remover(Name); 39 { 40 llvm::raw_fd_ostream OS(FD, /*shouldClose*/ true); 41 llvm::yaml::Input YIn(Yaml); 42 if (!llvm::yaml::convertYAML(YIn, OS, [](const llvm::Twine &Msg) {})) 43 return llvm::createStringError(llvm::inconvertibleErrorCode(), 44 "convertYAML() failed"); 45 } 46 return TestFile(Name, std::move(Remover)); 47 } 48 49 llvm::Expected<TestFile> TestFile::fromYamlFile(const llvm::Twine &Name) { 50 auto BufferOrError = 51 llvm::MemoryBuffer::getFile(GetInputFilePath(Name), /*FileSize*/ -1, 52 /*RequiresNullTerminator*/ false); 53 if (!BufferOrError) 54 return llvm::errorCodeToError(BufferOrError.getError()); 55 return fromYaml(BufferOrError.get()->getBuffer()); 56 } 57 58 TestFile::~TestFile() { 59 if (!Name) 60 return; 61 if (std::error_code EC = 62 llvm::sys::fs::remove(*Name, /*IgnoreNonExisting*/ false)) 63 GTEST_LOG_(WARNING) << "Failed to delete `" << Name->c_str() 64 << "`: " << EC.message(); 65 } 66