From a62a28d1d9c8df7cb77e4bca19814922729b5291 Mon Sep 17 00:00:00 2001
From: Elliott Hughes <enh@google.com>
Date: Wed, 7 May 2014 14:30:33 -0700
Subject: [PATCH] Add basic tests for fsync/fdatasync.

Bug: 14613980
Change-Id: Ie8002c2a1abae07295b7bdb33772764767c03d37
---
 tests/unistd_test.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 43 insertions(+)

diff --git a/tests/unistd_test.cpp b/tests/unistd_test.cpp
index ce0bebadd..2b51aad59 100644
--- a/tests/unistd_test.cpp
+++ b/tests/unistd_test.cpp
@@ -275,3 +275,46 @@ TEST(unistd, clearenv) {
 
   EXPECT_EQ(0, unsetenv("test-variable"));
 }
+
+static void TestFsyncFunction(int (*fn)(int)) {
+  int fd;
+
+  // Can't sync an invalid fd.
+  errno = 0;
+  EXPECT_EQ(-1, fn(-1));
+  EXPECT_EQ(EBADF, errno);
+
+  // It doesn't matter whether you've opened a file for write or not.
+  TemporaryFile tf;
+  ASSERT_NE(-1, tf.fd);
+
+  EXPECT_EQ(0, fn(tf.fd));
+
+  ASSERT_NE(-1, fd = open(tf.filename, O_RDONLY));
+  EXPECT_EQ(0, fn(fd));
+  close(fd);
+
+  ASSERT_NE(-1, fd = open(tf.filename, O_RDWR));
+  EXPECT_EQ(0, fn(fd));
+  close(fd);
+
+  // The fd can even be a directory.
+  ASSERT_NE(-1, fd = open("/", O_RDONLY));
+  EXPECT_EQ(0, fn(fd));
+  close(fd);
+
+  // But some file systems may choose to be fussy...
+  errno = 0;
+  ASSERT_NE(-1, fd = open("/proc/version", O_RDONLY));
+  EXPECT_EQ(-1, fn(fd));
+  EXPECT_EQ(EINVAL, errno);
+  close(fd);
+}
+
+TEST(unistd, fdatasync) {
+  TestFsyncFunction(fdatasync);
+}
+
+TEST(unistd, fsync) {
+  TestFsyncFunction(fsync);
+}