2 * Copyright 2016 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/File.h>
19 #include <folly/String.h>
20 #include <folly/portability/Fcntl.h>
22 #include <gtest/gtest.h>
24 using namespace folly;
27 void expectWouldBlock(ssize_t r) {
28 int savedErrno = errno;
30 EXPECT_EQ(EAGAIN, savedErrno) << errnoStr(savedErrno);
32 void expectOK(ssize_t r) {
33 int savedErrno = errno;
34 EXPECT_LE(0, r) << ": errno=" << errnoStr(savedErrno);
39 // Open a file, ensure it's indeed open for reading
43 EXPECT_NE(-1, f.fd());
44 EXPECT_EQ(1, ::read(f.fd(), &buf, 1));
46 EXPECT_EQ(-1, f.fd());
50 TEST(File, SimpleStringPiece) {
52 File f(StringPiece("/etc/hosts"));
53 EXPECT_NE(-1, f.fd());
54 EXPECT_EQ(1, ::read(f.fd(), &buf, 1));
56 EXPECT_EQ(-1, f.fd());
60 // Wrap a file descriptor, make sure that ownsFd works
61 // We'll test that the file descriptor is closed by closing the writing
62 // end of a pipe and making sure that a non-blocking read from the reading
68 int flags = ::fcntl(p[0], F_GETFL);
70 expectOK(::fcntl(p[0], F_SETFL, flags | O_NONBLOCK));
71 expectWouldBlock(::read(p[0], &buf, 1));
74 EXPECT_EQ(p[1], f.fd());
76 // Ensure that moving the file doesn't close it
79 EXPECT_EQ(p[1], f.fd());
80 File f1(std::move(f));
81 EXPECT_EQ(-1, f.fd());
82 EXPECT_EQ(p[1], f1.fd());
84 expectWouldBlock(::read(p[0], &buf, 1)); // not closed
87 EXPECT_EQ(p[1], f.fd());
89 ssize_t r = ::read(p[0], &buf, 1); // eof
96 File in(STDOUT_FILENO, false);
97 CHECK_EQ(STDOUT_FILENO, in.release());
98 CHECK_EQ(-1, in.release());
101 #define EXPECT_CONTAINS(haystack, needle) \
102 EXPECT_NE(::std::string::npos, ::folly::StringPiece(haystack).find(needle)) \
103 << "Haystack: '" << haystack << "'\nNeedle: '" << needle << "'";
105 TEST(File, UsefulError) {
107 File("does_not_exist.txt", 0, 0666);
108 } catch (const std::runtime_error& e) {
109 EXPECT_CONTAINS(e.what(), "does_not_exist.txt");
110 EXPECT_CONTAINS(e.what(), "0666");
115 File temp = File::temporary();
117 EXPECT_TRUE(bool(temp));
125 if (File file = File::temporary()) {
131 EXPECT_FALSE(bool(File()));
135 if (File notOpened = File()) {