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/ScopedHandle.h"
13
14#include <gtest/gtest.h>
15
16namespace android {
17namespace base {
18
19namespace {
20
21// The path of a file that can always be opened for reading on any platform.
22static const char kNullFile[] = "NUL";
23
24HANDLE OpenNull() {
25    return ::CreateFile(kNullFile,
26                        GENERIC_READ,
27                        FILE_SHARE_READ|FILE_SHARE_WRITE,
28                        NULL,
29                        OPEN_EXISTING,
30                        FILE_ATTRIBUTE_NORMAL,
31                        NULL);
32}
33
34}  // namespace
35
36TEST(ScopedHandle, DefaultConstructor) {
37    ScopedHandle h;
38    EXPECT_FALSE(h.valid());
39    EXPECT_EQ(INVALID_HANDLE_VALUE, h.get());
40}
41
42TEST(ScopedHandle, Constructor) {
43    ScopedHandle h(OpenNull());
44    EXPECT_TRUE(h.valid());
45}
46
47TEST(ScopedHandle, Release) {
48    ScopedHandle h(OpenNull());
49    EXPECT_TRUE(h.valid());
50    HANDLE handle = h.release();
51    EXPECT_FALSE(h.valid());
52    EXPECT_NE(INVALID_HANDLE_VALUE, handle);
53    ::CloseHandle(handle);
54}
55
56TEST(ScopedHandle, Close) {
57    ScopedHandle h(OpenNull());
58    EXPECT_TRUE(h.valid());
59    h.close();
60    EXPECT_FALSE(h.valid());
61}
62
63TEST(ScopedHandle, Swap) {
64    ScopedHandle h1;
65    ScopedHandle h2(OpenNull());
66    EXPECT_FALSE(h1.valid());
67    EXPECT_TRUE(h2.valid());
68    h1.swap(&h2);
69    EXPECT_FALSE(h2.valid());
70    EXPECT_TRUE(h1.valid());
71}
72
73}  // namespace base
74}  // namespace android
75