1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "content/browser/posix_file_descriptor_info_impl.h"
6
7 #include <fcntl.h>
8 #include <unistd.h>
9 #include <utility>
10
11 #include "base/posix/eintr_wrapper.h"
12 #include "testing/gtest/include/gtest/gtest.h"
13
14 namespace {
15
16 // Get a safe file descriptor for test purposes.
17 // TODO(morrita) Merge with things in file_descriptor_set_posix_unittest.cc
GetSafeFd()18 int GetSafeFd() {
19 return open("/dev/null", O_RDONLY);
20 }
21
22 // Returns true if fd was already closed. Closes fd if not closed.
23 // TODO(morrita) Merge with things in file_descriptor_set_posix_unittest.cc
VerifyClosed(int fd)24 bool VerifyClosed(int fd) {
25 const int duped = HANDLE_EINTR(dup(fd));
26 if (duped != -1) {
27 EXPECT_NE(IGNORE_EINTR(close(duped)), -1);
28 EXPECT_NE(IGNORE_EINTR(close(fd)), -1);
29 return false;
30 }
31 return true;
32 }
33
34 } // namespace
35
36 namespace content {
37
38 typedef testing::Test PosixFileDescriptorInfoTest;
39
TEST_F(PosixFileDescriptorInfoTest,Transfer)40 TEST_F(PosixFileDescriptorInfoTest, Transfer) {
41 int testingId = 42;
42 std::unique_ptr<PosixFileDescriptorInfo> target(
43 PosixFileDescriptorInfoImpl::Create());
44 base::ScopedFD fd(GetSafeFd());
45
46 int raw_fd = fd.get();
47 target->Transfer(testingId, std::move(fd));
48 ASSERT_EQ(1U, target->GetMappingSize());
49 ASSERT_EQ(target->GetFDAt(0), raw_fd);
50 ASSERT_EQ(target->GetIDAt(0), testingId);
51
52 target.reset();
53
54 ASSERT_TRUE(VerifyClosed(raw_fd));
55 }
56
TEST_F(PosixFileDescriptorInfoTest,Share)57 TEST_F(PosixFileDescriptorInfoTest, Share) {
58 int testingId = 42;
59 std::unique_ptr<PosixFileDescriptorInfo> target(
60 PosixFileDescriptorInfoImpl::Create());
61 base::ScopedFD fd(GetSafeFd());
62
63 int raw_fd = fd.get();
64 target->Share(testingId, fd.get());
65 ASSERT_EQ(1U, target->GetMappingSize());
66 ASSERT_EQ(target->GetFDAt(0), raw_fd);
67 ASSERT_EQ(target->GetIDAt(0), testingId);
68
69 target.reset();
70
71 ASSERT_TRUE(!VerifyClosed(fd.release()));
72 }
73
TEST_F(PosixFileDescriptorInfoTest,GetMappingWithIDAdjustment)74 TEST_F(PosixFileDescriptorInfoTest, GetMappingWithIDAdjustment) {
75 int testingId1 = 42;
76 int testingId2 = 43;
77 std::unique_ptr<PosixFileDescriptorInfo> target(
78 PosixFileDescriptorInfoImpl::Create());
79
80 target->Transfer(testingId1, base::ScopedFD(GetSafeFd()));
81 target->Transfer(testingId2, base::ScopedFD(GetSafeFd()));
82
83 base::FileHandleMappingVector mapping =
84 target->GetMappingWithIDAdjustment(100);
85 ASSERT_EQ(mapping[0].second, 142);
86 ASSERT_EQ(mapping[1].second, 143);
87 }
88
89 } // namespace content
90