1 // Copyright 2020 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "android/base/files/ScopedFd.h"
16
17 #ifndef _MSC_VER
18 #include <unistd.h>
19 #endif
20 #include <fcntl.h>
21
22 #include <gtest/gtest.h>
23
24 namespace android {
25 namespace base {
26
27 namespace {
28
29 // The path of a file that can always be opened for reading on any platform.
30 #ifdef _WIN32
31 static const char kNullFile[] = "NUL";
32 #else
33 static const char kNullFile[] = "/dev/null";
34 #endif
35
OpenNull()36 int OpenNull() {
37 return ::open(kNullFile, O_RDONLY);
38 }
39
40 } // namespace
41
TEST(ScopedFd,DefaultConstructor)42 TEST(ScopedFd, DefaultConstructor) {
43 ScopedFd f;
44 EXPECT_FALSE(f.valid());
45 EXPECT_EQ(-1, f.get());
46 }
47
TEST(ScopedFd,Constructor)48 TEST(ScopedFd, Constructor) {
49 ScopedFd f(OpenNull());
50 EXPECT_TRUE(f.valid());
51 }
52
TEST(ScopedFd,Release)53 TEST(ScopedFd, Release) {
54 ScopedFd f(OpenNull());
55 EXPECT_TRUE(f.valid());
56 int fd = f.release();
57 EXPECT_FALSE(f.valid());
58 EXPECT_NE(-1, fd);
59 ::close(fd);
60 }
61
TEST(ScopedFd,Close)62 TEST(ScopedFd, Close) {
63 ScopedFd f(OpenNull());
64 EXPECT_TRUE(f.valid());
65 f.close();
66 EXPECT_FALSE(f.valid());
67 }
68
TEST(ScopedFd,Swap)69 TEST(ScopedFd, Swap) {
70 ScopedFd f1;
71 ScopedFd f2(OpenNull());
72 EXPECT_FALSE(f1.valid());
73 EXPECT_TRUE(f2.valid());
74 int fd = f2.get();
75 f1.swap(&f2);
76 EXPECT_FALSE(f2.valid());
77 EXPECT_TRUE(f1.valid());
78 EXPECT_EQ(fd, f1.get());
79 }
80
81
82 } // namespace base
83 } // namespace android
84