1 //===- raw_pwrite_stream_test.cpp - raw_pwrite_stream 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/ADT/SmallString.h" 10 #include "llvm/Config/llvm-config.h" 11 #include "llvm/Support/FileSystem.h" 12 #include "llvm/Support/FileUtilities.h" 13 #include "llvm/Support/raw_ostream.h" 14 #include "gtest/gtest.h" 15 16 using namespace llvm; 17 18 #define ASSERT_NO_ERROR(x) ASSERT_EQ(x, std::error_code()) 19 20 namespace { 21 22 TEST(raw_pwrite_ostreamTest, TestSVector) { 23 SmallVector<char, 0> Buffer; 24 raw_svector_ostream OS(Buffer); 25 OS << "abcd"; 26 StringRef Test = "test"; 27 OS.pwrite(Test.data(), Test.size(), 0); 28 EXPECT_EQ(Test, OS.str()); 29 30 #ifdef GTEST_HAS_DEATH_TEST 31 #ifndef NDEBUG 32 EXPECT_DEATH(OS.pwrite("12345", 5, 0), 33 "We don't support extending the stream"); 34 #endif 35 #endif 36 } 37 38 #ifdef _WIN32 39 #define setenv(name, var, ignore) _putenv_s(name, var) 40 #endif 41 42 TEST(raw_pwrite_ostreamTest, TestFD) { 43 SmallString<64> Path; 44 int FD; 45 46 // If we want to clean up from a death test, we have to remove the file from 47 // the parent process. Have the parent create the file, pass it via 48 // environment variable to the child, let the child crash, and then remove it 49 // in the parent. 50 const char *ParentPath = getenv("RAW_PWRITE_TEST_FILE"); 51 if (ParentPath) { 52 Path = ParentPath; 53 ASSERT_NO_ERROR(sys::fs::openFileForRead(Path, FD)); 54 } else { 55 ASSERT_NO_ERROR(sys::fs::createTemporaryFile("foo", "bar", FD, Path)); 56 setenv("RAW_PWRITE_TEST_FILE", Path.c_str(), true); 57 } 58 FileRemover Cleanup(Path); 59 60 raw_fd_ostream OS(FD, true); 61 OS << "abcd"; 62 StringRef Test = "test"; 63 OS.pwrite(Test.data(), Test.size(), 0); 64 OS.pwrite(Test.data(), Test.size(), 0); 65 66 #ifdef GTEST_HAS_DEATH_TEST 67 #ifndef NDEBUG 68 EXPECT_DEATH(OS.pwrite("12345", 5, 0), 69 "We don't support extending the stream"); 70 #endif 71 #endif 72 } 73 74 #ifdef LLVM_ON_UNIX 75 TEST(raw_pwrite_ostreamTest, TestDevNull) { 76 int FD; 77 sys::fs::openFileForWrite("/dev/null", FD, sys::fs::CD_OpenExisting); 78 raw_fd_ostream OS(FD, true); 79 OS << "abcd"; 80 StringRef Test = "test"; 81 OS.pwrite(Test.data(), Test.size(), 0); 82 OS.pwrite(Test.data(), Test.size(), 0); 83 } 84 #endif 85 } 86