1// Copyright 2014 The Android Open Source Project
2//
3// This software is licensed under the terms of the GNU General Public
4// License version 2, as published by the Free Software Foundation, and
5// may be copied, distributed, and modified under those terms.
6//
7// This program is distributed in the hope that it will be useful,
8// but WITHOUT ANY WARRANTY; without even the implied warranty of
9// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10// GNU General Public License for more details.
11
12#include "android/base/files/ScopedFd.h"
13
14#include <unistd.h>
15#include <fcntl.h>
16
17#include <gtest/gtest.h>
18
19namespace android {
20namespace base {
21
22namespace {
23
24// The path of a file that can always be opened for reading on any platform.
25#ifdef _WIN32
26static const char kNullFile[] = "NUL";
27#else
28static const char kNullFile[] = "/dev/null";
29#endif
30
31int OpenNull() {
32    return ::open(kNullFile, O_RDONLY);
33}
34
35}  // namespace
36
37TEST(ScopedFd, DefaultConstructor) {
38    ScopedFd f;
39    EXPECT_FALSE(f.valid());
40    EXPECT_EQ(-1, f.get());
41}
42
43TEST(ScopedFd, Constructor) {
44    ScopedFd f(OpenNull());
45    EXPECT_TRUE(f.valid());
46}
47
48TEST(ScopedFd, Release) {
49    ScopedFd f(OpenNull());
50    EXPECT_TRUE(f.valid());
51    int fd = f.release();
52    EXPECT_FALSE(f.valid());
53    EXPECT_NE(-1, fd);
54    ::close(fd);
55}
56
57TEST(ScopedFd, Close) {
58    ScopedFd f(OpenNull());
59    EXPECT_TRUE(f.valid());
60    f.close();
61    EXPECT_FALSE(f.valid());
62}
63
64TEST(ScopedFd, Swap) {
65    ScopedFd f1;
66    ScopedFd f2(OpenNull());
67    EXPECT_FALSE(f1.valid());
68    EXPECT_TRUE(f2.valid());
69    f1.swap(&f2);
70    EXPECT_FALSE(f2.valid());
71    EXPECT_TRUE(f1.valid());
72}
73
74
75}  // namespace base
76}  // namespace android
77