1 //===- llvm/unittest/Support/FileUtilitiesTest.cpp - unit tests -----------===//
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/FileUtilities.h"
10 #include "llvm/Support/Errc.h"
11 #include "llvm/Support/ErrorHandling.h"
12 #include "llvm/Support/FileSystem.h"
13 #include "llvm/Support/MemoryBuffer.h"
14 #include "llvm/Support/Path.h"
15 #include "gtest/gtest.h"
16 #include <fstream>
17 
18 using namespace llvm;
19 using namespace llvm::sys;
20 
21 #define ASSERT_NO_ERROR(x)                                                     \
22   if (std::error_code ASSERT_NO_ERROR_ec = x) {                                \
23     SmallString<128> MessageStorage;                                           \
24     raw_svector_ostream Message(MessageStorage);                               \
25     Message << #x ": did not return errc::success.\n"                          \
26             << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n"          \
27             << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n";      \
28     GTEST_FATAL_FAILURE_(MessageStorage.c_str());                              \
29   } else {                                                                     \
30   }
31 
32 namespace {
33 TEST(writeFileAtomicallyTest, Test) {
34   // Create unique temporary directory for these tests
35   SmallString<128> RootTestDirectory;
36   ASSERT_NO_ERROR(
37     fs::createUniqueDirectory("writeFileAtomicallyTest", RootTestDirectory));
38 
39   SmallString<128> FinalTestfilePath(RootTestDirectory);
40   sys::path::append(FinalTestfilePath, "foo.txt");
41   const std::string TempUniqTestFileModel = FinalTestfilePath.str().str() + "-%%%%%%%%";
42   const std::string TestfileContent = "fooFOOfoo";
43 
44   llvm::Error Err = llvm::writeFileAtomically(TempUniqTestFileModel, FinalTestfilePath, TestfileContent);
45   ASSERT_FALSE(static_cast<bool>(Err));
46 
47   std::ifstream FinalFileStream(FinalTestfilePath.str());
48   std::string FinalFileContent;
49   FinalFileStream >> FinalFileContent;
50   ASSERT_EQ(FinalFileContent, TestfileContent);
51 }
52 } // anonymous namespace
53