2 * Copyright 2013 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 <glog/logging.h>
20 #include <gtest/gtest.h>
22 #include "folly/Benchmark.h"
23 #include "folly/String.h"
25 using namespace folly;
28 void expectWouldBlock(ssize_t r) {
29 int savedErrno = errno;
31 EXPECT_EQ(EAGAIN, savedErrno) << errnoStr(errno);
33 void expectOK(ssize_t r) {
34 int savedErrno = errno;
35 EXPECT_LE(0, r) << ": errno=" << errnoStr(errno);
40 // Open a file, ensure it's indeed open for reading
44 EXPECT_NE(-1, f.fd());
45 EXPECT_EQ(1, ::read(f.fd(), &buf, 1));
47 EXPECT_EQ(-1, f.fd());
52 // Wrap a file descriptor, make sure that ownsFd works
53 // We'll test that the file descriptor is closed by closing the writing
54 // end of a pipe and making sure that a non-blocking read from the reading
60 int flags = ::fcntl(p[0], F_GETFL);
62 expectOK(::fcntl(p[0], F_SETFL, flags | O_NONBLOCK));
63 expectWouldBlock(::read(p[0], &buf, 1));
66 EXPECT_EQ(p[1], f.fd());
68 // Ensure that moving the file doesn't close it
71 EXPECT_EQ(p[1], f.fd());
72 File f1(std::move(f));
73 EXPECT_EQ(-1, f.fd());
74 EXPECT_EQ(p[1], f1.fd());
76 expectWouldBlock(::read(p[0], &buf, 1)); // not closed
79 EXPECT_EQ(p[1], f.fd());
81 ssize_t r = ::read(p[0], &buf, 1); // eof
87 #define EXPECT_CONTAINS(haystack, needle) \
88 EXPECT_NE(::std::string::npos, ::folly::StringPiece(haystack).find(needle)) \
89 << "Haystack: '" << haystack << "'\nNeedle: '" << needle << "'";
91 TEST(File, UsefulError) {
93 File("does_not_exist.txt", 0, 0666);
94 } catch (const std::runtime_error& e) {
95 EXPECT_CONTAINS(e.what(), "does_not_exist.txt");
96 EXPECT_CONTAINS(e.what(), "0666");
101 File temp = File::temporary();
103 EXPECT_TRUE(bool(temp));
111 if (File file = File::temporary()) {
117 EXPECT_FALSE(bool(File()));
121 if (File notOpened = File()) {