Fix copyright lines
[folly.git] / folly / test / FileTest.cpp
index 0111e4b97f5f514922fa8891d8f493ff4993224f..b1163c5845199e633acf1b2644d5375e3f7c1c65 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2013 Facebook, Inc.
+ * Copyright 2013-present Facebook, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * limitations under the License.
  */
 
-#include "folly/File.h"
+#include <folly/File.h>
 
-#include <glog/logging.h>
-#include <gtest/gtest.h>
-
-#include "folly/Benchmark.h"
-#include "folly/String.h"
+#include <folly/String.h>
+#include <folly/portability/Fcntl.h>
+#include <folly/portability/GTest.h>
 
 using namespace folly;
 
@@ -28,13 +26,13 @@ namespace {
 void expectWouldBlock(ssize_t r) {
   int savedErrno = errno;
   EXPECT_EQ(-1, r);
-  EXPECT_EQ(EAGAIN, savedErrno) << errnoStr(errno);
+  EXPECT_EQ(EAGAIN, savedErrno) << errnoStr(savedErrno);
 }
 void expectOK(ssize_t r) {
   int savedErrno = errno;
-  EXPECT_LE(0, r) << ": errno=" << errnoStr(errno);
+  EXPECT_LE(0, r) << ": errno=" << errnoStr(savedErrno);
 }
-}  // namespace
+} // namespace
 
 TEST(File, Simple) {
   // Open a file, ensure it's indeed open for reading
@@ -48,6 +46,15 @@ TEST(File, Simple) {
   }
 }
 
+TEST(File, SimpleStringPiece) {
+  char buf = 'x';
+  File f(StringPiece("/etc/hosts"));
+  EXPECT_NE(-1, f.fd());
+  EXPECT_EQ(1, ::read(f.fd(), &buf, 1));
+  f.close();
+  EXPECT_EQ(-1, f.fd());
+}
+
 TEST(File, OwnsFd) {
   // Wrap a file descriptor, make sure that ownsFd works
   // We'll test that the file descriptor is closed by closing the writing
@@ -84,3 +91,57 @@ TEST(File, OwnsFd) {
   ::close(p[0]);
 }
 
+TEST(File, Release) {
+  File in(STDOUT_FILENO, false);
+  CHECK_EQ(STDOUT_FILENO, in.release());
+  CHECK_EQ(-1, in.release());
+}
+
+#define EXPECT_CONTAINS(haystack, needle) \
+  EXPECT_NE(::std::string::npos, ::folly::StringPiece(haystack).find(needle)) \
+    << "Haystack: '" << haystack << "'\nNeedle: '" << needle << "'";
+
+TEST(File, UsefulError) {
+  try {
+    File("does_not_exist.txt", 0, 0666);
+  } catch (const std::runtime_error& e) {
+    EXPECT_CONTAINS(e.what(), "does_not_exist.txt");
+    EXPECT_CONTAINS(e.what(), "0666");
+  }
+}
+
+TEST(File, Truthy) {
+  File temp = File::temporary();
+
+  EXPECT_TRUE(bool(temp));
+
+  if (temp) {
+    ;
+  } else {
+    ADD_FAILURE();
+  }
+
+  if (File file = File::temporary()) {
+    ;
+  } else {
+    ADD_FAILURE();
+  }
+
+  EXPECT_FALSE(bool(File()));
+  if (File()) {
+    ADD_FAILURE();
+  }
+  if (File notOpened = File()) {
+    ADD_FAILURE();
+  }
+}
+
+TEST(File, HelperCtor) {
+  File::makeFile(StringPiece("/etc/hosts")).then([](File&& f) {
+    char buf = 'x';
+    EXPECT_NE(-1, f.fd());
+    EXPECT_EQ(1, ::read(f.fd(), &buf, 1));
+    f.close();
+    EXPECT_EQ(-1, f.fd());
+  });
+}